Exemple #1
0
 private Pipeline CreatePipeline(
     PipelineShaderStageCreateInfo[] shaderStages,
     VertexInputBindingDescription[] vertexInputBindingDescription,
     VertexInputAttributeDescription[] vertexInputAttributeDescription,
     PipelineLayout pipelineLayout,
     GraphicsPipelineCreateInfo customPipelineProperties = null)
 {
     return(VContext.Instance.device.CreateGraphicsPipelines
            (
                null,
                new GraphicsPipelineCreateInfo[]
     {
         new GraphicsPipelineCreateInfo()
         {
             Stages = shaderStages,
             VertexInputState = new PipelineVertexInputStateCreateInfo()
             {
                 VertexBindingDescriptions = vertexInputBindingDescription,
                 VertexAttributeDescriptions = vertexInputAttributeDescription,
             },
             InputAssemblyState = customPipelineProperties?.InputAssemblyState ?? VContext.Instance.DefaultGraphicsPipelineCreateInfo.InputAssemblyState,
             ViewportState = customPipelineProperties?.ViewportState ?? VContext.Instance.DefaultGraphicsPipelineCreateInfo.ViewportState,
             RasterizationState = customPipelineProperties?.RasterizationState ?? VContext.Instance.DefaultGraphicsPipelineCreateInfo.RasterizationState,
             DepthStencilState = customPipelineProperties?.DepthStencilState ?? VContext.Instance.DefaultGraphicsPipelineCreateInfo.DepthStencilState,
             ColorBlendState = customPipelineProperties?.ColorBlendState ?? VContext.Instance.DefaultGraphicsPipelineCreateInfo.ColorBlendState,
             MultisampleState = customPipelineProperties?.MultisampleState ?? VContext.Instance.DefaultGraphicsPipelineCreateInfo.MultisampleState,
             RenderPass = VContext.Instance.RenderPass,
             Layout = pipelineLayout
         }
     }
            ).First());
 }
Exemple #2
0
        public void CreateComputePipeline()
        {
            var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo(
                new DescriptorSetLayoutBinding(0, DescriptorType.StorageBuffer, 1, ShaderStages.Compute),
                new DescriptorSetLayoutBinding(1, DescriptorType.StorageBuffer, 1, ShaderStages.Compute));

            using (DescriptorSetLayout descriptorSetLayout = Device.CreateDescriptorSetLayout(descriptorSetLayoutCreateInfo))
                using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(new[] { descriptorSetLayout })))
                    using (ShaderModule shader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.comp.spv"))))
                        using (PipelineCache cache = Device.CreatePipelineCache())
                        {
                            var pipelineCreateInfo = new ComputePipelineCreateInfo(
                                new PipelineShaderStageCreateInfo(ShaderStages.Compute, shader, "main"),
                                pipelineLayout);

                            using (Device.CreateComputePipelines(new[] { pipelineCreateInfo })[0]) { }
                            using (Device.CreateComputePipelines(new[] { pipelineCreateInfo }, cache)[0]) { }
                            using (Device.CreateComputePipelines(new[] { pipelineCreateInfo }, allocator: CustomAllocator)[0]) { }
                            using (Device.CreateComputePipelines(new[] { pipelineCreateInfo }, cache, CustomAllocator)[0]) { }
                            using (Device.CreateComputePipeline(pipelineCreateInfo)) { }
                            using (Device.CreateComputePipeline(pipelineCreateInfo, allocator: CustomAllocator)) { }
                            using (Device.CreateComputePipeline(pipelineCreateInfo, cache)) { }
                            using (Device.CreateComputePipeline(pipelineCreateInfo, cache, CustomAllocator)) { }
                        }
        }
        public EnvironmentCube(string cubemapPath, PipelineLayout plLayout, Queue staggingQ, RenderPass renderPass, PipelineCache cache = null)
            : base(renderPass, cache, "EnvCube pipeline")
        {
            using (GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, renderPass.Samples, false)) {
                cfg.RenderPass = renderPass;
                cfg.Layout     = plLayout;
                cfg.AddVertexBinding(0, 3 * sizeof(float));
                cfg.AddVertexAttributes(0, VkFormat.R32g32b32Sfloat);
                cfg.AddShaders(
                    new ShaderInfo(Dev, VkShaderStageFlags.Vertex, "#EnvironmentPipeline.skybox.vert.spv"),
                    new ShaderInfo(Dev, VkShaderStageFlags.Fragment, STR_FRAG_PATH)
                    );

                cfg.multisampleState.rasterizationSamples = Samples;

                layout = cfg.Layout;

                init(cfg);
            }

            using (CommandPool cmdPool = new CommandPool(staggingQ.Dev, staggingQ.index)) {
                vboSkybox = new GPUBuffer <float> (staggingQ, cmdPool, VkBufferUsageFlags.VertexBuffer, box_vertices);

                cubemap = KTX.KTX.Load(staggingQ, cmdPool, cubemapPath,
                                       VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true);
                cubemap.CreateView(VkImageViewType.Cube, VkImageAspectFlags.Color);
                cubemap.CreateSampler(VkSamplerAddressMode.ClampToEdge);
                cubemap.SetName("skybox Texture");
                cubemap.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal;

                generateBRDFLUT(staggingQ, cmdPool);
                generateCubemaps(staggingQ, cmdPool);
            }
        }
Exemple #4
0
        public override void Initialise(Device device, VulkanBufferManager bufferManager)
        {
            this.vertexShader = device.CreateVertexModule(shanq => from input in shanq.GetInput <Vertex>()
                                                          select new VertexOutput
            {
                Colour   = input.Colour,
                Position = new vec4(input.Position, 0, 1)
            });

            this.fragmentShader = device.CreateFragmentModule(shanq => from input in shanq.GetInput <FragmentInput>()
                                                              select new FragmentOutput
            {
                Colour = new vec4(input.Colour, 1)
            });

            indexCount = indices.Count();

            this.vertexBuffer = bufferManager.CreateBuffer((uint)Marshal.SizeOf <Vertex>() * (uint)vertices.Length, BufferUsageFlags.TransferDestination | BufferUsageFlags.VertexBuffer, MemoryPropertyFlags.DeviceLocal);

            this.vertexBuffer.Update(vertices);

            this.indexBuffer = bufferManager.CreateBuffer((uint)Marshal.SizeOf <uint>() * (uint)indices.Length, BufferUsageFlags.TransferDestination | BufferUsageFlags.IndexBuffer, MemoryPropertyFlags.DeviceLocal);

            this.indexBuffer.Update(indices);

            this.pipelineLayout = device.CreatePipelineLayout(null, null);
        }
Exemple #5
0
        protected Pipeline[] CreatePipelines(PipelineLayout pipelineLayout, RenderPass renderPass, PipelineShaderStageCreateInfo[] shaderStageCreateInfos, VertexData vertexData)
        {
            var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo(PrimitiveTopology.TriangleList, false);

            var vertexInputState = new PipelineVertexInputStateCreateInfo(vertexData.BindingDescriptions, vertexData.AttributeDescriptions);

            var rasterizationState = new PipelineRasterizationStateCreateInfo();

            //rasterizationState.RasterizerDiscardEnable = true;
            rasterizationState.LineWidth = 1;

            //PipelineDepthStencilStateCreateInfo
            //PipelineDynamicStateCreateInfo
            //viewportState
            var createInfos = new[]
            {
                new GraphicsPipelineCreateInfo(shaderStageCreateInfos, vertexInputState, inputAssemblyState, rasterizationState, pipelineLayout, renderPass, 0, 0)
                {
                    ViewportState    = new PipelineViewportStateCreateInfo(),
                    MultisampleState = new PipelineMultisampleStateCreateInfo()
                    {
                        RasterizationSamples = SampleCountFlags.SampleCountFlags1
                    }
                }
            };

            return(device.CreateGraphicsPipelines(null, createInfos));
        }
Exemple #6
0
        public void GetData()
        {
            var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo(
                new DescriptorSetLayoutBinding(0, DescriptorType.StorageBuffer, 1, ShaderStages.Compute),
                new DescriptorSetLayoutBinding(1, DescriptorType.StorageBuffer, 1, ShaderStages.Compute));

            using (DescriptorSetLayout descriptorSetLayout = Device.CreateDescriptorSetLayout(descriptorSetLayoutCreateInfo))
                using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(new[] { descriptorSetLayout })))
                    using (ShaderModule shader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.comp.spv"))))
                    {
                        var pipelineCreateInfo = new ComputePipelineCreateInfo(
                            new PipelineShaderStageCreateInfo(ShaderStages.Compute, shader, "main"),
                            pipelineLayout);

                        byte[] cacheBytes;

                        // Populate cache.
                        using (PipelineCache cache = Device.CreatePipelineCache())
                        {
                            using (Device.CreateComputePipeline(pipelineCreateInfo, cache)) { }
                            cacheBytes = cache.GetData();
                        }

                        Assert.False(cacheBytes.All(x => x == 0));

                        // Recreate pipeline from cache.
                        using (PipelineCache cache = Device.CreatePipelineCache(new PipelineCacheCreateInfo(cacheBytes)))
                        {
                            using (Device.CreateComputePipeline(pipelineCreateInfo, cache)) { }
                        }
                    }
        }
Exemple #7
0
        public void CmdDraw()
        {
            var renderPassCreateInfo = new RenderPassCreateInfo(new[] { new SubpassDescription(
                                                                            new[] { new AttachmentReference(0, ImageLayout.ColorAttachmentOptimal) }) },
                                                                new[] { new AttachmentDescription {
                                                                            Format = Format.B8G8R8A8UNorm, Samples = SampleCounts.Count1
                                                                        } });
            var imageCreateInfo = new ImageCreateInfo
            {
                Usage       = ImageUsages.ColorAttachment,
                Format      = Format.B8G8R8A8UNorm,
                Extent      = new Extent3D(2, 2, 1),
                ImageType   = ImageType.Image2D,
                MipLevels   = 1,
                ArrayLayers = 1,
                Samples     = SampleCounts.Count1
            };
            var imageViewCreateInfo = new ImageViewCreateInfo(
                Format.B8G8R8A8UNorm,
                new ImageSubresourceRange(ImageAspects.Color, 0, 1, 0, 1));

            using (ShaderModule vertexShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.vert.spv"))))
                using (ShaderModule fragmentShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.frag.spv"))))
                    using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout())
                        using (RenderPass renderPass = Device.CreateRenderPass(renderPassCreateInfo))
                            using (Image image = Device.CreateImage(imageCreateInfo))
                            {
                                MemoryRequirements imageMemReq = image.GetMemoryRequirements();
                                int memTypeIndex = PhysicalDeviceMemoryProperties.MemoryTypes.IndexOf(imageMemReq.MemoryTypeBits, MemoryProperties.DeviceLocal);
                                using (DeviceMemory imageMemory = Device.AllocateMemory(new MemoryAllocateInfo(imageMemReq.Size, memTypeIndex)))
                                {
                                    image.BindMemory(imageMemory);
                                    using (ImageView imageView = image.CreateView(imageViewCreateInfo))
                                        using (Framebuffer framebuffer = renderPass.CreateFramebuffer(new FramebufferCreateInfo(new[] { imageView }, 2, 2)))
                                            using (Pipeline pipeline = Device.CreateGraphicsPipeline(new GraphicsPipelineCreateInfo(
                                                                                                         pipelineLayout,
                                                                                                         renderPass,
                                                                                                         0,
                                                                                                         new[]
                                            {
                                                new PipelineShaderStageCreateInfo(ShaderStages.Vertex, vertexShader, "main"),
                                                new PipelineShaderStageCreateInfo(ShaderStages.Fragment, fragmentShader, "main")
                                            },
                                                                                                         new PipelineInputAssemblyStateCreateInfo(),
                                                                                                         new PipelineVertexInputStateCreateInfo(),
                                                                                                         new PipelineRasterizationStateCreateInfo {
                                                RasterizerDiscardEnable = true, LineWidth = 1.0f
                                            })))
                                            {
                                                CommandBuffer.Begin();
                                                CommandBuffer.CmdBeginRenderPass(new RenderPassBeginInfo(framebuffer, new Rect2D(0, 0, 2, 2)));
                                                CommandBuffer.CmdBindPipeline(PipelineBindPoint.Graphics, pipeline);
                                                CommandBuffer.CmdDraw(3);
                                                CommandBuffer.CmdEndRenderPass();
                                                CommandBuffer.End();
                                            }
                                }
                            }
        }
        protected LayoutsExample() : base()
        {
            DescriptorSetLayouts = CreateDescriptorSetLayouts();

            GraphicsPipelineLayout = CreatePipelineLayout();

            //VkApi.descriptors
        }
Exemple #9
0
 public void Draw(CommandBuffer cmd, PipelineLayout pipelineLayout, Scene scene, bool shadowPass = false)
 {
     if (scene.Root == null)
     {
         return;
     }
     RenderNode(cmd, pipelineLayout, scene.Root, Matrix4x4.Identity, shadowPass);
 }
Exemple #10
0
        private void TearDown()
        {
            device.WaitIdle();

            renderFinishedSemaphore.Dispose();
            renderFinishedSemaphore = null;

            imageAvailableSemaphore.Dispose();
            imageAvailableSemaphore = null;

            vertexBufferMemory.Free();
            vertexBufferMemory = null;

            vertexBuffer.Dispose();
            vertexBuffer = null;

            commandPool.Dispose();
            commandPool = null;

            foreach (var frameBuffer in frameBuffers)
            {
                frameBuffer.Dispose();
            }
            frameBuffers = null;

            fragShader.Dispose();
            fragShader = null;

            vertShader.Dispose();
            vertShader = null;

            pipeline.Dispose();
            pipeline = null;

            pipelineLayout.Dispose();
            pipelineLayout = null;

            foreach (var imageView in swapChainImageViews)
            {
                imageView.Dispose();
            }
            swapChainImageViews = null;

            renderPass.Dispose();
            renderPass = null;

            swapChain.Dispose();
            swapChain = null;

            device.Dispose();
            device = null;

            surface.Dispose();
            surface = null;

            instance.Dispose();
            instance = null;
        }
Exemple #11
0
 public void DrawAll(CommandBuffer cmd, PipelineLayout pipelineLayout, bool shadowPass = false)
 {
     foreach (Scene sc in Scenes)
     {
         foreach (Node node in sc.Root.Children)
         {
             RenderNode(cmd, pipelineLayout, node, sc.Root.localMatrix, shadowPass);
         }
     }
 }
Exemple #12
0
        //private void CreateGraphicsPipeline()
        //{
        //	var bindingDescription = Vertex.GetBindingDescription();
        //	var attributeDescriptions = Vertex.GetAttributeDescriptions();

        //	pipelineLayout = device.CreatePipelineLayout(null, null);

        //	pipeline = device.CreateGraphicsPipeline(
        //		null,
        //		new[]
        //		{
        //			new PipelineShaderStageCreateInfo
        //			{
        //				Stage = ShaderStageFlags.Vertex,
        //				Module = vertShader,
        //				Name = "main"
        //			},
        //			new PipelineShaderStageCreateInfo
        //			{
        //				Stage = ShaderStageFlags.Fragment,
        //				Module = fragShader,
        //				Name = "main"
        //			}
        //		},
        //		new PipelineRasterizationStateCreateInfo
        //		{
        //			DepthClampEnable = false,
        //			RasterizerDiscardEnable = false,
        //			PolygonMode = PolygonMode.Fill,
        //			LineWidth = 1,
        //			CullMode = CullModeFlags.Back,
        //			FrontFace = FrontFace.Clockwise,
        //			DepthBiasEnable = false
        //		},
        //		pipelineLayout,
        //		renderPass,
        //		0,
        //		null,
        //		-1,
        //		vertexInputState: new PipelineVertexInputStateCreateInfo(),
        //		inputAssemblyState: new PipelineInputAssemblyStateCreateInfo
        //		{
        //			PrimitiveRestartEnable = false,
        //			Topology = PrimitiveTopology.TriangleList
        //		},
        //		viewportState: new PipelineViewportStateCreateInfo
        //		{
        //			Viewports = new[]
        //			{
        //				new Viewport(0f, 0f, swapChainExtent.Width, swapChainExtent.Height, 0, 1)
        //			},
        //			Scissors = new[]
        //			{
        //				new Rect2D(swapChainExtent)
        //			}
        //		},
        //		colorBlendState: new PipelineColorBlendStateCreateInfo
        //		{
        //			Attachments = new[]
        //			{
        //				new PipelineColorBlendAttachmentState
        //				{
        //					ColorWriteMask = ColorComponentFlags.R | ColorComponentFlags.G | ColorComponentFlags.B | ColorComponentFlags.A,
        //					BlendEnable = false
        //				}
        //			},
        //			LogicOpEnable = false
        //		},
        //		multisampleState: new PipelineMultisampleStateCreateInfo
        //		{
        //			SampleShadingEnable = false,
        //			RasterizationSamples = SampleCountFlags.SampleCount1,
        //			MinSampleShading = 1
        //		}
        //	);
        //}

        private void CreateGraphicsPipeline()
        {
            var bindingDescription    = Vertex.GetBindingDescription();
            var attributeDescriptions = Vertex.GetAttributeDescriptions();

            pipelineLayout = device.CreatePipelineLayout(null, null);

            pipeline = device.CreateGraphicsPipelines(
                null,
                new[]
        void CreateComputePipeline()
        {
            /*
             * We create a compute pipeline here.
             */

            /*
             * Create a shader module. A shader module basically just encapsulates some shader code.
             */
            // the code in comp.spv was created by running the command:
            // glslangValidator.exe -V shader.comp
            byte[] code = ReadFile("shaders/shader.comp.spv");
            ShaderModuleCreateInfo createInfo = new ShaderModuleCreateInfo()
            {
                Code = code
            };

            computeShaderModule = device.CreateShaderModule(createInfo);

            /*
             * Now let us actually create the compute pipeline.
             * A compute pipeline is very simple compared to a graphics pipeline.
             * It only consists of a single stage with a compute shader.
             * So first we specify the compute shader stage, and it's entry point(main).
             */
            PipelineShaderStageCreateInfo shaderStageCreateInfo = new PipelineShaderStageCreateInfo()
            {
                Stage  = ShaderStages.Compute,// VK_SHADER_STAGE_COMPUTE_BIT;
                Module = computeShaderModule,
                Name   = "main"
            };

            /*
             * The pipeline layout allows the pipeline to access descriptor sets.
             * So we just specify the descriptor set layout we created earlier.
             */
            PipelineLayoutCreateInfo pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo(new[] { descriptorSetLayout });

            pipelineLayout = device.CreatePipelineLayout(pipelineLayoutCreateInfo);

            ComputePipelineCreateInfo pipelineCreateInfo = new ComputePipelineCreateInfo()
            {
                Stage  = shaderStageCreateInfo,
                Layout = pipelineLayout
            };

            /*
             * Now, we finally create the compute pipeline.
             */
            ComputePipelineCreateInfo[] ci = { pipelineCreateInfo };
            pipelines = device.CreateComputePipelines(ci);
        }
Exemple #14
0
        private void CreateComputePipeline()
        {
            var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo(new[] { _descriptorSetLayout });

            _pipelineLayout = Device.Logical.CreatePipelineLayout(pipelineLayoutCreateInfo);

            using (ShaderModule shader = Device.Logical.CreateShaderModule(new ShaderModuleCreateInfo(SpirV)))
            {
                var computePipelineCreateInfo = new ComputePipelineCreateInfo(
                    new PipelineShaderStageCreateInfo(ShaderStages.Compute, shader, "main"),
                    _pipelineLayout);
                _pipeline = Device.Logical.CreateComputePipeline(computePipelineCreateInfo);
            }
        }
Exemple #15
0
        public void Push(CommandBuffer commandBuffer, PipelineLayout pipelineLayout)
        {
            //If there is no data added then there is no need to push
            if (entries.Count == 0)
            {
                return;
            }

            commandBuffer.CmdPushConstants(
                pipelineLayout,
                stages,
                offset: 0,
                size: (int)currentSize,
                values: memory.Pointer);
        }
 private Pipeline CreateComputePipeline(
     PipelineShaderStageCreateInfo shaderStage,
     PipelineLayout pipelineLayout)
 {
     return(VContext.Instance.device.CreateComputePipelines(
                null,
                new ComputePipelineCreateInfo[]
     {
         new ComputePipelineCreateInfo()
         {
             Layout = pipelineLayout,
             Stage = shaderStage,
         }
     }
                ).First());
 }
        public void Build()
        {
            DescriptorSetLayout?.Dispose();
            PipelineLayout?.Dispose();
            //UsingSamplers?.DisposeRange();
            DescriptorPool?.Dispose();
            RenderPass?.Dispose();
            Pipeline?.Dispose();

            DescriptorSetLayout = VKHelper.CreateDescriptorSetLayout(Graphics, DescriptorItems);
            PipelineLayout      = VKHelper.CreatePipelineLayout(Graphics, DescriptorSetLayout);
            DescriptorPool      = VKHelper.CreateDescriptorPool(Graphics, DescriptorItems);
            DescriptorSet       = VKHelper.CreateDescriptorSet(DescriptorPool, DescriptorSetLayout, DescriptorItems, out UsingSamplers);
            RenderPass          = VKHelper.CreateRenderPass(Graphics, ClearDepthOnBeginPass);
            Pipeline            = VKHelper.CreateGraphicsPipeline(Graphics, PipelineLayout, RenderPass, Shaders, DepthTest, DepthWrite, Instancing, InstanceInfoType, BlendMode, PrimitiveType, PrimitiveRenderMode, PrimitiveCullMode, LineWidth, ViewportPos, ViewportSize);
        }
Exemple #18
0
        protected Effect(
            GraphicsDevice graphicsDevice,
            string vertexShaderName,
            string pixelShaderName,
            VertexDescriptor vertexDescriptor,
            PipelineLayoutDescription pipelineLayoutDescription)
        {
            _graphicsDevice = graphicsDevice;

            _vertexShader = AddDisposable(new Shader(graphicsDevice.ShaderLibrary, vertexShaderName));
            _pixelShader  = AddDisposable(new Shader(graphicsDevice.ShaderLibrary, pixelShaderName));

            _cachedPipelineStates = new Dictionary <EffectPipelineStateHandle, PipelineState>();

            _vertexDescriptor = vertexDescriptor;

            _pipelineLayout = AddDisposable(new PipelineLayout(_graphicsDevice, ref pipelineLayoutDescription));
        }
Exemple #19
0
        public void Draw(CommandBuffer cmd, PipelineLayout pipelineLayout, Buffer instanceBuf, bool shadowPass = false, params InstancedCmd[] instances)
        {
            cmd.BindVertexBuffer(instanceBuf, 1);
            uint firstInstance = 0;

            for (int i = 0; i < instances.Length; i++)
            {
                foreach (Primitive p in Meshes[instances[i].meshIdx].Primitives)
                {
                    if (!shadowPass)
                    {
                        cmd.PushConstant(pipelineLayout, VkShaderStageFlags.Fragment, (int)p.material, (uint)Marshal.SizeOf <Matrix4x4>());
                    }
                    cmd.DrawIndexed(p.indexCount, instances[i].count, p.indexBase, p.vertexBase, firstInstance);
                }
                firstInstance += instances[i].count;
            }
        }
            public void CreateResources(
                Device logicalDevice,
                ShaderInputManager shaderInputManager,
                RenderPass renderPass,
                ReadOnlySpan <DeviceTexture> targets,
                ReadOnlySpan <IShaderInput> globalInputs)
            {
                //Update the shader inputs
                //TODO: Get rid of all the array allocation here
                var totalInputs = globalInputs.ToArray().Concat(renderObject.Inputs.ToArray());

                if (inputBlock == null)
                {
                    inputBlock = shaderInputManager.Allocate(totalInputs);
                }
                else
                {
                    inputBlock.Value.Update(totalInputs);
                }

                //Create a pipeline layout if we don't have one allready
                if (pipelineLayout == null)
                {
                    pipelineLayout = logicalDevice.CreatePipelineLayout(new PipelineLayoutCreateInfo(
                                                                            setLayouts: new [] { inputBlock.Value.Layout },
                                                                            pushConstantRanges: pushDataContainer.GetRanges()));
                }

                //Create a pipeline if we don't have one allready
                if (pipeline == null)
                {
                    pipeline = PipelineUtils.CreatePipeline(
                        logicalDevice,
                        renderPass,
                        pipelineLayout,
                        vertModule,
                        fragModule,
                        specializationContainer,
                        depthClamp,
                        depthBias,
                        targets,
                        renderObject);
                }
            }
Exemple #21
0
        private void CreateGraphicsPipeline()
        {
            this.descriptorSetLayout = this.device.CreateDescriptorSetLayout(new[]
            {
                new DescriptorSetLayoutBinding
                {
                    Binding         = 1,
                    DescriptorCount = 1,
                    DescriptorType  = DescriptorType.CombinedImageSampler,
                    StageFlags      = ShaderStageFlags.Fragment
                }
            });

            var bindingDescription    = Vertex.GetBindingDescription();
            var attributeDescriptions = Vertex.GetAttributeDescriptions();

            this.pipelineLayout = device.CreatePipelineLayout(this.descriptorSetLayout, null);

            this.pipeline = device.CreateGraphicsPipelines(null, new[]
        Pipeline[] CreatePipelines(PipelineLayout pipelineLayout, RenderPass renderPass, PipelineShaderStageCreateInfo[] shaderStageCreateInfos, VertexData vertexData)
        {
            // Some Vulkan commands specify geometric objects to be drawn or computational work to be
            // performed, while others specify state controlling how objects are handled by the various
            // pipeline stages, or control data transfer between memory organized as images and
            // buffers. Commands are effectively sent through a processing 'pipeline', either a
            // graphics pipeline or a compute pipeline.

            // (In our case, we want a graphics pipeline)

            // The first stage of the graphics pipeline (Input Assembler) assembles vertices to form
            // geometric primitives such as points, lines, and triangles, based on a requested
            // primitive topology.
            var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo(PrimitiveTopology.TriangleList, false);

            // In the next stage (Vertex Shader) vertices can be transformed, computing positions and
            // attributes for each vertex.
            var vertexInputState = new PipelineVertexInputStateCreateInfo(vertexData.BindingDescriptions, vertexData.AttributeDescriptions);

            // The final resulting primitives are clipped to a clip volume in preparation for the next
            // stage, Rasterization. The rasterizer produces a series of framebuffer addresses and
            // values using a two-dimensional description of a point, line segment, or triangle. Each
            // fragment so produced is fed to the next stage (Fragment Shader) that performs operations
            // on individual fragments before they finally alter the framebuffer.
            var rasterizationState = new PipelineRasterizationStateCreateInfo();

            rasterizationState.LineWidth = 1;

            var createInfos = new[]
            {
                new GraphicsPipelineCreateInfo(shaderStageCreateInfos, vertexInputState, inputAssemblyState, rasterizationState, pipelineLayout, renderPass, 0, 0)
                {
                    ViewportState    = new PipelineViewportStateCreateInfo(),
                    MultisampleState = new PipelineMultisampleStateCreateInfo()
                    {
                        RasterizationSamples = SampleCountFlags.SampleCountFlags1
                    }
                }
            };

            return(device.CreateGraphicsPipelines(null, createInfos));
        }
Exemple #23
0
        public void CmdBindPipeline()
        {
            var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo(
                new DescriptorSetLayoutBinding(0, DescriptorType.StorageBuffer, 1, ShaderStages.Compute),
                new DescriptorSetLayoutBinding(1, DescriptorType.StorageBuffer, 1, ShaderStages.Compute));

            using (DescriptorSetLayout descriptorSetLayout = Device.CreateDescriptorSetLayout(descriptorSetLayoutCreateInfo))
                using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(new[] { descriptorSetLayout })))
                    using (ShaderModule shader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.comp.spv"))))
                    {
                        var pipelineCreateInfo = new ComputePipelineCreateInfo(
                            new PipelineShaderStageCreateInfo(ShaderStages.Compute, shader, "main"),
                            pipelineLayout);

                        using (Pipeline pipeline = Device.CreateComputePipeline(pipelineCreateInfo))
                        {
                            CommandBuffer.Begin();
                            CommandBuffer.CmdBindPipeline(PipelineBindPoint.Compute, pipeline);
                            CommandBuffer.End();
                        }
                    }
        }
        public PipelineLayoutCacheEntry(VulkanGraphicsDevice gd, Device device, uint stages)
        {
            _gd     = gd;
            _device = device;
            _stages = stages;

            DescriptorSetLayouts = PipelineLayoutFactory.Create(gd, device, stages, out var pipelineLayout);
            PipelineLayout       = pipelineLayout;

            _dsCache = new List <Auto <DescriptorSetCollection> > [CommandBufferPool.MaxCommandBuffers][];

            for (int i = 0; i < CommandBufferPool.MaxCommandBuffers; i++)
            {
                _dsCache[i] = new List <Auto <DescriptorSetCollection> > [PipelineBase.DescriptorSetLayouts];

                for (int j = 0; j < PipelineBase.DescriptorSetLayouts; j++)
                {
                    _dsCache[i][j] = new List <Auto <DescriptorSetCollection> >();
                }
            }

            _dsCacheCursor = new int[PipelineBase.DescriptorSetLayouts];
        }
Exemple #25
0
        public void CmdBindDescriptorSet()
        {
            const int bufferSize = 256;

            var layoutCreateInfo = new DescriptorSetLayoutCreateInfo(
                new DescriptorSetLayoutBinding(0, DescriptorType.StorageBuffer, 1));
            var descriptorPoolCreateInfo = new DescriptorPoolCreateInfo(
                1,
                new[] { new DescriptorPoolSize(DescriptorType.StorageBuffer, 1) });

            using (DescriptorSetLayout descriptorSetLayout = Device.CreateDescriptorSetLayout(layoutCreateInfo))
                using (DescriptorPool descriptorPool = Device.CreateDescriptorPool(descriptorPoolCreateInfo))
                    using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(new[] { descriptorSetLayout })))
                        using (Buffer buffer = Device.CreateBuffer(new BufferCreateInfo(bufferSize, BufferUsages.StorageBuffer)))
                            using (DeviceMemory memory = Device.AllocateMemory(new MemoryAllocateInfo(bufferSize, 0)))
                            {
                                // Required to satisfy the validation layer.
                                buffer.GetMemoryRequirements();

                                buffer.BindMemory(memory);

                                DescriptorSet descriptorSet =
                                    descriptorPool.AllocateSets(new DescriptorSetAllocateInfo(1, descriptorSetLayout))[0];

                                var descriptorWrite = new WriteDescriptorSet(descriptorSet, 0, 0, 1, DescriptorType.StorageBuffer,
                                                                             bufferInfo: new[] { new DescriptorBufferInfo(buffer) });

                                descriptorPool.UpdateSets(new[] { descriptorWrite });

                                CommandBuffer.Begin();
                                CommandBuffer.CmdBindDescriptorSet(PipelineBindPoint.Graphics, pipelineLayout, descriptorSet);
                                CommandBuffer.CmdBindDescriptorSets(PipelineBindPoint.Graphics, pipelineLayout, 0, new[] { descriptorSet });
                                CommandBuffer.End();

                                descriptorPool.Reset();
                            }
        }
Exemple #26
0
 internal static unsafe extern Result vkCreatePipelineLayout(Device device, PipelineLayoutCreateInfo* createInfo, AllocationCallbacks* allocator, PipelineLayout* pipelineLayout);
Exemple #27
0
        private unsafe void CreatePipelineLayout()
        {
            var binding = new DescriptorSetLayoutBinding
            {
                Binding = 0,
                DescriptorCount = 1,
                DescriptorType = DescriptorType.UniformBuffer,
                StageFlags = ShaderStageFlags.Vertex
            };

            var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo
            {
                StructureType = StructureType.DescriptorSetLayoutCreateInfo,
                BindingCount = 1,
                Bindings = new IntPtr(&binding)
            };
            descriptorSetLayout = device.CreateDescriptorSetLayout(ref descriptorSetLayoutCreateInfo);

            var localDescriptorSetLayout = descriptorSetLayout;
            var createInfo = new PipelineLayoutCreateInfo
            {
                StructureType = StructureType.PipelineLayoutCreateInfo,
                SetLayoutCount = 1,
                SetLayouts = new IntPtr(&localDescriptorSetLayout)
            };
            pipelineLayout = device.CreatePipelineLayout(ref createInfo);

            var poolSize = new DescriptorPoolSize { DescriptorCount = 2, Type = DescriptorType.UniformBuffer };
            var descriptorPoolCreateinfo = new DescriptorPoolCreateInfo
            {
                StructureType = StructureType.DescriptorPoolCreateInfo,
                PoolSizeCount = 1,
                PoolSizes = new IntPtr(&poolSize),
                MaxSets = 2
            };
            descriptorPool = device.CreateDescriptorPool(ref descriptorPoolCreateinfo);

            var bufferCreateInfo = new BufferCreateInfo
            {
                StructureType = StructureType.BufferCreateInfo,
                Usage = BufferUsageFlags.UniformBuffer,
                Size = 64,
            };
            uniformBuffer = device.CreateBuffer(ref bufferCreateInfo);

            MemoryRequirements memoryRequirements;
            device.GetBufferMemoryRequirements(uniformBuffer, out memoryRequirements);
            var memory = AllocateMemory(MemoryPropertyFlags.HostVisible | MemoryPropertyFlags.HostCoherent, memoryRequirements);

            device.BindBufferMemory(uniformBuffer, memory, 0);

            var mappedMemory = device.MapMemory(memory, 0, 64, MemoryMapFlags.None);
            var data = new[]
            {
                1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, 1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, 1.0f, 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f,
            };
            Utilities.Write(mappedMemory, data, 0, data.Length);
            device.UnmapMemory(memory);
        }
Exemple #28
0
 internal static unsafe extern void vkDestroyPipelineLayout(Device device, PipelineLayout pipelineLayout, AllocationCallbacks* allocator);
Exemple #29
0
 public unsafe void PushConstants(PipelineLayout layout, ShaderStageFlags stageFlags, uint offset, uint size, IntPtr values)
 {
     vkCmdPushConstants(this, layout, stageFlags, offset, size, values);
 }
Exemple #30
0
 internal static unsafe extern void vkCmdBindDescriptorSets(CommandBuffer commandBuffer, PipelineBindPoint pipelineBindPoint, PipelineLayout layout, uint firstSet, uint descriptorSetCount, DescriptorSet* descriptorSets, uint dynamicOffsetCount, uint* dynamicOffsets);
Exemple #31
0
 public unsafe void BindDescriptorSets(PipelineBindPoint pipelineBindPoint, PipelineLayout layout, uint firstSet, uint descriptorSetCount, DescriptorSet* descriptorSets, uint dynamicOffsetCount, uint* dynamicOffsets)
 {
     vkCmdBindDescriptorSets(this, pipelineBindPoint, layout, firstSet, descriptorSetCount, descriptorSets, dynamicOffsetCount, dynamicOffsets);
 }
Exemple #32
0
 internal static unsafe extern void vkCmdPushConstants(CommandBuffer commandBuffer, PipelineLayout layout, ShaderStageFlags stageFlags, uint offset, uint size, IntPtr values);
Exemple #33
0
 public unsafe void DestroyPipelineLayout(PipelineLayout pipelineLayout, AllocationCallbacks* allocator = null)
 {
     vkDestroyPipelineLayout(this, pipelineLayout, allocator);
 }
        private unsafe void CreatePipelineLayout(PipelineStateDescription pipelineStateDescription)
        {
            // Remap descriptor set indices to those in the shader. This ordering generated by the ShaderCompiler
            var resourceGroups = pipelineStateDescription.EffectBytecode.Reflection.ResourceBindings.Select(x => x.ResourceGroup ?? "Globals").Distinct().ToList();
            ResourceGroupCount = resourceGroups.Count;

            var layouts = pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.Layouts;
            
            // Get binding indices used by the shader
            var destinationBindings = pipelineStateDescription.EffectBytecode.Stages
                .SelectMany(x => BinarySerialization.Read<ShaderInputBytecode>(x.Data).ResourceBindings)
                .GroupBy(x => x.Key, x => x.Value)
                .ToDictionary(x => x.Key, x => x.First());

            var maxBindingIndex = destinationBindings.Max(x => x.Value);
            var destinationEntries = new DescriptorSetLayoutBuilder.Entry[maxBindingIndex + 1];

            DescriptorBindingMapping = new List<DescriptorSetInfo>();

            for (int i = 0; i < resourceGroups.Count; i++)
            {
                var resourceGroupName = resourceGroups[i] == "Globals" ? pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.DefaultSetSlot : resourceGroups[i];
                var layoutIndex = resourceGroups[i] == null ? 0 : layouts.FindIndex(x => x.Name == resourceGroupName);

                // Check if the resource group is used by the shader
                if (layoutIndex == -1)
                    continue;

                var sourceEntries = layouts[layoutIndex].Layout.Entries;

                for (int sourceBinding = 0; sourceBinding < sourceEntries.Count; sourceBinding++)
                {
                    var sourceEntry = sourceEntries[sourceBinding];

                    int destinationBinding;
                    if (destinationBindings.TryGetValue(sourceEntry.Key.Name, out destinationBinding))
                    {
                        destinationEntries[destinationBinding] = sourceEntry;

                        // No need to umpdate immutable samplers
                        if (sourceEntry.Class == EffectParameterClass.Sampler && sourceEntry.ImmutableSampler != null)
                        {
                            continue;
                        }

                        DescriptorBindingMapping.Add(new DescriptorSetInfo
                        {
                            SourceSet = layoutIndex,
                            SourceBinding = sourceBinding,
                            DestinationBinding = destinationBinding,
                            DescriptorType = VulkanConvertExtensions.ConvertDescriptorType(sourceEntry.Class, sourceEntry.Type)
                        });
                    }
                }
            }

            // Create default sampler, used by texture and buffer loads
            destinationEntries[0] = new DescriptorSetLayoutBuilder.Entry
            {
                Class = EffectParameterClass.Sampler,
                Type = EffectParameterType.Sampler,
                ImmutableSampler = GraphicsDevice.SamplerStates.PointWrap,
                ArraySize = 1,
            };

            // Create descriptor set layout
            NativeDescriptorSetLayout = DescriptorSetLayout.CreateNativeDescriptorSetLayout(GraphicsDevice, destinationEntries, out DescriptorTypeCounts);

            // Create pipeline layout
            var nativeDescriptorSetLayout = NativeDescriptorSetLayout;
            var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo
            {
                StructureType = StructureType.PipelineLayoutCreateInfo,
                SetLayoutCount = 1,
                SetLayouts = new IntPtr(&nativeDescriptorSetLayout)
            };
            NativeLayout = GraphicsDevice.NativeDevice.CreatePipelineLayout(ref pipelineLayoutCreateInfo);
        }