Пример #1
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                dev.WaitIdle();

                for (int i = 0; i < swapChain.ImageCount; i++)
                {
                    dev.DestroySemaphore(drawComplete[i]);
                    cmds[i].Free();
                }

                swapChain.Dispose();

                vkDestroySurfaceKHR(instance.Handle, hSurf, IntPtr.Zero);

                cmdPool.Dispose();

                if (disposing)
                {
                    dev.Dispose();
                    instance.Dispose();
                }
                else
                {
                    Debug.WriteLine("a VkWindow has not been correctly disposed");
                }

                Glfw3.DestroyWindow(hWin);
                Glfw3.Terminate();


                isDisposed = true;
            }
        }
Пример #2
0
        private void CreateInstance()
        {
            var enabledLayers = new List <string>();

            if (Instance.EnumerateLayerProperties().Any(x => x.LayerName == "VK_LAYER_LUNARG_standard_validation"))
            {
                enabledLayers.Add("VK_LAYER_LUNARG_standard_validation");
            }

            var glfwExtensions = Glfw3.glfwGetRequiredInstanceExtensions();

            this.instance = Instance.Create(new InstanceCreateInfo
            {
                ApplicationInfo = new ApplicationInfo
                {
                    ApplicationName    = "Ludum Dare 38",
                    ApplicationVersion = new SharpVk.Version(1, 0, 0),
                    EngineName         = "SharpVk",
                    EngineVersion      = Constants.SharpVkVersion,
                    ApiVersion         = Constants.ApiVersion10
                },
                EnabledExtensionNames = glfwExtensions.Concat(new[] { ExtDebugReport.ExtensionName }).ToArray(),
                EnabledLayerNames     = enabledLayers.ToArray()
            }, null);

            this.reportCallback = this.instance.CreateDebugReportCallback(new DebugReportCallbackCreateInfo
            {
                Flags       = DebugReportFlags.Error | DebugReportFlags.Warning,
                PfnCallback = this.debugReportDelegate
            });
        }
Пример #3
0
        /// <summary>
        /// Create a new vulkan enabled window with GLFW.
        /// </summary>
        /// <param name="name">Caption of the window</param>
        /// <param name="_width">Width.</param>
        /// <param name="_height">Height.</param>
        /// <param name="vSync">Vertical synchronisation status for creating the swapchain.</param>
        public VkWindow(string name = "VkWindow", uint _width = 800, uint _height = 600, bool vSync = true)
        {
            Width  = _width;
            Height = _height;
            VSync  = vSync;

            Glfw3.Init();

            Glfw3.WindowHint(WindowAttribute.ClientApi, 0);
            Glfw3.WindowHint(WindowAttribute.Resizable, 1);

            hWin = Glfw3.CreateWindow((int)Width, (int)Height, name, MonitorHandle.Zero, IntPtr.Zero);

            if (hWin == IntPtr.Zero)
            {
                throw new Exception("[GLFW3] Unable to create vulkan Window");
            }

            Glfw3.SetKeyCallback(hWin, HandleKeyDelegate);
            Glfw3.SetMouseButtonPosCallback(hWin, HandleMouseButtonDelegate);
            Glfw3.SetCursorPosCallback(hWin, HandleCursorPosDelegate);
            Glfw3.SetScrollCallback(hWin, HandleScrollDelegate);
            Glfw3.SetCharCallback(hWin, HandleCharDelegate);

            windows.Add(hWin, this);
        }
Пример #4
0
        private void CreateInstance()
        {
            var enabledLayers = new List <string>();

            //VK_LAYER_LUNARG_api_dump
            //VK_LAYER_LUNARG_standard_validation

            void AddAvailableLayer(string layerName)
            {
                if (Instance.EnumerateLayerProperties().Any(x => x.LayerName == layerName))
                {
                    enabledLayers.Add(layerName);
                }
            }

            AddAvailableLayer("VK_LAYER_LUNARG_standard_validation");

            this.instance = Instance.Create(
                enabledLayers.ToArray(),
                Glfw3.GetRequiredInstanceExtensions().Append(ExtExtensions.DebugReport).ToArray(),
                applicationInfo: new ApplicationInfo
            {
                ApplicationName    = "Hello Triangle",
                ApplicationVersion = new Version(1, 0, 0),
                EngineName         = "SharpVk",
                EngineVersion      = new Version(0, 4, 1),
                ApiVersion         = new Version(1, 0, 0)
            });

            instance.CreateDebugReportCallback(DebugReportDelegate, DebugReportFlags.Error | DebugReportFlags.Warning);
        }
Пример #5
0
        private void CreateInstance()
        {
            var enabledLayers = new List <string>();

            if (Instance.EnumerateLayerProperties().Any(x => x.LayerName == "VK_LAYER_LUNARG_standard_validation"))
            {
                enabledLayers.Add("VK_LAYER_LUNARG_standard_validation");
            }

            var glfwExtensions = Glfw3.GetRequiredInstanceExtensions();

            this.instance = Instance.Create(
                enabledLayers.ToArray(),
                glfwExtensions.Append(ExtExtensions.DebugReport).ToArray(),
                applicationInfo: new ApplicationInfo
            {
                ApplicationName    = "Vertex Buffers",
                ApplicationVersion = new Version(1, 0, 0),
                EngineName         = "SharpVk",
                EngineVersion      = new Version(0, 4, 0),
                ApiVersion         = new Version(1, 0, 0)
            });

            instance.CreateDebugReportCallback(DebugReportDelegate, DebugReportFlags.Error | DebugReportFlags.Warning | DebugReportFlags.Information | DebugReportFlags.Debug);
        }
        public void Run()
        {
            var helper = new VkHelperFunctions();

            Glfw3.Init();

            Glfw3.WindowHint(WindowAttribute.ClientApi, 0);
            var window   = Glfw3.CreateWindow(1024, 768, "shit", default, default);
Пример #7
0
 /// <summary>
 /// Set current mouse cursor in the GLFW window.
 /// </summary>
 /// <param name="cursor">New mouse cursor to set.</param>
 public void SetCursor(CursorShape cursor)
 {
     if (currentCursor != IntPtr.Zero)
     {
         Glfw3.DestroyCursor(currentCursor);
     }
     currentCursor = Glfw3.CreateStandardCursor(cursor);
     Glfw3.SetCursor(hWin, currentCursor);
 }
Пример #8
0
        static void Main()
        {
            Glfw3.Init();
            Console.WriteLine($"GLFW3 version: {Glfw3.GetVersion ()}");
            IntPtr win = Glfw3.CreateWindow(100, 100, "test", MonitorHandle.Zero, IntPtr.Zero);

            Glfw3.DestroyWindow(win);
            Glfw3.Terminate();
        }
Пример #9
0
        private void MainLoop()
        {
            while (!Glfw3.WindowShouldClose(this.window))
            {
                this.DrawFrame();

                Glfw3.PollEvents();
            }
        }
Пример #10
0
        private void InitialiseWindow()
        {
            Glfw3.glfwInit();

            Glfw3.glfwWindowHint(0x00022001, 0);
            this.window = Glfw3.glfwCreateWindow(SurfaceWidth, SurfaceHeight, "Vulkan", IntPtr.Zero, IntPtr.Zero);

            this.windowSizeChanged = (x, y, z) => this.RecreateSwapChain();
            Glfw3.glfwSetWindowSizeCallback(this.window, this.windowSizeChanged);
        }
Пример #11
0
        private void InitialiseWindow()
        {
            Glfw3.Init();

            Glfw3.WindowHint(0x00022001, 0);
            this.window             = Glfw3.CreateWindow(SurfaceWidth, SurfaceHeight, "Hello Triangle", IntPtr.Zero, IntPtr.Zero);
            this.windowSizeCallback = (x, y, z) => this.RecreateSwapChain();

            Glfw3.SetWindowSizeCallback(this.window, this.windowSizeCallback);
        }
Пример #12
0
        public GlFwForm(int width, int height, string title, GlfwWindowEventListener eventListener)
        {
            _width            = width;
            _height           = height;
            _title            = title;
            _winEventListener = eventListener;
            //

            SetGlfwWindowHandler(Glfw3.glfwCreateWindow(_width, _height, title, IntPtr.Zero, IntPtr.Zero));
            GlfwAppLoop.RegisterGlfwForm(this);
        }
Пример #13
0
        public override void Initialise(Game game)
        {
            Glfw3.glfwInit();

            Glfw3.glfwWindowHint(0x00022001, 0);
            this.WindowHandle = Glfw3.glfwCreateWindow(1280, 720, this.options.Title, IntPtr.Zero, IntPtr.Zero);

            this.windowSizeChanged = this.OnWindowSizeChanged;
            Glfw3.glfwSetWindowSizeCallback(this.WindowHandle, this.windowSizeChanged);

            this.game = game;
        }
Пример #14
0
 private static void SetCallbacks(Window window)
 {
     Glfw3.SetCharCallback(window.Handle, new CharDelegate((handle, codepoint) =>
                                                           Console.WriteLine("CharDelegate called (codepoint: " + codepoint + ")")));
     Glfw3.SetScrollCallback(window.Handle, new ScrollDelegate((handle, xoffset, yoffset) =>
                                                               Console.WriteLine("ScrollDelegate called (xoffset: " + xoffset + ", yoffset: " + yoffset + ")")));
     Glfw3.SetCursorPosCallback(window.Handle, new CursorPosDelegate((handle, xpos, ypos) =>
                                                                     Console.WriteLine("CursorPosDelegate called (xpos: " + xpos + ", ypos: " + ypos + ")")));
     Glfw3.SetMouseButtonPosCallback(window.Handle, new MouseButtonDelegate((handle, button, action, mods) =>
                                                                            Console.WriteLine("MouseButtonDelegate called (button: " + button + ", action: " +
                                                                                              Enum.GetName(typeof(InputAction), action) + ", mods: " + Enum.GetName(typeof(Modifier), mods) + ")")));
 }
Пример #15
0
        public override void Initialise(Game game)
        {
            Glfw3.Init();

            Glfw3.WindowHint(0x00022001, 0);
            this.WindowHandle = Glfw3.CreateWindow(this.options.InitialWidth, this.options.InitialHeight, this.options.Title, IntPtr.Zero, IntPtr.Zero);

            this.windowSizeChanged = this.OnWindowSizeChanged;
            Glfw3.SetWindowSizeCallback(this.WindowHandle, this.windowSizeChanged);

            this.game = game;
        }
Пример #16
0
        protected virtual void onKeyDown(Key key, int scanCode, Modifier modifiers)
        {
            switch (key)
            {
            case Key.F4:
                if (modifiers == Modifier.Alt)
                {
                    Glfw3.SetWindowShouldClose(currentWindow.hWin, 1);
                }
                break;

            case Key.Escape:
                Glfw3.SetWindowShouldClose(currentWindow.hWin, 1);
                break;

            case Key.Up:
                camera.Move(0, 0, 1);
                break;

            case Key.Down:
                camera.Move(0, 0, -1);
                break;

            case Key.Left:
                camera.Move(1, 0, 0);
                break;

            case Key.Right:
                camera.Move(-1, 0, 0);
                break;

            case Key.PageUp:
                camera.Move(0, 1, 0);
                break;

            case Key.PageDown:
                camera.Move(0, -1, 0);
                break;

            case Key.F3:
                if (camera.Type == Camera.CamType.FirstPerson)
                {
                    camera.Type = Camera.CamType.LookAt;
                }
                else
                {
                    camera.Type = Camera.CamType.FirstPerson;
                }
                break;
            }
            updateViewRequested = true;
        }
Пример #17
0
        public void Update()
        {
            Glfw3.PollEvents();

            if (Glfw3.WindowShouldClose(this.WindowHandle))
            {
                this.game.SignalStop();
            }

            this.IsResized = this.isResizeSignalled;

            this.isResizeSignalled = false;
        }
Пример #18
0
        public static void Start()
        {
            GlfwWindowEventListener winEventListener = new GlfwWindowEventListener();
            var form = new GlFwForm(800, 600, "hello!", winEventListener);

            form.MakeCurrent();

            string versionStr3 = Marshal.PtrToStringAnsi(Glfw3.glfwGetVersionString());


            OpenTK.Platform.Factory.GetCustomPlatformFactory = () => OpenTK.Platform.Egl.EglAngle.NewFactory();
            OpenTK.Toolkit.Init(new OpenTK.ToolkitOptions {
                Backend = OpenTK.PlatformBackend.PreferNative,
            });
            OpenTK.Graphics.PlatformAddressPortal.GetAddressDelegate = OpenTK.Platform.Utilities.CreateGetAddress();

            //-----------
            IntPtr currentContext = Glfw3.glfwGetCurrentContext();
            var    contextHandler = new OpenTK.ContextHandle(currentContext);

            var glfwContext = new GLFWContextForOpenTK(contextHandler);
            var context     = OpenTK.Graphics.GraphicsContext.CreateExternalContext(glfwContext);


            bool isCurrent   = context.IsCurrent;
            var  demoContext = new Mini.GLDemoContext(800, 600);

            demoContext.LoadDemo(new OpenTkEssTest.T108_LionFill());

            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.ClearColor(1, 1, 1, 1);
            //--------------------------------------------------------------------------------
            //setup viewport size
            //set up canvas
            int ww_w = 800;
            int ww_h = 600;
            int max  = Math.Max(ww_w, ww_h);

            GL.Viewport(0, 0, max, max);

            //---------
            form.RenderDel = () =>
            {
                demoContext.Render();
                form.SwapBuffers();
            };
            //---------

            GlfwAppLoop.Run();
        }
Пример #19
0
        /// <summary>
        /// Create the minimum vulkan objects to quickly start a new application. The folowing objects are created:
        /// - Vulkan Instance with extensions present in the `EnabledInstanceExtensions` property.
        /// - Vulkan Surface for the GLFW native window.
        /// - Vulkan device for the selected physical one with configured enabledFeatures and extensions present in `EnabledDeviceExtensions` list. Selection of the default physical device
        ///   may be replaced by the `selectPhysicalDevice` method override.
        /// - Create a default Graphic Queue with presentable support. The default queue creation may be customized by overriding the `createQueues` method.
        /// - Default vulkan Swapchain creation. Some swapchain's parameters are controled through static fields of the `SwapChain` class (ex: `SwapChain.PREFERED_FORMAT`).
        /// - Create a default command pool for the `presentQueue` family index.
        /// - Create an empty command buffer collection (`cmds`).
        /// - Create one unsignaled vulkan semaphore (named `drawComplete` per swapchain image used to control presentation submission to the graphic queue.
        /// - Create a signaled vulkan fence (`drawFence`). (TODO: improve this.
        /// With all these objects, vulkan application programming startup is reduced to the minimal.
        /// </summary>
        protected virtual void initVulkan()
        {
            List <string> instExts = new List <string> (Glfw3.GetRequiredInstanceExtensions());

            if (EnabledInstanceExtensions != null)
            {
                instExts.AddRange(EnabledInstanceExtensions);
            }

            instance = new Instance(instExts.ToArray());

            hSurf = instance.CreateSurface(hWin);

            selectPhysicalDevice();

            VkPhysicalDeviceFeatures enabledFeatures = default;

            configureEnabledFeatures(phy.Features, ref enabledFeatures);

            //First create the c# device class
            dev = new Device(phy);
            dev.debugUtilsEnabled = instance.debugUtilsEnabled;            //store a boolean to prevent testing against the extension string presence.

            //create queue class
            createQueues();

            //activate the device to have effective queues created accordingly to what's available
            dev.Activate(enabledFeatures, EnabledDeviceExtensions);

            swapChain = new SwapChain(presentQueue as PresentQueue, Width, Height, SwapChain.PREFERED_FORMAT,
                                      VSync ? VkPresentModeKHR.FifoKHR : VkPresentModeKHR.ImmediateKHR);
            swapChain.Activate();

            Width  = swapChain.Width;
            Height = swapChain.Height;

            cmdPool = new CommandPool(dev, presentQueue.qFamIndex, VkCommandPoolCreateFlags.ResetCommandBuffer);

            cmds         = new PrimaryCommandBuffer[swapChain.ImageCount];
            drawComplete = new VkSemaphore[swapChain.ImageCount];
            drawFence    = new Fence(dev, true, "draw fence");

            for (int i = 0; i < swapChain.ImageCount; i++)
            {
                drawComplete[i] = dev.CreateSemaphore();
                drawComplete[i].SetDebugMarkerName(dev, "Semaphore DrawComplete" + i);
            }

            cmdPool.SetName("main CmdPool");
        }
Пример #20
0
        private void MainLoop()
        {
            this.initialTimestamp = Stopwatch.GetTimestamp();

            while (!Glfw3.glfwWindowShouldClose(this.window))
            {
                this.device.WaitIdle();

                this.UpdateUniformBuffer();
                this.DrawFrame();

                Glfw3.glfwPollEvents();
            }
        }
Пример #21
0
        public static void Run()
        {
            if (s_mainMsgWin == null)
            {
                return;
            }

            while (!s_mainMsgWin.ShouldClose())
            {
                /* Render here */
                /* Swap front and back buffers */

                s_mainMsgWin.RenderDel?.Invoke();

                /* Poll for and process events */
                //Glfw3.glfwPollEvents();
                Glfw3.glfwWaitEvents();
            }
            Glfw3.glfwTerminate();
        }
Пример #22
0
        /// <summary>
        /// main window loop, exits on GLFW3 exit event. Before entering the rendering loop, the following methods are called:
        /// - initVulkan (device, queues and swapchain creations).
        /// - OnResize (create there your frame buffers couple to the swapchain and trigger the recording of your command buffers for the presentation.
        /// - UpdateView (generaly used when the camera setup has changed to update MVP matrices)
        /// The rendering loop consist of the following steps:
        /// - render (the default one will submit the default command buffers to the presentQueue and trigger a queue present for each swapchain images.
        /// - if the `updateViewRequested` field is set to 'true', call the `UpdateView` method.
        /// - frame counting and chrono.
        /// - if elapsed time reached `UpdateFrequency` value, the `Update` method is called and the elapsed time chrono is reseet.
        /// - GLFW events are polled at the end of the loop.
        /// </summary>
        public virtual void Run()
        {
            initVulkan();

            OnResize();
            UpdateView();

            frameChrono = Stopwatch.StartNew();
            long totTime = 0;

            while (!Glfw3.WindowShouldClose(hWin))
            {
                render();

                if (updateViewRequested)
                {
                    UpdateView();
                }

                frameCount++;

                if (frameChrono.ElapsedMilliseconds > UpdateFrequency)
                {
                    Update();

                    frameChrono.Stop();
                    totTime += frameChrono.ElapsedMilliseconds;
                    fps      = (uint)((double)frameCount / (double)totTime * 1000.0);
                    Glfw3.SetWindowTitle(hWin, "FPS: " + fps.ToString());
                    if (totTime > 2000)
                    {
                        frameCount = 0;
                        totTime    = 0;
                    }
                    frameChrono.Restart();
                }
                Glfw3.PollEvents();
            }
        }
Пример #23
0
        private void CreateInstance()
        {
            var enabledLayers = new List <string>();

            if (Instance.EnumerateLayerProperties().Any(x => x.LayerName == "VK_LAYER_LUNARG_standard_validation"))
            {
                enabledLayers.Add("VK_LAYER_LUNARG_standard_validation");
            }

            var glfwExtensions = Glfw3.GetRequiredInstanceExtensions();

            this.instance = Instance.Create(enabledLayers.ToArray(), glfwExtensions.Concat(new[] { ExtExtensions.DebugReport }).ToArray(), InstanceCreateFlags.None,
                                            new ApplicationInfo
            {
                ApplicationName    = "Tectonic",
                ApplicationVersion = new SharpVk.Version(1, 0, 0),
                EngineName         = "Tectonic",
                ApiVersion         = new SharpVk.Version(1, 0, 0)
            });

            this.reportCallback = this.instance.CreateDebugReportCallback(this.debugReportDelegate, DebugReportFlags.Error | DebugReportFlags.Warning);
        }
Пример #24
0
        public VkWindow(bool debugMarkers = false, string name = "VkWindow", uint _width = 1024, uint _height = 768, bool vSync = false)
        {
            currentWindow = this;

            width  = _width;
            height = _height;

            Glfw3.Init();

            Glfw3.WindowHint(WindowAttribute.ClientApi, 0);
            Glfw3.WindowHint(WindowAttribute.Resizable, 1);

            hWin = Glfw3.CreateWindow((int)width, (int)height, name, MonitorHandle.Zero, IntPtr.Zero);

            Glfw3.SetKeyCallback(hWin, HandleKeyDelegate);
            Glfw3.SetMouseButtonPosCallback(hWin, HandleMouseButtonDelegate);
            Glfw3.SetCursorPosCallback(hWin, HandleCursorPosDelegate);
            Glfw3.SetWindowSizeCallback(hWin, HandleWindowSizeDelegate);
            Glfw3.SetScrollCallback(hWin, HandleScrollDelegate);
            Glfw3.SetCharCallback(hWin, HandleCharDelegate);

            initVulkan(vSync, debugMarkers);
        }
Пример #25
0
        public void CreateInstance()
        {
            var enabledLayers = new List <string>();

            //VK_LAYER_LUNARG_api_dump
            //VK_LAYER_LUNARG_standard_validation
            var prop = Instance.EnumerateLayerProperties();

            void AddAvailableLayer(string layerName, LayerProperties[] prop)
            {
                if (prop.Any(x => x.LayerName == layerName))
                {
                    enabledLayers.Add(layerName);
                }
            }

#if DEBUG
            AddAvailableLayer("VK_LAYER_LUNARG_standard_validation", prop);
#if APIDUMP
            AddAvailableLayer("VK_LAYER_LUNARG_api_dump", prop);
#endif
#endif

            this.instance = Instance.Create(
                enabledLayers.ToArray(),
                Glfw3.GetRequiredInstanceExtensions().Append(ExtExtensions.DebugReport).ToArray(),
                applicationInfo: new ApplicationInfo {
                ApplicationName    = "Hello Triangle",
                ApplicationVersion = new SharpVk.Version(1, 0, 0),
                EngineName         = "SharpVk",
                EngineVersion      = new SharpVk.Version(0, 4, 1),
                ApiVersion         = new SharpVk.Version(1, 0, 0)
            });

            instance.CreateDebugReportCallback(helper.DebugReport, DebugReportFlags.Error | DebugReportFlags.Warning);
        }
Пример #26
0
        private unsafe void Run()
        {
            var extensions = Instance.EnumerateExtensionProperties(null);

            var instance = Instance.Create(null, Glfw3.GetRequiredInstanceExtensions());

            var device = instance.EnumeratePhysicalDevices().First().CreateDevice(new DeviceQueueCreateInfo {
                QueueFamilyIndex = 0, QueuePriorities = new[] { 0f }
            }, null, null);

            device.GetQueue(0, 0);

            try
            {
                Glfw3.Init();

                using (var window = new Window(1920, 1080, "Test"))
                {
                    SetCallbacks(window);

                    while (!window.ShouldClose)
                    {
                        Glfw3.PollEvents();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
            finally
            {
                Glfw3.Terminate();
            }
        }
Пример #27
0
 protected InputAction GetButton(MouseButton button) =>
 Glfw3.GetMouseButton(hWin, button);
Пример #28
0
        public void Render()
        {
            this.DrawFrame();

            Glfw3.PollEvents();
        }
Пример #29
0
 public void AlwaysRun()
 {
     Glfw3.PollEvents();
 }
Пример #30
0
 internal bool ShouldClose()
 {
     return(Glfw3.glfwWindowShouldClose(_glfwWindow) != 0);
 }