Example #1
0
        public void Render(IRendererContext context, RenderPasses renderPass, IRenderable r)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (r == null)
            {
                throw new ArgumentNullException(nameof(r));
            }
            var c = (VeldridRendererContext)context;

            ApiUtil.Assert(renderPass == RenderPasses.Standard);
            _imguiRenderer.Render(c.GraphicsDevice, c.CommandList);
            c.CommandList.SetFullScissorRects();
        }
Example #2
0
        static void Main(string[] args)
        {
            _uiManager = new UiManager();

            // Create window, GraphicsDevice, and all resources necessary for the demo.
            VeldridStartup.CreateWindowAndGraphicsDevice(
                new WindowCreateInfo(50, 50, 1000, 720, WindowState.Normal, "FileDialog Demo"),
                new GraphicsDeviceOptions(true, null, true),
                out _window,
                out _gd);

            _window.Resized += _window_Resized;

            _cl = _gd.ResourceFactory.CreateCommandList();

            _controller = new ImGuiRenderer(_gd, _gd.MainSwapchain.Framebuffer.OutputDescription, _window.Width, _window.Height);

            ImGui.StyleColorsLight();

            // Main application loop
            while (_window.Exists)
            {
                InputSnapshot snapshot = _window.PumpEvents();
                if (!_window.Exists)
                {
                    break;
                }
                _controller.Update(1f / 60f, snapshot);

                SubmitUI();

                _cl.Begin();
                _cl.SetFramebuffer(_gd.MainSwapchain.Framebuffer);
                _cl.ClearColorTarget(0, new RgbaFloat(0.5f, 0.5f, 0.5f, 1f));
                _controller.Render(_gd, _cl);
                _cl.End();
                _gd.SubmitCommands(_cl);
                _gd.SwapBuffers(_gd.MainSwapchain);
            }

            // Clean up Veldrid resources
            _gd.WaitForIdle();
            _controller.Dispose();
            _cl.Dispose();
            _gd.Dispose();
        }
Example #3
0
        public void Draw()
        {
            double newElapsed   = mClock.Elapsed.TotalSeconds;
            float  deltaSeconds = (float)(newElapsed - mPreviousElapsed);

            mCommandList.Begin();

            mCommandList.UpdateBuffer(mProjectionBuffer, 0, Matrix4x4.CreatePerspectiveFieldOfView(
                                          1.0f,
                                          (float)mWindow.Width / mWindow.Height,
                                          0.5f,
                                          100f));

            mCommandList.UpdateBuffer(mViewBuffer, 0, Matrix4x4.CreateLookAt(Vector3.UnitZ * 2.5f, Vector3.Zero, Vector3.UnitY));

            Matrix4x4 rotation = Matrix4x4.CreateScale(mScale)
                                 * Matrix4x4.CreateFromAxisAngle(Vector3.UnitZ, mRotation.Z)
                                 * Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, mRotation.Y)
                                 * Matrix4x4.CreateFromAxisAngle(Vector3.UnitX, mRotation.X)
                                 * Matrix4x4.CreateTranslation(mTranslation);

            mCommandList.UpdateBuffer(mWorldBuffer, 0, ref rotation);

            mCommandList.SetFramebuffer(mSwapchain.Framebuffer);
            mCommandList.ClearColorTarget(0, RgbaFloat.Black);
            mCommandList.ClearDepthStencil(1f);
            mCommandList.SetPipeline(mPipeline);
            mCommandList.SetVertexBuffer(0, mVertexBuffer);
            mCommandList.SetIndexBuffer(mIndexBuffer, IndexFormat.UInt16);
            mCommandList.SetGraphicsResourceSet(0, mProjViewSet);
            mCommandList.SetGraphicsResourceSet(1, mWorldTextureSet);
            mCommandList.DrawIndexed(36, 1, 0, 0, 0);

            mImguiRenderer.Render(mGraphicsDevice, mCommandList); // [3]
            mCommandList.End();
            mGraphicsDevice.SubmitCommands(mCommandList);
            mGraphicsDevice.SwapBuffers(mSwapchain);
            mGraphicsDevice.WaitForIdle();

            if (mWindowResized)
            {
                mWindowResized = false;
                mGraphicsDevice.ResizeMainWindow((uint)mWindow.Width, (uint)mWindow.Height);
                mImguiRenderer.WindowResized(mWindow.Width, mWindow.Height);
            }
        }
Example #4
0
        public void Render(IRenderable renderable, CommonSet commonSet, IFramebufferHolder framebuffer, CommandList cl, GraphicsDevice device)
        {
            if (cl == null)
            {
                throw new ArgumentNullException(nameof(cl));
            }
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }
            if (renderable is not DebugGuiRenderable)
            {
                throw new ArgumentException($"{GetType().Name} was passed renderable of unexpected type {renderable?.GetType().Name ?? "null"}", nameof(renderable));
            }

            _imguiRenderer.Render(device, cl);
            cl.SetFullScissorRects();
        }
Example #5
0
        /// <summary>
        /// Handles ImGUI
        /// </summary>
        public override void Draw()
        {
            Graphics.Debug.PushGroup("ImGUI");

            // ImGUI Loop
            ImGuiRenderer.Update(VesselEngine.Instance.DeltaTime, VesselEngine.Instance.Window.InputSnapshot);
            OnGUI?.Invoke();
            ImGuiRenderer.Render(Graphics.veldridGraphicsDevice, Graphics.veldridCommandList);

            // Update viewports
            if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
            {
                ImGui.UpdatePlatformWindows();
                ImGui.RenderPlatformWindowsDefault();
            }

            Graphics.Debug.PopGroup();
        }
Example #6
0
        protected override void Draw(float deltaSeconds)
        {
            ImGuiRenderer.Update(deltaSeconds, this.Host.InputSnapshot);

            if (ImGui.Begin(
                    "Stats",
                    ImGuiWindowFlags.NoSavedSettings
                    | ImGuiWindowFlags.NoTitleBar
                    | ImGuiWindowFlags.NoResize
                    | ImGuiWindowFlags.NoMove
                    | ImGuiWindowFlags.NoBackground
                    ))
            {
                ImGui.SetWindowSize(new Vector2(200, 100));
                ImGui.SetWindowPos(new Vector2(10, 10));

                ImGui.TextColored(new Vector4(0, 0, 0, 1), "Vertices: " + this.shapeGeometry.Shape.Vertices.Length);
                ImGui.TextColored(new Vector4(0, 0, 0, 1), "Indices: " + this.shapeGeometry.Shape.Indices.Length);
                ImGui.TextColored(new Vector4(0, 0, 0, 1), "Triangles: " + this.shapeGeometry.Shape.Indices.Length / 3);
            }

            _ticks += deltaSeconds * 1000f;
            commandList.Begin();

            basicMaterial.Projection = Matrix4x4.CreatePerspectiveFieldOfView(1.0f, HostAspectRatio, 0.5f, 100f);
            basicMaterial.View       = Matrix4x4.CreateLookAt(Vector3.UnitZ * 2.5f, Vector3.Zero, Vector3.UnitY);
            basicMaterial.World      = Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, (_ticks / 1000f)) *
                                       Matrix4x4.CreateFromAxisAngle(Vector3.UnitX, (_ticks / 3000f));

            commandList.SetFramebuffer(DrawingContext.MainSwapchain.Framebuffer);
            commandList.ClearColorTarget(0, RgbaFloat.CornflowerBlue);
            commandList.ClearDepthStencil(1f);

            basicMaterial.Apply(commandList);
            shapeGeometry.Draw(commandList);

            ImGuiRenderer.Render(DrawingContext.GraphicsDevice, commandList);

            commandList.End();

            DrawingContext.GraphicsDevice.SubmitCommands(commandList);
            DrawingContext.GraphicsDevice.SwapBuffers(DrawingContext.MainSwapchain);
            DrawingContext.GraphicsDevice.WaitForIdle();
        }
Example #7
0
 /// <summary>
 /// 目前暂时先使用单个CommandList,在单线程的情况下提交渲染对象
 /// </summary>
 /// <param name="deltaSeconds"></param>
 protected virtual void Draw(float deltaSeconds)
 {
     _cl.Begin();
     _cl.SetFramebuffer(GraphicsDevice.MainSwapchain.Framebuffer);
     _cl.ClearColorTarget(0, RgbaFloat.Black);
     _cl.ClearDepthStencil(1f);
     foreach (var item in renders)
     {
         if (item is RayCastedGlobe)
         {
             continue;
         }
         item.Draw(_cl);
     }
     //最后渲染IMGUI
     _controller.Render(GraphicsDevice, _cl);
     _cl.End();
     GraphicsDevice.SubmitCommands(_cl);
     GraphicsDevice.SwapBuffers(GraphicsDevice.MainSwapchain);
     GraphicsDevice.WaitForIdle();
 }
Example #8
0
        public void Init(string name, int width, int height)
        {
            VeldridStartup.CreateWindowAndGraphicsDevice(
                new WindowCreateInfo(50, 50, width, height, WindowState.Normal, name),
                out _window,
                out _gd);

            _cl = _gd.ResourceFactory.CreateCommandList();

            _ren = new ImGuiRenderer(
                _gd,
                _gd.MainSwapchain.Framebuffer.OutputDescription,
                _window.Width,
                _window.Height);

            _window.Resized += () =>
            {
                _ren.WindowResized(_window.Width, _window.Height);
                _gd.MainSwapchain.Resize((uint)_window.Width, (uint)_window.Height);
            };

            Preload();

            while (_window.Exists)
            {
                var snapshot = _window.PumpEvents();
                _ren.Update(1f / 60f, snapshot);

                SubmitUI();

                _cl.Begin();
                _cl.SetFramebuffer(_gd.MainSwapchain.Framebuffer);
                _cl.ClearColorTarget(0, new RgbaFloat(0, 0, 0.2f, 1f));
                _ren.Render(_gd, _cl);
                _cl.End();
                _gd.SubmitCommands(_cl);
                _gd.SwapBuffers(_gd.MainSwapchain);
            }
        }
Example #9
0
 public void RenderCallback(GraphicsDevice gd, CommandList cl)
 {
     _imguiRenderer.Render(gd, cl);
 }
Example #10
0
        static void Main(string[] args)
        {
            _useOculus = true;
            if (!VRContext.IsOculusSupported())
            {
                _useOculus = false;
                if (!VRContext.IsOpenVRSupported())
                {
                    Console.WriteLine("This sample requires an Oculus or OpenVR-capable headset.");
                    return;
                }
            }

            Sdl2Window window = VeldridStartup.CreateWindow(
                new WindowCreateInfo(
                    Sdl2Native.SDL_WINDOWPOS_CENTERED, Sdl2Native.SDL_WINDOWPOS_CENTERED,
                    1280, 720,
                    WindowState.Normal,
                    "Veldrid.VirtualReality Sample"));

            VRContextOptions options = new VRContextOptions
            {
                EyeFramebufferSampleCount = TextureSampleCount.Count4
            };
            VRContext vrContext = _useOculus ? VRContext.CreateOculus(options) : VRContext.CreateOpenVR(options);

            GraphicsBackend backend = GraphicsBackend.Direct3D11;

            bool debug = false;

#if DEBUG
            debug = true;
#endif

            GraphicsDeviceOptions gdo = new GraphicsDeviceOptions(debug, null, false, ResourceBindingModel.Improved, true, true, true);

            if (backend == GraphicsBackend.Vulkan)
            {
                // Oculus runtime causes validation errors.
                gdo.Debug = false;
            }

            (GraphicsDevice gd, Swapchain sc) = CreateDeviceAndSwapchain(window, vrContext, backend, gdo);
            window.Resized += () => sc.Resize((uint)window.Width, (uint)window.Height);

            vrContext.Initialize(gd);

            ImGuiRenderer igr = new ImGuiRenderer(gd, sc.Framebuffer.OutputDescription, window.Width, window.Height, ColorSpaceHandling.Linear);
            window.Resized += () => igr.WindowResized(window.Width, window.Height);

            AssimpMesh mesh = new AssimpMesh(
                gd,
                vrContext.LeftEyeFramebuffer.OutputDescription,
                Path.Combine(AppContext.BaseDirectory, "cat", "cat.obj"),
                Path.Combine(AppContext.BaseDirectory, "cat", "cat_diff.png"));

            Skybox skybox = new Skybox(
                Image.Load <Rgba32>(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_ft.png")),
                Image.Load <Rgba32>(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_bk.png")),
                Image.Load <Rgba32>(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_lf.png")),
                Image.Load <Rgba32>(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_rt.png")),
                Image.Load <Rgba32>(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_up.png")),
                Image.Load <Rgba32>(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_dn.png")));
            skybox.CreateDeviceObjects(gd, vrContext.LeftEyeFramebuffer.OutputDescription);

            CommandList windowCL = gd.ResourceFactory.CreateCommandList();
            CommandList eyesCL   = gd.ResourceFactory.CreateCommandList();

            MirrorTextureEyeSource eyeSource = MirrorTextureEyeSource.BothEyes;

            Stopwatch sw            = Stopwatch.StartNew();
            double    lastFrameTime = sw.Elapsed.TotalSeconds;

            while (window.Exists)
            {
                double newFrameTime = sw.Elapsed.TotalSeconds;
                double deltaSeconds = newFrameTime - lastFrameTime;
                lastFrameTime = newFrameTime;

                InputSnapshot snapshot = window.PumpEvents();
                if (!window.Exists)
                {
                    break;
                }
                InputTracker.UpdateFrameInput(snapshot, window);
                HandleInputs(deltaSeconds);

                igr.Update(1f / 60f, snapshot);

                if (ImGui.BeginMainMenuBar())
                {
                    if (ImGui.BeginMenu("Settings"))
                    {
                        if (ImGui.BeginMenu("Mirror Texture"))
                        {
                            if (ImGui.MenuItem("Both Eyes", null, eyeSource == MirrorTextureEyeSource.BothEyes))
                            {
                                eyeSource = MirrorTextureEyeSource.BothEyes;
                            }
                            if (ImGui.MenuItem("Left Eye", null, eyeSource == MirrorTextureEyeSource.LeftEye))
                            {
                                eyeSource = MirrorTextureEyeSource.LeftEye;
                            }
                            if (ImGui.MenuItem("Right Eye", null, eyeSource == MirrorTextureEyeSource.RightEye))
                            {
                                eyeSource = MirrorTextureEyeSource.RightEye;
                            }

                            ImGui.EndMenu();
                        }

                        if (ImGui.BeginMenu("VR API"))
                        {
                            if (ImGui.MenuItem("Oculus", null, _useOculus) && !_useOculus)
                            {
                                _useOculus       = true;
                                _switchVRContext = true;
                            }
                            if (ImGui.MenuItem("OpenVR", null, !_useOculus) && _useOculus)
                            {
                                _useOculus       = false;
                                _switchVRContext = true;
                            }

                            ImGui.EndMenu();
                        }

                        ImGui.EndMenu();
                    }

                    ImGui.EndMainMenuBar();
                }

                windowCL.Begin();
                windowCL.SetFramebuffer(sc.Framebuffer);
                windowCL.ClearColorTarget(0, new RgbaFloat(0f, 0f, 0.2f, 1f));
                vrContext.RenderMirrorTexture(windowCL, sc.Framebuffer, eyeSource);
                igr.Render(gd, windowCL);
                windowCL.End();
                gd.SubmitCommands(windowCL);
                gd.SwapBuffers(sc);

                HmdPoseState poses = vrContext.WaitForPoses();

                // Render Eyes
                eyesCL.Begin();

                eyesCL.PushDebugGroup("Left Eye");
                Matrix4x4 leftView = poses.CreateView(VREye.Left, _userPosition, -Vector3.UnitZ, Vector3.UnitY);
                RenderEye(eyesCL, vrContext.LeftEyeFramebuffer, mesh, skybox, poses.LeftEyeProjection, leftView);
                eyesCL.PopDebugGroup();

                eyesCL.PushDebugGroup("Right Eye");
                Matrix4x4 rightView = poses.CreateView(VREye.Right, _userPosition, -Vector3.UnitZ, Vector3.UnitY);
                RenderEye(eyesCL, vrContext.RightEyeFramebuffer, mesh, skybox, poses.RightEyeProjection, rightView);
                eyesCL.PopDebugGroup();

                eyesCL.End();
                gd.SubmitCommands(eyesCL);

                vrContext.SubmitFrame();

                if (_switchVRContext)
                {
                    _switchVRContext = false;
                    vrContext.Dispose();
                    vrContext = _useOculus ? VRContext.CreateOculus() : VRContext.CreateOpenVR();
                    vrContext.Initialize(gd);
                }
            }

            vrContext.Dispose();
            gd.Dispose();
        }
Example #11
0
 public void Render(GraphicsDevice gd, CommandList cl, SceneContext sc, RenderPasses renderPass, IRenderable r)
 {
     Debug.Assert(renderPass == RenderPasses.Standard);
     _imguiRenderer.Render(gd, cl);
     cl.SetFullScissorRects();
 }
Example #12
0
 internal void EndDraw(CommandList commandList)
 {
     ImGui.PopFont();
     imGuiRenderer.Render(graphicsDevice, commandList);
 }
Example #13
0
        public Task Start(WindowCreateInfo wci, GraphicsDeviceOptions graphicsDeviceOptions)
        {
            return(Task.Factory.StartNew(() =>
            {
                _window = VeldridStartup.CreateWindow(ref wci);
                //Window.CursorVisible = false;
                //Window.SetMousePosition(Window.Width / 2, Window.Height / 2);
                _window.Resized += () => _windowResized = true;
                GraphicsDevice = VeldridStartup.CreateGraphicsDevice(_window, graphicsDeviceOptions, GraphicsBackend.Vulkan);
                CommandList = GraphicsDevice.ResourceFactory.CreateCommandList();

                CreateFramebuffer();

                Initialize();

                var imGuiRenderer = new ImGuiRenderer(GraphicsDevice, MainSceneFramebuffer.OutputDescription, _window.Width, _window.Height);

                _windowResized = true;

                Started?.Invoke();

                var frameWatch = Stopwatch.StartNew();

                while (_window.Exists)
                {
                    var inputSnapshot = _window.PumpEvents();

                    if (!_window.Exists)
                    {
                        break;
                    }

                    InputTracker.UpdateFrameInput(_window, inputSnapshot);

                    if (InputTracker.WasKeyDowned(Key.Tilde))
                    {
                        InputTracker.LockMouse = !InputTracker.LockMouse;
                    }
                    //if (InputTracker.WasKeyDowned(Key.T)) { StackedTiming.Enabled = !StackedTiming.Enabled; Timing.Enabled = !Timing.Enabled; }

                    if (_windowResized)
                    {
                        _windowResized = false;
                        GraphicsDevice.ResizeMainWindow((uint)_window.Width, (uint)_window.Height);

                        _projectionMatrix = Matrix4x4.CreatePerspectiveFieldOfView(
                            0.90f,
                            (float)_window.Width / _window.Height,
                            0.4f,
                            512f);
                        if (GraphicsDevice.IsClipSpaceYInverted)
                        {
                            _projectionMatrix *= Matrix4x4.CreateScale(1, -1, 1);
                        }

                        imGuiRenderer.WindowResized(_window.Width, _window.Height);
                    }

                    var frameTime = frameWatch.Elapsed.TotalSeconds;
                    frameTime = Math.Min(frameTime, 0.033333);
                    frameWatch.Restart();

                    imGuiRenderer.Update((float)frameTime, InputTracker.LockMouse ? new EmptyInputSnapshot() : InputTracker.FrameSnapshot);

                    Scene.Update(frameTime);

                    Tick?.Invoke();

                    CommandList.Begin();
                    CommandList.SetFramebuffer(MainSceneFramebuffer);
                    CommandList.ClearColorTarget(0, RgbaFloat.CornflowerBlue);
                    CommandList.ClearDepthStencil(1f);

                    var context = new RenderingContext()
                    {
                        GraphicsDevice = GraphicsDevice,
                        CommandList = CommandList,
                        CameraTransform = CameraTransform,
                        ProjectionMatrix = _projectionMatrix
                    };
                    Scene.Render(context);

                    var displaySize = ImGui.GetIO().DisplaySize;
                    ImGui.GetBackgroundDrawList().AddCircleFilled(displaySize / 2, 2, ImGui.GetColorU32(new Vector4(1, 1, 1, 1)));

                    imGuiRenderer.Render(GraphicsDevice, CommandList);

                    if (_mainSceneColourTexture != null && _mainSceneColourTexture.SampleCount != TextureSampleCount.Count1)
                    {
                        CommandList.ResolveTexture(_mainSceneColourTexture, GraphicsDevice.MainSwapchain.Framebuffer.ColorTargets.First().Target);
                    }

                    CommandList.End();
                    GraphicsDevice.SubmitCommands(CommandList);
                    GraphicsDevice.SwapBuffers(GraphicsDevice.MainSwapchain);
                    GraphicsDevice.WaitForIdle();

                    Resources.Update();
                }
            }, TaskCreationOptions.LongRunning));
        }
 public void Render(GraphicsDevice gd, CommandList cl, GraphicsSystem sc, RenderPasses renderPass)
 {
     Debug.Assert(renderPass == Glitch.Graphics.RenderPasses.Overlay);
     _imguiRenderer.Render(gd, cl);
 }
Example #15
0
 public override void Render(RenderContext rc, SceneContext sc, RenderPasses renderPass)
 {
     Debug.Assert(renderPass == RenderPasses.Overlay);
     _imguiRenderer.Render(rc);
 }
Example #16
0
        static string?Launcher()
        {
            var createInfo = new WindowCreateInfo
            {
                X                  = 100,
                Y                  = 100,
                WindowWidth        = 400,
                WindowHeight       = 150,
                WindowInitialState = WindowState.Normal,
                WindowTitle        = "OpenSAGE Apt Editor"
            };

            VeldridStartup.CreateWindowAndGraphicsDevice(createInfo, out var window, out var outGraphicsDevice);
            using var graphicsDevice           = outGraphicsDevice;
            graphicsDevice.SyncToVerticalBlank = true;
            using var commandList   = graphicsDevice.ResourceFactory.CreateCommandList();
            using var imGuiRenderer = new ImGuiRenderer(graphicsDevice,
                                                        graphicsDevice.MainSwapchain.Framebuffer.OutputDescription,
                                                        window.Width,
                                                        window.Height);
            using var gameTimer = new DeltaTimer();
            string?rootPath      = null;
            var    rootPathInput = new ImGuiTextBox(1024);

            void OnWindowResized()
            {
                graphicsDevice.ResizeMainWindow((uint)window.Width, (uint)window.Height);
                imGuiRenderer.WindowResized(window.Width, window.Height);
            }

            window.Resized += OnWindowResized;
            try
            {
                gameTimer.Start();
                while (rootPath == null)
                {
                    if (!window.Exists)
                    {
                        return(null);
                    }

                    gameTimer.Update();
                    var inputSnapshot = window.PumpEvents();
                    imGuiRenderer.Update((float)gameTimer.CurrentGameTime.DeltaTime.TotalSeconds, inputSnapshot);

                    commandList.Begin();
                    commandList.SetFramebuffer(graphicsDevice.MainSwapchain.Framebuffer);
                    commandList.ClearColorTarget(0, RgbaFloat.Clear);

                    ImGui.SetNextWindowPos(Vector2.Zero);
                    ImGui.SetNextWindowSize(new Vector2(window.Width, window.Height));
                    var open = true;
                    if (ImGui.Begin("Launcher", ref open, ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize))
                    {
                        ImGui.TextWrapped("Start OpenSage Apt Editor by providing a root path.");
                        ImGui.TextWrapped("It's recommended that you set it to " +
                                          "the RA3SDK_UI_ScreensPack folder so you could load apt files more easily.");
                        rootPathInput.InputText("##rootPath", out var inputRootPath);
                        if (ImGui.Button("Load"))
                        {
                            rootPath = inputRootPath;
                            window.Close();
                        }
                    }
                    ImGui.End();

                    imGuiRenderer.Render(graphicsDevice, commandList);
                    commandList.End();
                    graphicsDevice.SubmitCommands(commandList);
                    graphicsDevice.SwapBuffers();
                }
                return(rootPath);
            }
            finally
            {
                window.Resized -= OnWindowResized;
            }
        }
Example #17
0
        public static void Main(string[] args)
        {
            GraphicsBackend?preferredBackend = null;

            ArgumentSyntax.Parse(args, syntax =>
            {
                string preferredBackendString = null;
                syntax.DefineOption("renderer", ref preferredBackendString, false, $"Choose which renderer backend should be used. Valid options: {string.Join(",", Enum.GetNames(typeof(GraphicsBackend)))}");
                if (preferredBackendString != null)
                {
                    if (Enum.TryParse <GraphicsBackend>(preferredBackendString, out var preferredBackendTemp))
                    {
                        preferredBackend = preferredBackendTemp;
                    }
                    else
                    {
                        syntax.ReportError($"Unknown renderer backend: {preferredBackendString}");
                    }
                }
            });

            Platform.Start();

            const int initialWidth  = 1024;
            const int initialHeight = 768;

            using (var window = new GameWindow("OpenSAGE Viewer", 100, 100, initialWidth, initialHeight, preferredBackend))
                using (var commandList = window.GraphicsDevice.ResourceFactory.CreateCommandList())
                    using (var imGuiRenderer = new ImGuiRenderer(window.GraphicsDevice, window.GraphicsDevice.MainSwapchain.Framebuffer.OutputDescription, initialWidth, initialHeight))
                        using (var gameTimer = new GameTimer())
                        {
                            window.ClientSizeChanged += (sender, e) =>
                            {
                                imGuiRenderer.WindowResized(window.ClientBounds.Width, window.ClientBounds.Height);
                            };

                            gameTimer.Start();

                            using (var mainForm = new MainForm(window, imGuiRenderer))
                            {
                                var emptyInputSnapshot = new EmptyInputSnapshot();
                                var isGameViewFocused  = false;

                                while (true)
                                {
                                    commandList.Begin();

                                    gameTimer.Update();

                                    if (!window.PumpEvents())
                                    {
                                        break;
                                    }

                                    commandList.SetFramebuffer(window.GraphicsDevice.MainSwapchain.Framebuffer);

                                    commandList.ClearColorTarget(0, RgbaFloat.Clear);

                                    if (isGameViewFocused)
                                    {
                                        if (window.CurrentInputSnapshot.KeyEvents.Any(x => x.Down && x.Key == Key.Escape))
                                        {
                                            isGameViewFocused = false;
                                        }
                                    }

                                    var inputSnapshot = isGameViewFocused
                            ? emptyInputSnapshot
                            : window.CurrentInputSnapshot;

                                    imGuiRenderer.Update(
                                        (float)gameTimer.CurrentGameTime.ElapsedGameTime.TotalSeconds,
                                        inputSnapshot);

                                    mainForm.Draw(ref isGameViewFocused);

                                    imGuiRenderer.Render(window.GraphicsDevice, commandList);

                                    commandList.End();

                                    window.GraphicsDevice.SubmitCommands(commandList);

                                    window.GraphicsDevice.SwapBuffers();
                                }
                            }
                        }

            Platform.Stop();
        }
Example #18
0
        public static void Run(Options opts)
        {
            GraphicsBackend?preferredBackend = null;

            if (opts.Renderer != Renderer.Default)
            {
                preferredBackend = (GraphicsBackend)opts.Renderer;
            }

            Platform.Start();

            const int initialWidth  = 1024;
            const int initialHeight = 768;

            using (var window = new GameWindow("OpenSAGE Viewer", 100, 100, initialWidth, initialHeight, preferredBackend))
                using (var commandList = window.GraphicsDevice.ResourceFactory.CreateCommandList())
                    using (var imGuiRenderer = new ImGuiRenderer(window.GraphicsDevice, window.GraphicsDevice.MainSwapchain.Framebuffer.OutputDescription, initialWidth, initialHeight))
                        using (var gameTimer = new GameTimer())
                        {
                            window.ClientSizeChanged += (sender, e) =>
                            {
                                imGuiRenderer.WindowResized(window.ClientBounds.Width, window.ClientBounds.Height);
                            };

                            gameTimer.Start();

                            using (var mainForm = new MainForm(window, imGuiRenderer))
                            {
                                var emptyInputSnapshot = new EmptyInputSnapshot();
                                var isGameViewFocused  = false;

                                while (true)
                                {
                                    commandList.Begin();

                                    gameTimer.Update();

                                    if (!window.PumpEvents())
                                    {
                                        break;
                                    }

                                    commandList.SetFramebuffer(window.GraphicsDevice.MainSwapchain.Framebuffer);

                                    commandList.ClearColorTarget(0, RgbaFloat.Clear);

                                    if (isGameViewFocused)
                                    {
                                        if (window.CurrentInputSnapshot.KeyEvents.Any(x => x.Down && x.Key == Key.Escape))
                                        {
                                            isGameViewFocused = false;
                                        }
                                    }

                                    var inputSnapshot = isGameViewFocused
                            ? emptyInputSnapshot
                            : window.CurrentInputSnapshot;

                                    imGuiRenderer.Update(
                                        (float)gameTimer.CurrentGameTime.ElapsedGameTime.TotalSeconds,
                                        inputSnapshot);

                                    mainForm.Draw(ref isGameViewFocused);

                                    imGuiRenderer.Render(window.GraphicsDevice, commandList);

                                    commandList.End();

                                    window.GraphicsDevice.SubmitCommands(commandList);

                                    window.GraphicsDevice.SwapBuffers();
                                }
                            }
                        }

            Platform.Stop();
        }
Example #19
0
        static void Main(string[] args)
        {
            Platform.Start();

            const int initialWidth  = 1024;
            const int initialHeight = 768;

            VeldridStartup.CreateWindowAndGraphicsDevice(
                new WindowCreateInfo(100, 100, initialWidth, initialHeight, WindowState.Normal, "OpenSAGE Big Editor"),
                out var window,
                out var graphicsDevice);

            graphicsDevice.SyncToVerticalBlank = true;

            using (var commandList = graphicsDevice.ResourceFactory.CreateCommandList())
                using (var imGuiRenderer = new ImGuiRenderer(graphicsDevice, graphicsDevice.MainSwapchain.Framebuffer.OutputDescription, initialWidth, initialHeight))
                    using (var gameTimer = new GameTimer())
                    {
                        window.Resized += () =>
                        {
                            graphicsDevice.ResizeMainWindow((uint)window.Width, (uint)window.Height);
                            imGuiRenderer.WindowResized(window.Width, window.Height);
                        };

                        var windowOpen = true;
                        window.Closed += () => windowOpen = false;

                        gameTimer.Start();

                        using (var mainForm = new MainForm())
                        {
                            while (windowOpen)
                            {
                                commandList.Begin();

                                gameTimer.Update();

                                var inputSnapshot = window.PumpEvents();

                                commandList.SetFramebuffer(graphicsDevice.MainSwapchain.Framebuffer);

                                commandList.ClearColorTarget(0, RgbaFloat.Clear);

                                imGuiRenderer.Update(
                                    (float)gameTimer.CurrentGameTime.ElapsedGameTime.TotalSeconds,
                                    inputSnapshot);

                                mainForm.Draw(window);

                                imGuiRenderer.Render(graphicsDevice, commandList);

                                commandList.End();

                                graphicsDevice.SubmitCommands(commandList);

                                graphicsDevice.SwapBuffers();
                            }
                        }
                    }

            graphicsDevice.Dispose();

            Platform.Stop();
        }
Example #20
0
        static void MainImGui(string[] args)
        {
            VeldridStartup.CreateWindowAndGraphicsDevice(
                new WindowCreateInfo(50, 50, 1920, 1080, WindowState.Normal, "ImGui Test"),
                out var window,
                out var gd);

            var cl = gd.ResourceFactory.CreateCommandList();

            // [1]
            var imguiRenderer = new ImGuiRenderer(
                gd,
                gd.MainSwapchain.Framebuffer.OutputDescription,
                window.Width,
                window.Height);

            var io = ImGui.GetIO();
//
//            var data = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(ushort)) * 3);
//            var ranges = new ImVector<ushort>(3, 3, data);
//            ranges[0] = 0xf000;
//            ranges[1] = 0xf3ff;
//            ranges[2] = 0;
//
            var font = io.Fonts.AddFontFromFileTTF("Inconsolata-Regular.ttf", 16);

//            io.Fonts.Build();
            imguiRenderer.RecreateFontDeviceTexture();
            if (!font.IsLoaded())
            {
                throw new Exception("Could not load font");
            }

            var field = typeof(ImGuiRenderer).GetField("_scaleFactor", BindingFlags.Instance | BindingFlags.NonPublic);

            field.SetValue(imguiRenderer, new Vector2(2.5f, 2.5f));

            window.Resized += () =>
            {
                imguiRenderer.WindowResized(window.Width, window.Height);
                gd.MainSwapchain.Resize((uint)window.Width, (uint)window.Height);
            };

            var buffer = new StringBuilder("[ryan@manjaro-xfce-vm-laptop ~]$ ");
//            for (int i = 127; i < 256 + 128; i++)
//                buffer.AppendLine($"{i}: {(char)i}");

            var  nextToggle = DateTime.UtcNow.AddMilliseconds(750);
            bool visible    = true;

            while (window.Exists)
            {
                var snapshot = new InputSnapshotWrapper(window.PumpEvents(), new Vector2(2.5f, 2.5f));
                imguiRenderer.Update(1f / 60f, snapshot); // [2]

                bool scrollToBottom = false;
                foreach (var c in snapshot.KeyCharPresses)
                {
                    buffer.Append(c);
                    scrollToBottom = true;
                }

                foreach (var k in snapshot.KeyEvents)
                {
                    if (k.Down && k.Key == Key.Enter)
                    {
                        buffer.AppendLine();
                        scrollToBottom = true;
                    }
                }

                if (DateTime.UtcNow >= nextToggle)
                {
                    visible    = !visible;
                    nextToggle = nextToggle.AddMilliseconds(750);
                }

                // Draw whatever you want here.
                ImGui.Begin("Test Window", ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoNav);
                ImGui.SetWindowPos(new Vector2(0, 0));
                ImGui.SetWindowSize(new Vector2(window.Width / 2.5f, window.Height / 2.5f));
                {
                    ImGui.PushFont(font);

                    ImGui.TextWrapped(buffer.ToString() + (visible ? '_' : ' '));
                    if (scrollToBottom)
                    {
                        ImGui.SetScrollHereY(1);
                    }
                }

                cl.Begin();
                cl.SetFramebuffer(gd.MainSwapchain.Framebuffer);
                cl.ClearColorTarget(0, new RgbaFloat(0, 0, 0.2f, 1f));
                imguiRenderer.Render(gd, cl); // [3]
                cl.End();
                gd.SubmitCommands(cl);
                gd.SwapBuffers(gd.MainSwapchain);
            }
        }
Example #21
0
 public override void Render(GraphicsDevice gd, CommandList cl, SceneContext sc, RenderPasses renderPass)
 {
     Debug.Assert(renderPass == RenderPasses.Overlay);
     _imguiRenderer.Render(gd, cl);
 }
Example #22
0
 public override void Draw(CommandList commandList)
 {
     _imGuiRenderer.Render(Renderer.GraphicsDevice, commandList);
 }
Example #23
0
        public override void Update()
        {
            var deltaSeconds = Stopwatch.Elapsed.TotalSeconds;
            InfoViewer.Log("Client FPS", Math.Round(1f / deltaSeconds, 2).ToString());

            InfoViewer.Log("Roundtrip", _server?.Roundtrip.ToString());
            InfoViewer.Log("Roundtrip Varience", _server?.RoundtripVarience.ToString());

            Stopwatch.Restart();

            NetworkEvent networkEvent = _client.Poll();
            while (networkEvent.Type != NetworkEventType.Nothing)
            {
                switch (networkEvent.Type)
                {
                    case NetworkEventType.Connect:
                        _server = networkEvent.Connection;
                        break;
                    case NetworkEventType.Data:
                        var diff = _messageTimer.Elapsed.TotalMilliseconds;
                        //InfoViewer.Values["Message Time"] = Math.Round(diff, 4).ToString();
                        _messageTimer.Restart();
                        MessageRecieved(networkEvent.Data);
                        break;
                }
                networkEvent.Recycle();
                networkEvent = _client.Poll();
            }

            _imGuiRenderer.Update((float)deltaSeconds, _window.InputSnapshot);
            var imGuiWantsMouse = ImGuiNET.ImGui.GetIO().WantCaptureMouse;

            var cameraEntities = _camerasSet.GetEntities();
            var cameraTransform = cameraEntities.Length > 0 ? cameraEntities[0].Get<Transform>() : new Transform();

            var inputTrackerTransform = Matrix3x2.CreateTranslation(-_window.Width / 2f, -_window.Height / 2f) *
                Matrix3x2.CreateScale(1 / Settings.GRAPHICS_SCALE, -1 / Settings.GRAPHICS_SCALE) *
                Matrix3x2.CreateScale(1 / _zoom) *
                cameraTransform.Matrix;

            _cameraSpaceInputTracker.SetTransform(inputTrackerTransform);
            _cameraSpaceGameInputTracker.SetActive(!imGuiWantsMouse);

            _zoom += _window.InputSnapshot.WheelDelta * 0.1f;

            PreUpdate(deltaSeconds);
            Scene.Update(new LogicUpdate((float)deltaSeconds, _cameraSpaceGameInputTracker));
            PostUpdate(deltaSeconds);

            var serverMessages = new List<object>();

            _editorMenu.Run(new EditorUpdate()
            {
                CameraSpaceInput = _cameraSpaceInputTracker,
                CameraSpaceGameInput = _cameraSpaceGameInputTracker,
                Scene = Scene,
                ServerMessages = serverMessages
            });

            var clientUpdate = new ClientSystemUpdate()
            {
                Messages = serverMessages,
                Input = _cameraSpaceGameInputTracker
            };

            foreach (var system in _clientSystems)
            {
                system.Update(clientUpdate);
            }

            if(_server != null)
            {
                var messages = SerializeMessages(serverMessages);
                _server.Send(messages, 5, true, _messagesSent++);
            }

            cameraEntities = _camerasSet.GetEntities();
            cameraTransform = cameraEntities.Length > 0 ? cameraEntities[0].Get<Transform>() : new Transform();

            var cameraMatrix = cameraTransform.GetCameraMatrix(Settings.GRAPHICS_SCALE) * Matrix4x4.CreateScale(_zoom);

            var vp = _viewport.Viewport;
            _drawDevice.Begin(cameraMatrix * _viewport.GetScalingTransform(), vp);

            Scene.Render(_drawDevice);

            float gridSize = 20;
            var gridCenter = new Vector2((int)Math.Round(cameraTransform.WorldPosition.X / gridSize) * gridSize, (int)Math.Round(cameraTransform.WorldPosition.Y / gridSize) * gridSize);
            for (int x = -2; x <= 2; x++)
            {
                for (int y = -2; y <= 2; y++)
                {
                    SpriteBatchExtensions.DrawCircle(_drawDevice, (gridCenter + new Vector2(x, y) * gridSize) * Settings.GRAPHICS_SCALE, 0.2f * Settings.GRAPHICS_SCALE, 8, RgbaFloat.Red);
                }
            }

            _drawDevice.Draw();

            _imGuiRenderer.Render(_drawDevice.GraphicsDevice, _drawDevice.CommandList);

            _drawDevice.End();

            _window.GraphicsDevice.SwapBuffers(_window.MainSwapchain);
            _window.GraphicsDevice.WaitForIdle();
        }
Example #24
0
        public Task Start(WindowCreateInfo wci, GraphicsDeviceOptions graphicsDeviceOptions)
        {
            //return Task.Factory.StartNew(() =>
            //{
            AddRenderer(new Renderer()
            {
                RenderWireframes = false
            });

            _window = VeldridStartup.CreateWindow(ref wci);
            //Window.CursorVisible = false;
            //Window.SetMousePosition(Window.Width / 2, Window.Height / 2);
            _window.Resized += () => _windowResized = true;
            _graphicsDevice  = VeldridStartup.CreateGraphicsDevice(_window, graphicsDeviceOptions);
            _commandList     = _graphicsDevice.ResourceFactory.CreateCommandList();
            _renderers.ForEach(r => r.Initialize(_graphicsDevice, _commandList, _window.Width, _window.Height));
            var imGuiRenderer = new ImGuiRenderer(_graphicsDevice, _graphicsDevice.MainSwapchain.Framebuffer.OutputDescription, _window.Width, _window.Height);

            Started?.Invoke();
            var frameWatch      = Stopwatch.StartNew();
            var targetFrameTime = 0.13f;

            while (_window.Exists)
            {
                var inputSnapshot = _window.PumpEvents();

                if (!_window.Exists)
                {
                    break;
                }

                InputTracker.UpdateFrameInput(_window, inputSnapshot);

                if (InputTracker.WasKeyDowned(Key.Escape))
                {
                    break;
                }
                if (InputTracker.WasKeyDowned(Key.Tilde))
                {
                    InputTracker.LockMouse = !InputTracker.LockMouse;
                }
                if (InputTracker.WasKeyDowned(Key.T))
                {
                    StackedTiming.Enabled = !StackedTiming.Enabled; Timing.Enabled = !Timing.Enabled;
                }

                if (_windowResized)
                {
                    _windowResized = false;
                    _graphicsDevice.ResizeMainWindow((uint)_window.Width, (uint)_window.Height);
                    _renderers.ForEach(r => r.WindowResized(_window.Width, _window.Height));
                    imGuiRenderer.WindowResized(_window.Width, _window.Height);
                }

                var frameTime = (float)frameWatch.Elapsed.TotalSeconds;
                frameWatch.Restart();

                imGuiRenderer.Update(frameTime, InputTracker.LockMouse ? new EmptyInputSnapshot() : InputTracker.FrameSnapshot);

                Tick?.Invoke();
                if (NextScene != null)
                {
                    if (CurrentScene != null)
                    {
                        CurrentScene.SceneStopped();
                    }
                    CurrentScene = NextScene;
                    NextScene    = null;
                    CurrentScene.SceneStarted(this);
                }
                if (CurrentScene != null)
                {
                    StackedTiming.PushFrameTimer("Scene Update");
                    CurrentScene.Update(frameTime);
                    StackedTiming.PopFrameTimer();
                }

                _commandList.Begin();

                _commandList.SetFramebuffer(_graphicsDevice.MainSwapchain.Framebuffer);
                //commandList.ClearColorTarget(0, new RgbaFloat(25f / 255, 25f / 255, 112f / 255, 1.0f));
                _commandList.ClearColorTarget(0, RgbaFloat.CornflowerBlue);
                _commandList.ClearDepthStencil(1f);

                StackedTiming.PushFrameTimer("Render");
                if (Camera != null)
                {
                    _renderers.ForEach(r => r.Render(Camera, _graphicsDevice, _commandList, RenderWireframes.SOLID));
                }
                StackedTiming.PopFrameTimer();

                StackedTiming.Render(frameTime);
                Timing.Render(frameTime);

                imGuiRenderer.Render(_graphicsDevice, _commandList);

                _commandList.End();
                _graphicsDevice.SubmitCommands(_commandList);
                _graphicsDevice.SwapBuffers(_graphicsDevice.MainSwapchain);
                _graphicsDevice.WaitForIdle();

                bool jobsRemain = true;
                while (jobsRemain && frameWatch.Elapsed.TotalSeconds < targetFrameTime)
                {
                    jobsRemain = BestEffortFrameQueue.ConsumeActions(1);
                }
            }
            //}, TaskCreationOptions.LongRunning);
            return(Task.CompletedTask);
        }
Example #25
0
        static void GameWindowAdapter(string rootPath)
        {
            var installation = new GameInstallation(new AptEditorDefinition(), rootPath);

            using var game = new Game(installation, null, new Configuration { LoadShellMap = false });
            // should be the ImGui context created by DeveloperModeView
            var initialContext = ImGui.GetCurrentContext();
            var device         = game.GraphicsDevice;
            var window         = game.Window;

            using var imGuiRenderer = new ImGuiRenderer(device,
                                                        game.Panel.OutputDescription,
                                                        window.ClientBounds.Width,
                                                        window.ClientBounds.Height);
            var font = imGuiRenderer.LoadSystemFont("consola.ttf");

            using var commandList = device.ResourceFactory.CreateCommandList();
            var ourContext = ImGui.GetCurrentContext();

            // reset ImGui Context to initial one
            ImGui.SetCurrentContext(initialContext);

            var mainForm = new MainForm(game);

            void OnClientSizeChanged(object?sender, EventArgs args)
            {
                imGuiRenderer.WindowResized(window.ClientBounds.Width, window.ClientBounds.Height);
            }

            void OnRendering2D(object?sender, EventArgs e)
            {
                var previousContext = ImGui.GetCurrentContext();

                ImGui.SetCurrentContext(ourContext);
                try
                {
                    commandList.Begin();
                    commandList.SetFramebuffer(game.Panel.Framebuffer);
                    imGuiRenderer.Update((float)game.RenderTime.DeltaTime.TotalSeconds, window.CurrentInputSnapshot);
                    using (var fontSetter = new ImGuiFontSetter(font))
                    {
                        mainForm.Draw();
                    }
                    imGuiRenderer.Render(game.GraphicsDevice, commandList);
                    commandList.End();
                    device.SubmitCommands(commandList);
                }
                finally
                {
                    ImGui.SetCurrentContext(previousContext);
                }
            }

            window.ClientSizeChanged += OnClientSizeChanged;
            game.RenderCompleted     += OnRendering2D;
            try
            {
                game.ShowMainMenu();
                game.Run();
            }
            finally
            {
                game.RenderCompleted     -= OnRendering2D;
                window.ClientSizeChanged -= OnClientSizeChanged;
            }
        }