Example #1
0
        private void pickPhysicalDevice()
        {
            int deviceCount = 0;

            Vulkan.vkEnumeratePhysicalDevices(instance, ref deviceCount, null);

            if (deviceCount == 0)
            {
                throw Program.Throw("failed to find GPUs with Vulkan support!");
            }

            VkPhysicalDevice[] devices = new VkPhysicalDevice[deviceCount];
            Vulkan.vkEnumeratePhysicalDevices(instance, ref deviceCount, devices);

            physicalDevice = null;

            foreach (var device in devices)
            {
                if (isDeviceSuitable(device))
                {
                    physicalDevice = device;
                    break;
                }
            }

            if (physicalDevice == null)
            {
                throw Program.Throw("failed to find a suitable GPU!");
            }
        }
Example #2
0
        private void CreateUniformBuffer(VkDevice device, VkPhysicalDevice physicalDevice)
        {
            var bufferSize = Marshal.SizeOf <Transform>();
            VkMemoryPropertyFlags memoryFlags = VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;

            SampleHelpers.CreateBuffer(device, physicalDevice, bufferSize, VkBufferUsageFlags.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, memoryFlags, out m_uniformBuffer, out m_uniformBufferMemory);
        }
Example #3
0
        private void PickPhysicalDevice()
        {
            uint deviceCount = 0;

            Helpers.CheckErrors(VulkanNative.vkEnumeratePhysicalDevices(instance, &deviceCount, null));
            if (deviceCount == 0)
            {
                throw new Exception("Failed to find GPUs with Vulkan support!");
            }

            VkPhysicalDevice *devices = stackalloc VkPhysicalDevice[(int)deviceCount];

            Helpers.CheckErrors(VulkanNative.vkEnumeratePhysicalDevices(instance, &deviceCount, devices));

            for (int i = 0; i < deviceCount; i++)
            {
                var device = devices[i];
                if (this.IsPhysicalDeviceSuitable(device))
                {
                    this.physicalDevice = device;
                    break;
                }
            }

            if (this.physicalDevice == default)
            {
                throw new Exception("failed to find a suitable GPU!");
            }
        }
Example #4
0
        internal GraphicsDevice(Core core, bool validation)
        {
            if (!Glfw.VulkanSupported())
            {
                throw new PlatformNotSupportedException("The Vulkan runtime is not available on this platform");
            }
            Core = core;

            // Create the instance and select the device to use
            InitializeVulkanInstance(validation, out VkInstanceInfo, out VkDebugUtils, out VkDeviceInfo, out Features);
            VkInstance       = VkInstanceInfo.Instance;
            VkPhysicalDevice = VkDeviceInfo.PhysicalDevice;
            LINFO($"Selected device '{VkDeviceInfo.DeviceName}'");

            // Create the device and queue objects
            CreateVulkanDevice(VkDeviceInfo, Features, out VkDevice, out var graphicsQueue, out var graphicsQueueIndex);
            GraphicsQueue = new(this, graphicsQueue, graphicsQueueIndex);
            LINFO("Created Vulkan device instance");
            Limits = new(VkDeviceInfo);

            // Create the memory manager
            Memory = new(this);

            // Create the global binding table for the device
            BindingTable = new(this);

            // Prepare resources
            SamplerPool.Initialize(this);
            Resources = new(this);
        }
Example #5
0
        static void Main(string[] args)
        {
            VkInstance inst;

            using (VkApplicationInfo ai = new VkApplicationInfo()) {
                using (VkInstanceCreateInfo ci = new VkInstanceCreateInfo {
                    pApplicationInfo = ai
                }){
                    CheckResult(vkCreateInstance(ci, IntPtr.Zero, out inst));
                }
            }

            Vk.LoadInstanceFunctionPointers(inst);

            CheckResult(vkEnumeratePhysicalDevices(inst, out uint phyCount, IntPtr.Zero));

            VkPhysicalDevice[] phys = new VkPhysicalDevice[phyCount];

            CheckResult(vkEnumeratePhysicalDevices(inst, out phyCount, phys.Pin()));

            for (int i = 0; i < phys.Length; i++)
            {
                vkGetPhysicalDeviceProperties(phys[i], out VkPhysicalDeviceProperties props);
                Console.WriteLine($"{props.deviceName}");
                Console.WriteLine($"\tdeviceType:   {props.deviceType,20}");
                Console.WriteLine($"\tapiVersion:   {(Version)props.apiVersion,20}");
                Console.WriteLine($"\tdriverVersion:{props.driverVersion,20}");
                Console.WriteLine($"\tvendorID:     {props.vendorID,20}");
            }

            vkDestroyInstance(inst, IntPtr.Zero);
        }
Example #6
0
        static void GetSwapchainFormat(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface)
        {
            uint formatCount = 0;

            vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, null);
            VkSurfaceFormatKHR[] formats = new VkSurfaceFormatKHR[formatCount];

            fixed(VkSurfaceFormatKHR *ptr = &formats[0])
            Assert(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, ptr));



            for (int i = 0; i < formatCount; i++)
            {
                Console.WriteLine($"Format {formats[i].format} {formats[i].colorSpace} is available.");
                for (int k = 0; k < UNORM_FORMATS.Length; k++)
                {
                    if (formats[i].format == UNORM_FORMATS[k])
                    {
                        surfaceFormat = formats[i];
                        return;
                    }
                }
            }

            surfaceFormat = formats[0];//Fallback
        }
Example #7
0
        public static uint getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat *depthFormat)
        {
            // Since all depth formats may be optional, we need to find a suitable depth format to use
            // Start with the highest precision packed format
            List <VkFormat> depthFormats = new List <VkFormat>()
            {
                VkFormat.D32SfloatS8Uint,
                VkFormat.D32Sfloat,
                VkFormat.D24UnormS8Uint,
                VkFormat.D16UnormS8Uint,
                VkFormat.D16Unorm,
            };

            foreach (VkFormat format in depthFormats)
            {
                VkFormatProperties formatProps;
                vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &formatProps);
                // Format must support depth stencil attachment for optimal tiling
                if ((formatProps.optimalTilingFeatures & VkFormatFeatureFlags.DepthStencilAttachment) != 0)
                {
                    *depthFormat = format;
                    return(True);
                }
            }

            return(False);
        }
Example #8
0
        public unsafe Mesh(VkDevice device, VkPhysicalDevice physicalDevice, T[] vertices, uint[] indices)
        {
            this.vertices = new FDataBuffer <T>(device, physicalDevice, vertices.Length, VkBufferUsageFlags.VertexBuffer,
                                                VkSharingMode.Exclusive);
            this.indices = new FDataBuffer <uint>(device, physicalDevice, indices.Length, VkBufferUsageFlags.IndexBuffer, VkSharingMode.Exclusive);

            Span <T> spanv = this.vertices.Map();
            T *      vptr;

            fixed(T *ptr = spanv)
            vptr = ptr;

            Parallel.For(0, vertices.Length, (i) =>
            {
                *(vptr + i) = vertices[i];
            });
            vptr  = null;
            spanv = this.vertices.UnMap();

            Span <uint> spani = this.indices.Map();
            uint *      iptr;

            fixed(uint *ptr = spani)
            iptr = ptr;

            Parallel.For(0, indices.Length, (i) =>
            {
                *(iptr + i) = indices[i];
            });
            iptr  = null;
            spani = this.indices.UnMap();
        }
Example #9
0
        static (uint graphicsFamily, uint presentFamily) FindQueueFamilies(
            VkPhysicalDevice device, VkSurfaceKHR surface)
        {
            var queueFamilies = vkGetPhysicalDeviceQueueFamilyProperties(device);

            uint graphicsFamily = QueueFamilyIgnored;
            uint presentFamily  = QueueFamilyIgnored;
            uint i = 0;

            foreach (var queueFamily in queueFamilies)
            {
                if ((queueFamily.queueFlags & VkQueueFlags.Graphics) != VkQueueFlags.None)
                {
                    graphicsFamily = i;
                }

                vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, out var presentSupport);

                if (presentSupport)
                {
                    presentFamily = i;
                }

                if (graphicsFamily != QueueFamilyIgnored &&
                    presentFamily != QueueFamilyIgnored)
                {
                    break;
                }

                i++;
            }

            return(graphicsFamily, presentFamily);
        }
Example #10
0
        public unsafe QueueFamilyIndices(VkPhysicalDevice device, VkSurfaceKHR surface)
        {
            int graphicsIndex = -1;
            int presentIndex  = -1;

            uint queueFamilyCount = 0;

            VulkanNative.vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, null);
            VkQueueFamilyProperties *queueFamilies = stackalloc VkQueueFamilyProperties[(int)queueFamilyCount];

            VulkanNative.vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies);

            for (int i = 0; i < queueFamilyCount; i++)
            {
                var q = queueFamilies[i];

                if (q.queueCount > 0 && (q.queueFlags & VkQueueFlagBits.VK_QUEUE_GRAPHICS_BIT) != 0)
                {
                    graphicsIndex = i;
                }

                VkBool32 presentSupported = false;
                VkResult result           = VulkanNative.vkGetPhysicalDeviceSurfaceSupportKHR(device, (uint)i, surface, &presentSupported);
                Helpers.CheckErrors(result);
                if (presentIndex < 0 && q.queueCount > 0 && presentSupported)
                {
                    presentIndex = i;
                }
            }

            GraphicsFamily = graphicsIndex;
            PresentFamily  = presentIndex;
        }
Example #11
0
        public static VkResult vkGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, ref int presentModeCount, VkPresentModeKHR[] presentModes)
        {
            VkPreconditions.CheckNull(physicalDevice, nameof(physicalDevice));
            VkPreconditions.CheckNull(surface, nameof(surface));

            return(GetPhysicalDevice(physicalDevice).GetSurfacePresentModes(surface, ref presentModeCount, presentModes));
        }
            static uint GetMemoryTypeIndex(VkPhysicalDevice vulkanPhysicalDevice)
            {
                uint memoryTypeIndex = uint.MaxValue;

                VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties;

                vkGetPhysicalDeviceMemoryProperties(vulkanPhysicalDevice, &physicalDeviceMemoryProperties);

                var memoryTypesCount = physicalDeviceMemoryProperties.memoryTypeCount;
                var memoryTypes      = physicalDeviceMemoryProperties.memoryTypes;

                for (uint index = 0; index < memoryTypesCount; index++)
                {
                    if ((memoryTypes[unchecked ((int)index)].propertyFlags & (uint)VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
                    {
                        memoryTypeIndex = index;
                        break;
                    }
                }

                if (memoryTypeIndex == uint.MaxValue)
                {
                    ThrowInvalidOperationException(nameof(memoryTypeIndex), memoryTypeIndex);
                }
                return(memoryTypeIndex);
            }
Example #13
0
        private bool IsPhysicalDeviceSuitable(VkPhysicalDevice physicalDevice)
        {
            QueueFamilyIndices indices = this.FindQueueFamilies(physicalDevice);

            bool extensionsSupported = this.CheckPhysicalDeviceExtensionSupport(physicalDevice);

            // acquire Raytracing features
            VkPhysicalDeviceRayTracingFeaturesKHR rayTracingFeatures = new VkPhysicalDeviceRayTracingFeaturesKHR()
            {
                sType = VkStructureType.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_FEATURES_KHR,
                pNext = null,
            };

            VkPhysicalDeviceFeatures2 deviceFeatures2 = new VkPhysicalDeviceFeatures2()
            {
                sType = VkStructureType.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
                pNext = &rayTracingFeatures,
            };

            VulkanNative.vkGetPhysicalDeviceFeatures2(physicalDevice, &deviceFeatures2);

            extensionsSupported = extensionsSupported && rayTracingFeatures.rayTracing;

            bool swapChainAdequate = false;

            if (extensionsSupported)
            {
                SwapChainSupportDetails swapChainSupport = this.QuerySwapChainSupport(physicalDevice);
                swapChainAdequate = (swapChainSupport.formats.Length != 0 && swapChainSupport.presentModes.Length != 0);
            }

            return(indices.IsComplete() && extensionsSupported && swapChainAdequate);
        }
Example #14
0
        public unsafe SwapChainSupportDetails(VkPhysicalDevice device, VkSurfaceKHR surface)
        {
            VkSurfaceCapabilitiesKHR capabilitiesKHR;

            VulkanNative.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &capabilitiesKHR);
            capabilities = capabilitiesKHR;
            formats      = null;
            presentModes = null;

            uint formatCount;

            VulkanNative.vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, null);
            if (formatCount > 0)
            {
                formats = new VkSurfaceFormatKHR[formatCount];
                fixed(VkSurfaceFormatKHR *formatsPtr = formats)
                {
                    VulkanNative.vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, formatsPtr);
                }
            }

            uint presentModeCount;

            VulkanNative.vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, null);
            if (presentModeCount > 0)
            {
                presentModes = new VkPresentModeKHR[presentModeCount];
                fixed(VkPresentModeKHR *presentsPtr = presentModes)
                {
                    VulkanNative.vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, presentsPtr);
                }
            }
        }
Example #15
0
        public static VkResult vkGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, out VkSurfaceCapabilitiesKHR capabilities)
        {
            VkPreconditions.CheckNull(physicalDevice, nameof(physicalDevice));
            VkPreconditions.CheckNull(surface, nameof(surface));

            return(GetPhysicalDevice(physicalDevice).GetSurfaceCapabilities(surface, out capabilities));
        }
Example #16
0
        private void CreatePhysicalDevice()
        {
            uint deviceCount = 0;

            vkEnumeratePhysicalDevices(_instance, ref deviceCount, null);
            if (deviceCount == 0)
            {
                throw new InvalidOperationException("No physical devices exist.");
            }

            VkPhysicalDevice[] physicalDevices = new VkPhysicalDevice[deviceCount];
            vkEnumeratePhysicalDevices(_instance, ref deviceCount, ref physicalDevices[0]);
            // Just use the first one.
            _physicalDevice = physicalDevices[0];

            vkGetPhysicalDeviceProperties(_physicalDevice, out _physicalDeviceProperties);
            string deviceName;

            fixed(byte *utf8NamePtr = _physicalDeviceProperties.deviceName)
            {
                deviceName = Encoding.UTF8.GetString(utf8NamePtr, (int)MaxPhysicalDeviceNameSize);
            }

            vkGetPhysicalDeviceFeatures(_physicalDevice, out _physicalDeviceFeatures);

            vkGetPhysicalDeviceMemoryProperties(_physicalDevice, out _physicalDeviceMemProperties);
        }
Example #17
0
        public static VkResult vkGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, ref int formatCount, VkSurfaceFormatKHR[] formats)
        {
            VkPreconditions.CheckNull(physicalDevice, nameof(physicalDevice));
            VkPreconditions.CheckNull(surface, nameof(surface));

            return(GetPhysicalDevice(physicalDevice).GetSurfaceFormats(surface, ref formatCount, formats));
        }
Example #18
0
        private void CreateVertexBuffer(VkDevice device, VkPhysicalDevice physicalDevice)
        {
            // 初期頂点データ.
            var vertices = new Vertex[3] {
                new Vertex()
                {
                    Position = new vec3(-.5f, 0.5f, 0.0f), Color = new vec4(0.0f, 0.0f, 1.0f, 1.0f)
                },
                new Vertex()
                {
                    Position = new vec3(+.5f, 0.5f, 0.0f), Color = new vec4(0.0f, 1.0f, 0.0f, 1.0f)
                },
                new Vertex()
                {
                    Position = new vec3(0.0f, -.5f, 0.0f), Color = new vec4(1.0f, 0.0f, 0.0f, 1.0f)
                },
            };
            var bufferSize = Marshal.SizeOf <Vertex>() * vertices.Length;
            VkMemoryPropertyFlags memoryFlags = VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;

            SampleHelpers.CreateBuffer(device, physicalDevice, bufferSize, VkBufferUsageFlags.VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, memoryFlags, out m_vertexBuffer, out m_vertexBufferMemory);

            // 初期頂点データの書き込み.
            MappedMemoryStream mappedStream;

            VulkanAPI.vkMapMemory(device, m_vertexBufferMemory, 0, VkDeviceSize.VK_WHOLE_SIZE, 0, out mappedStream);
            mappedStream.Write(vertices);
            VulkanAPI.vkUnmapMemory(device, m_vertexBufferMemory);
        }
Example #19
0
        public void CreateCubeModel(VkDevice device, VkPhysicalDevice physicalDevice)
        {
            var cubeVertices = CubeModel.GetVertices();
            var cubeIndices  = CubeModel.GetIndices();
            var vbSize       = Marshal.SizeOf <CubeModel.Vertex>() * cubeVertices.Length;
            var ibSize       = Marshal.SizeOf <ushort>() * cubeIndices.Length;

            VkMemoryPropertyFlags flags = VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;

            SampleHelpers.CreateBuffer(device, physicalDevice, vbSize, VkBufferUsageFlags.VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, flags, out m_vertexBuffer, out m_vertexBufferMemory);
            SampleHelpers.CreateBuffer(device, physicalDevice, ibSize, VkBufferUsageFlags.VK_BUFFER_USAGE_INDEX_BUFFER_BIT, flags, out m_indexBuffer, out m_indexBufferMemory);

            // 初期データの書き込み.
            MappedMemoryStream mapped;

            VulkanAPI.vkMapMemory(device, m_vertexBufferMemory, 0, VkDeviceSize.VK_WHOLE_SIZE, 0, out mapped);
            mapped.Write(cubeVertices);
            VulkanAPI.vkUnmapMemory(device, m_vertexBufferMemory);
            VulkanAPI.vkMapMemory(device, m_indexBufferMemory, 0, VkDeviceSize.VK_WHOLE_SIZE, 0, out mapped);
            mapped.Write(cubeIndices);
            VulkanAPI.vkUnmapMemory(device, m_indexBufferMemory);

            m_resourceManager.Regist(m_vertexBuffer, m_vertexBufferMemory);
            m_resourceManager.Regist(m_indexBuffer, m_indexBufferMemory);
        }
Example #20
0
        private static Mesh <VoxelVertex> _DoGenerateMesh(VkDevice device, VkPhysicalDevice physicalDevice, bool optimize)
        {
            List <Face> faces     = new List <Face>();
            Stopwatch   stopwatch = Stopwatch.StartNew();
            Random      random    = new Random();

            ushort[,,] blocks = new ushort[VoxelRenderChunk.CHUNK_SIZE, VoxelRenderChunk.CHUNK_SIZE, VoxelRenderChunk.CHUNK_SIZE];
            for (int x2 = 0; x2 < VoxelRenderChunk.CHUNK_SIZE; x2++)
            {
                for (int z2 = 0; z2 < VoxelRenderChunk.CHUNK_SIZE; z2++)
                {
                    for (int y2 = 0; y2 < VoxelRenderChunk.CHUNK_SIZE; y2++)
                    {
                        blocks[x2, y2, z2] = (ushort)(random.Next(6));
                    }
                }
            }

            VoxelRenderChunk chunk = new VoxelRenderChunk(blocks);
            Span <ushort>    span = chunk.Span;
            int x = 0, y = 0, z = 0;

            for (int i = 0; i < span.Length; i++)
            {
                if (span[i] != 0)
                {
                    faces.AddRange(GenerateFaces(new Vector3(x, y, z), span[i]));
                }

                z++;
                if (z >= VoxelRenderChunk.CHUNK_SIZE)
                {
                    z = 0;
                    y++;
                    if (y >= VoxelRenderChunk.CHUNK_SIZE)
                    {
                        y = 0;
                        x++;
                    }
                }
            }
            Face[] faceArr = faces.ToArray();
            if (optimize)
            {
                LoopFaces(ref faceArr, Vector3.UnitX);
                LoopFaces(ref faceArr, Vector3.UnitY);
                LoopFaces(ref faceArr, Vector3.UnitZ);
            }

            VoxelVertex[] vertices = new VoxelVertex[faceArr.Length * 4]; uint[] indicies = new uint[faceArr.Length * 6];
            for (uint i = 0; i < faceArr.Length; i++)
            {
                faceArr[i].Generate(ref vertices, ref indicies, i * 4, i * 6);
            }
            stopwatch.Stop();
            Console.WriteLine(((double)stopwatch.ElapsedTicks) / Stopwatch.Frequency * 1000);
            Console.WriteLine($"Vertex Count: {vertices.Length}, Index Count: {indicies.Length}");
            return(new Mesh <VoxelVertex>(device, physicalDevice, vertices.ToArray(), indicies.ToArray()));
        }
Example #21
0
 public FTexture(VkDevice device, VkPhysicalDevice physicalDevice, int cmdPoolID, VkQueue queue, string[] paths,
                 VkFormat format, int width, int height, uint mipLevels = 1)
 {
     MipLevels = mipLevels;
     image     = LoadTexture(device, physicalDevice, cmdPoolID, queue, paths, MipLevels);
     imageView = CreateColourImageArrayView(device, image, paths.Length, format, MipLevels);
     InitMips(device, queue, image, width, height, MipLevels, (uint)paths.Length, cmdPoolID);
 }
Example #22
0
        SwapchainSupport GetSwapchainSupport(VkPhysicalDevice physicalDevice)
        {
            var cap     = surface.GetCapabilities(physicalDevice);
            var formats = surface.GetFormats(physicalDevice);
            var modes   = surface.GetPresentModes(physicalDevice);

            return(new SwapchainSupport(cap, new List <VkSurfaceFormatKHR>(formats), new List <VkPresentModeKHR>(modes)));
        }
Example #23
0
        public static VkResult vkGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice, int queueFamilyIndex, VkSurfaceKHR surface, out bool pSupported)
        {
            VkPreconditions.CheckNull(physicalDevice, nameof(physicalDevice));
            VkPreconditions.CheckNull(surface, nameof(surface));
            VkPreconditions.CheckRange(queueFamilyIndex, 0, int.MaxValue, nameof(queueFamilyIndex));

            return(GetPhysicalDevice(physicalDevice).GetSurfaceSupport(queueFamilyIndex, surface, out pSupported));
        }
Example #24
0
 public static extern VkResult GetPhysicalDeviceImageFormatProperties(
     VkPhysicalDevice physicalDevice,
     VkFormat format,
     VkImageType type,
     VkImageTiling tiling,
     VkImageUsageFlags usage,
     VkImageCreateFlags flags,
     IntPtr pImageFormatProperties
     );
Example #25
0
        public static bool TryAllocateMemoryForBuffer(ulong size, VkDevice device, VkPhysicalDevice pDevice, ref VkMemoryRequirements memoryRequirements, ref VkMemoryPropertyFlags memoryProperties, out ulong offset, out VkDeviceMemory mem)
        {
            if (size > Buffer.LargestBufferSize)
            {
                Buffer.LargestBufferSize = size;
            }

            if (size >= Buffer.LargePooledBufferSize)
            {
                offset = 0;
                mem    = VkDeviceMemory.Null;
                Buffer.PoolMissesDueToSize++;
                return(false);
            }
            else if (size >= Buffer.SmallPooledBufferSize)
            {
                if (BigMemoryPool == VkDeviceMemory.Null)
                {
                    AllocatePool(out BigMemoryPool, ref device, ref pDevice, ref memoryProperties, ref memoryRequirements, Buffer.LargePooledBufferCount * Buffer.LargePooledBufferSize);
                    for (ulong i = 0; i < Buffer.LargePooledBufferCount; i++)
                    {
                        FreeBig.Enqueue(i * Buffer.LargePooledBufferSize);
                    }
                }

                if (FreeBig.TryDequeue(out offset))
                {
                    Buffer.CurrentFreeBigPool = FreeBig.Count;
                    mem = BigMemoryPool;
                    return(true);
                }
            }
            else
            {
                if (SmallMemoryPool == VkDeviceMemory.Null)
                {
                    AllocatePool(out SmallMemoryPool, ref device, ref pDevice, ref memoryProperties, ref memoryRequirements, Buffer.SmallPooledBufferCount * Buffer.SmallPooledBufferSize);
                    for (ulong i = 0; i < Buffer.SmallPooledBufferCount; i++)
                    {
                        FreeSmall.Enqueue(i * Buffer.SmallPooledBufferSize);
                    }
                }

                if (FreeSmall.TryDequeue(out offset))
                {
                    Buffer.CurrentFreeSmallPool = FreeSmall.Count;
                    mem = SmallMemoryPool;
                    return(true);
                }
            }

            offset = 0;
            mem    = VkDeviceMemory.Null;
            Buffer.PoolMissesDueToExaustion++;
            return(false);
        }
Example #26
0
    private static SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface)
    {
        SwapChainSupportDetails details = new SwapChainSupportDetails();

        vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, out details.Capabilities).CheckResult();

        details.Formats      = vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface);
        details.PresentModes = vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface);
        return(details);
    }
Example #27
0
 public static extern void GetPhysicalDeviceSparseImageFormatProperties(
     VkPhysicalDevice physicalDevice,
     VkFormat format,
     VkImageType type,
     VkSampleCountFlags samples,
     VkImageUsageFlags usage,
     VkImageTiling tiling,
     ref uint pPropertyCount,
     IntPtr pProperties
     );
Example #28
0
        private static VkDevice CreateDevice(VkInstance instance, out VkPhysicalDevice physicalDevice,
                                             VkSurfaceKHR surface, out uint queueFamilyIndex)
        {
            queueFamilyIndex = 0;//SHORTCUT computed from queue properties
            physicalDevice   = PickPhysicalDevice(instance, surface, out queueFamilyIndex);

            List <GCHandle> handles            = new List <GCHandle>();
            List <string>   requiredExtensions = new List <string>();

            requiredExtensions.Add("VK_KHR_swapchain");
            string[] extensionNames        = requiredExtensions.ToArray();
            byte[][] pExtensionNames       = new byte[extensionNames.Length][];
            byte *[] ppExtensionNamesArray = new byte *[extensionNames.Length];

            for (int i = 0; i < pExtensionNames.Length; i++)
            {
                pExtensionNames[i] = Encoding.UTF8.GetBytes(extensionNames[i] + char.MinValue);
                GCHandle handle = GCHandle.Alloc(pExtensionNames[i]);
                handles.Add(handle);
                fixed(byte *p = &(((byte[])handle.Target)[0]))
                {
                    ppExtensionNamesArray[i] = p;
                }
            }
            VkDevice device;

            fixed(byte **extensions = &ppExtensionNamesArray[0])
            {
                float[] pQueuePriorities = new float[] { 1.0f };
                VkDeviceQueueCreateInfo deviceQueueCreateInfo = VkDeviceQueueCreateInfo.New();

                deviceQueueCreateInfo.queueFamilyIndex = queueFamilyIndex;
                deviceQueueCreateInfo.queueCount       = 1;

                fixed(float *ptr = &(pQueuePriorities[0]))
                deviceQueueCreateInfo.pQueuePriorities = ptr;

                VkDeviceCreateInfo createInfo = VkDeviceCreateInfo.New();

                createInfo.queueCreateInfoCount    = 1;
                createInfo.pQueueCreateInfos       = &deviceQueueCreateInfo;
                createInfo.ppEnabledExtensionNames = extensions;
                createInfo.enabledExtensionCount   = (uint)extensionNames.Length;

                device = VkDevice.Null;
                Assert(vkCreateDevice(physicalDevice, &createInfo, null, &device));

                foreach (var handle in handles)
                {
                    handle.Free();
                }
            }

            return(device);
        }
Example #29
0
        public VkResourceFactory(VkRenderContext rc)
        {
            RenderContext   = rc;
            _device         = rc.Device;
            _physicalDevice = rc.PhysicalDevice;

            VkCommandPoolCreateInfo commandPoolCI = VkCommandPoolCreateInfo.New();

            commandPoolCI.flags            = VkCommandPoolCreateFlags.None;
            commandPoolCI.queueFamilyIndex = rc.GraphicsQueueIndex;
        }
Example #30
0
        internal VulkanGraphicsAdapter(VulkanGraphicsProvider graphicsProvider, VkPhysicalDevice vulkanPhysicalDevice)
            : base(graphicsProvider)
        {
            AssertNotNull(vulkanPhysicalDevice, nameof(vulkanPhysicalDevice));

            _vulkanPhysicalDevice = vulkanPhysicalDevice;

            _vulkanPhysicalDeviceProperties = new ValueLazy <VkPhysicalDeviceProperties>(GetVulkanPhysicalDeviceProperties);
            _name = new ValueLazy <string>(GetName);

            _ = _state.Transition(to: Initialized);
        }