コード例 #1
0
        private unsafe Pipeline(PipelineSettings settings, VulkanRenderer renderer)
        {
            _renderer = renderer;

            Device device = _renderer.Params.Device;
            AllocationCallbacks *allocator = (AllocationCallbacks *)_renderer.Params.AllocationCallbacks.ToPointer();
            Vk vk = _renderer.Vk;

            PipelineShaderStageCreateInfo *shaderStages = stackalloc PipelineShaderStageCreateInfo[2]
            {
                _renderer.Shader.VertexShaderStage,
                _renderer.Shader.FragmentShaderStage
            };
            PipelineVertexInputStateCreateInfo   vertexInputState           = VertexInputState(_bindingDescription, _attributeDescriptions);
            PipelineInputAssemblyStateCreateInfo inputAssemblyState         = InputAssemblyState(settings);
            PipelineRasterizationStateCreateInfo rasterizationState         = RasterizationState(settings);
            PipelineMultisampleStateCreateInfo   multisampleState           = MultisampleState();
            PipelineColorBlendAttachmentState    colourBlendAttachmentState = ColorBlendAttachmentState(settings);
            PipelineColorBlendStateCreateInfo    colourBlendState           = ColourBlendState(colourBlendAttachmentState);
            PipelineViewportStateCreateInfo      viewportState     = ViewportState();
            PipelineDynamicStateCreateInfo       dynamicState      = DynamicStates(DynamicState.Viewport, DynamicState.Scissor);
            PipelineDepthStencilStateCreateInfo  depthStencilState = DepthStencilState(settings);

            GraphicsPipelineCreateInfo pipelineCreateInfo = new()
            {
                SType = StructureType.GraphicsPipelineCreateInfo,

                StageCount = 2,
                PStages    = shaderStages,

                PVertexInputState   = &vertexInputState,
                PInputAssemblyState = &inputAssemblyState,
                PRasterizationState = &rasterizationState,
                PMultisampleState   = &multisampleState,
                PColorBlendState    = &colourBlendState,
                PViewportState      = &viewportState,
                PDynamicState       = &dynamicState,
                PDepthStencilState  = &depthStencilState,
                PTessellationState  = null,

                Layout = _renderer.Shader.PipelineLayout,

                RenderPass = _renderer.Params.RenderPass,
                Subpass    = _renderer.Params.SubpassIndex,

                BasePipelineIndex  = -1,
                BasePipelineHandle = default
            };

            _renderer.AssertVulkan(vk.CreateGraphicsPipelines(device, default, 1, pipelineCreateInfo, allocator, out _handle));
コード例 #2
0
        private unsafe void Recreate()
        {
            if (Description.RootSignature == null)
            {
                return;
            }

            CreateRenderPass(Description);

            CreatePipelineLayout(Description);

            // Create shader stages
            Dictionary <int, string> inputAttributeNames;

            // Note: important to pin this so that stages[x].Name is valid during this whole function
            void *defaultEntryPointData = Interop.Fixed(defaultEntryPoint);
            var   stages = CreateShaderStages(Description, out inputAttributeNames);

            var inputAttributes     = new VertexInputAttributeDescription[Description.InputElements.Length];
            int inputAttributeCount = 0;
            var inputBindings       = new VertexInputBindingDescription[inputAttributes.Length];
            int inputBindingCount   = 0;

            for (int inputElementIndex = 0; inputElementIndex < inputAttributes.Length; inputElementIndex++)
            {
                var inputElement = Description.InputElements[inputElementIndex];
                var slotIndex    = inputElement.InputSlot;

                if (inputElement.InstanceDataStepRate > 1)
                {
                    throw new NotImplementedException();
                }

                Format format;
                int    size;
                bool   isCompressed;
                VulkanConvertExtensions.ConvertPixelFormat(inputElement.Format, out format, out size, out isCompressed);

                var location = inputAttributeNames.FirstOrDefault(x => x.Value == inputElement.SemanticName && inputElement.SemanticIndex == 0 || x.Value == inputElement.SemanticName + inputElement.SemanticIndex);
                if (location.Value != null)
                {
                    inputAttributes[inputAttributeCount++] = new VertexInputAttributeDescription
                    {
                        Format   = format,
                        Offset   = (uint)inputElement.AlignedByteOffset,
                        Binding  = (uint)inputElement.InputSlot,
                        Location = (uint)location.Key
                    };
                }

                inputBindings[slotIndex].Binding   = (uint)slotIndex;
                inputBindings[slotIndex].InputRate = inputElement.InputSlotClass == InputClassification.Vertex ? VertexInputRate.Vertex : VertexInputRate.Instance;

                // TODO VULKAN: This is currently an argument to Draw() overloads.
                if (inputBindings[slotIndex].Stride < inputElement.AlignedByteOffset + size)
                {
                    inputBindings[slotIndex].Stride = (uint)(inputElement.AlignedByteOffset + size);
                }

                if (inputElement.InputSlot >= inputBindingCount)
                {
                    inputBindingCount = inputElement.InputSlot + 1;
                }
            }

            var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo
            {
                StructureType          = StructureType.PipelineInputAssemblyStateCreateInfo,
                Topology               = VulkanConvertExtensions.ConvertPrimitiveType(Description.PrimitiveType),
                PrimitiveRestartEnable = VulkanConvertExtensions.ConvertPrimitiveRestart(Description.PrimitiveType),
            };

            // TODO VULKAN: Tessellation and multisampling
            var multisampleState = new PipelineMultisampleStateCreateInfo
            {
                StructureType        = StructureType.PipelineMultisampleStateCreateInfo,
                RasterizationSamples = SampleCountFlags.Sample1
            };

            var tessellationState = new PipelineTessellationStateCreateInfo();

            var rasterizationState = CreateRasterizationState(Description.RasterizerState);

            var depthStencilState = CreateDepthStencilState(Description);

            var description = Description.BlendState;

            var renderTargetCount     = Description.Output.RenderTargetCount;
            var colorBlendAttachments = new PipelineColorBlendAttachmentState[renderTargetCount];

            var renderTargetBlendState = &description.RenderTarget0;

            for (int i = 0; i < renderTargetCount; i++)
            {
                colorBlendAttachments[i] = new PipelineColorBlendAttachmentState
                {
                    BlendEnable                 = renderTargetBlendState->BlendEnable,
                    AlphaBlendOperation         = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->AlphaBlendFunction),
                    ColorBlendOperation         = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->ColorBlendFunction),
                    DestinationAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaDestinationBlend),
                    DestinationColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorDestinationBlend),
                    SourceAlphaBlendFactor      = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaSourceBlend),
                    SourceColorBlendFactor      = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorSourceBlend),
                    ColorWriteMask              = VulkanConvertExtensions.ConvertColorWriteChannels(renderTargetBlendState->ColorWriteChannels),
                };

                if (description.IndependentBlendEnable)
                {
                    renderTargetBlendState++;
                }
            }

            var viewportState = new PipelineViewportStateCreateInfo
            {
                StructureType = StructureType.PipelineViewportStateCreateInfo,
                ScissorCount  = 1,
                ViewportCount = 1,
            };

            fixed(DynamicState *dynamicStatesPointer = &dynamicStates[0])
            {
                var vertexInputState = new PipelineVertexInputStateCreateInfo
                {
                    StructureType = StructureType.PipelineVertexInputStateCreateInfo,
                    VertexAttributeDescriptionCount = (uint)inputAttributeCount,
                    VertexAttributeDescriptions     = inputAttributes.Length > 0 ? new IntPtr(Interop.Fixed(inputAttributes)) : IntPtr.Zero,
                    VertexBindingDescriptionCount   = (uint)inputBindingCount,
                    VertexBindingDescriptions       = inputBindings.Length > 0 ? new IntPtr(Interop.Fixed(inputBindings)) : IntPtr.Zero,
                };

                var colorBlendState = new PipelineColorBlendStateCreateInfo
                {
                    StructureType   = StructureType.PipelineColorBlendStateCreateInfo,
                    AttachmentCount = (uint)renderTargetCount,
                    Attachments     = colorBlendAttachments.Length > 0 ? new IntPtr(Interop.Fixed(colorBlendAttachments)) : IntPtr.Zero,
                };

                var dynamicState = new PipelineDynamicStateCreateInfo
                {
                    StructureType     = StructureType.PipelineDynamicStateCreateInfo,
                    DynamicStateCount = (uint)dynamicStates.Length,
                    DynamicStates     = new IntPtr(dynamicStatesPointer)
                };

                var createInfo = new GraphicsPipelineCreateInfo
                {
                    StructureType = StructureType.GraphicsPipelineCreateInfo,
                    Layout        = NativeLayout,
                    StageCount    = (uint)stages.Length,
                    Stages        = stages.Length > 0 ? new IntPtr(Interop.Fixed(stages)) : IntPtr.Zero,
                    //TessellationState = new IntPtr(&tessellationState),
                    VertexInputState   = new IntPtr(&vertexInputState),
                    InputAssemblyState = new IntPtr(&inputAssemblyState),
                    RasterizationState = new IntPtr(&rasterizationState),
                    MultisampleState   = new IntPtr(&multisampleState),
                    DepthStencilState  = new IntPtr(&depthStencilState),
                    ColorBlendState    = new IntPtr(&colorBlendState),
                    DynamicState       = new IntPtr(&dynamicState),
                    ViewportState      = new IntPtr(&viewportState),
                    RenderPass         = NativeRenderPass,
                    Subpass            = 0,
                };

                NativePipeline = GraphicsDevice.NativeDevice.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo);
            }

            // Cleanup shader modules
            foreach (var stage in stages)
            {
                GraphicsDevice.NativeDevice.DestroyShaderModule(stage.Module);
            }
        }
コード例 #3
0
        private unsafe void Recreate()
        {
            errorDuringCreate = false;

            if (Description.RootSignature == null)
            {
                return;
            }

            PipelineShaderStageCreateInfo[] stages;

            // try to recover from a rare failure?
            bool retry = false;

            // it appears pipeline creation is just not thread safe :(
            lock (PipeLock) {
                Xenko.Shaders.Compiler.EffectCompilerCache.CompileSynchronization.Wait();

                CreateRenderPass(Description);

                CreatePipelineLayout(Description);

                // Create shader stages
                Dictionary <int, string> inputAttributeNames;
                stages = CreateShaderStages(Description, out inputAttributeNames);

                var inputAttributes     = new VertexInputAttributeDescription[Description.InputElements.Length];
                int inputAttributeCount = 0;
                var inputBindings       = new VertexInputBindingDescription[inputAttributes.Length];
                int inputBindingCount   = 0;

                for (int inputElementIndex = 0; inputElementIndex < inputAttributes.Length; inputElementIndex++)
                {
                    var inputElement = Description.InputElements[inputElementIndex];
                    var slotIndex    = inputElement.InputSlot;

                    if (inputElement.InstanceDataStepRate > 1)
                    {
                        throw new NotImplementedException();
                    }

                    Format format;
                    int    size;
                    bool   isCompressed;
                    VulkanConvertExtensions.ConvertPixelFormat(inputElement.Format, out format, out size, out isCompressed);

                    var location = inputAttributeNames.FirstOrDefault(x => x.Value == inputElement.SemanticName && inputElement.SemanticIndex == 0 || x.Value == inputElement.SemanticName + inputElement.SemanticIndex);
                    if (location.Value != null)
                    {
                        inputAttributes[inputAttributeCount++] = new VertexInputAttributeDescription
                        {
                            Format   = format,
                            Offset   = (uint)inputElement.AlignedByteOffset,
                            Binding  = (uint)inputElement.InputSlot,
                            Location = (uint)location.Key
                        };
                    }

                    inputBindings[slotIndex].Binding   = (uint)slotIndex;
                    inputBindings[slotIndex].InputRate = inputElement.InputSlotClass == InputClassification.Vertex ? VertexInputRate.Vertex : VertexInputRate.Instance;

                    // TODO VULKAN: This is currently an argument to Draw() overloads.
                    if (inputBindings[slotIndex].Stride < inputElement.AlignedByteOffset + size)
                    {
                        inputBindings[slotIndex].Stride = (uint)(inputElement.AlignedByteOffset + size);
                    }

                    if (inputElement.InputSlot >= inputBindingCount)
                    {
                        inputBindingCount = inputElement.InputSlot + 1;
                    }
                }

                var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo
                {
                    StructureType          = StructureType.PipelineInputAssemblyStateCreateInfo,
                    Topology               = VulkanConvertExtensions.ConvertPrimitiveType(Description.PrimitiveType),
                    PrimitiveRestartEnable = true,
                };

                // TODO VULKAN: Tessellation and multisampling
                var multisampleState = new PipelineMultisampleStateCreateInfo
                {
                    StructureType        = StructureType.PipelineMultisampleStateCreateInfo,
                    RasterizationSamples = SampleCountFlags.Sample1
                };

                //var tessellationState = new PipelineTessellationStateCreateInfo();

                var rasterizationState = CreateRasterizationState(Description.RasterizerState);

                var depthStencilState = CreateDepthStencilState(Description);

                var description = Description.BlendState;

                var renderTargetCount     = Description.Output.RenderTargetCount;
                var colorBlendAttachments = new PipelineColorBlendAttachmentState[renderTargetCount];

                var renderTargetBlendState = &description.RenderTarget0;
                for (int i = 0; i < renderTargetCount; i++)
                {
                    colorBlendAttachments[i] = new PipelineColorBlendAttachmentState
                    {
                        BlendEnable                 = renderTargetBlendState->BlendEnable,
                        AlphaBlendOperation         = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->AlphaBlendFunction),
                        ColorBlendOperation         = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->ColorBlendFunction),
                        DestinationAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaDestinationBlend),
                        DestinationColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorDestinationBlend),
                        SourceAlphaBlendFactor      = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaSourceBlend),
                        SourceColorBlendFactor      = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorSourceBlend),
                        ColorWriteMask              = VulkanConvertExtensions.ConvertColorWriteChannels(renderTargetBlendState->ColorWriteChannels),
                    };

                    if (description.IndependentBlendEnable)
                    {
                        renderTargetBlendState++;
                    }
                }

                var viewportState = new PipelineViewportStateCreateInfo
                {
                    StructureType = StructureType.PipelineViewportStateCreateInfo,
                    ScissorCount  = 1,
                    ViewportCount = 1,
                };

                fixed(void *dynamicStatesPointer   = dynamicStates.Length == 0?null : dynamicStates,
                      inputAttributesPointer       = inputAttributes.Length == 0?null : inputAttributes,
                      inputBindingsPointer         = inputBindings.Length == 0?null : inputBindings,
                      colorBlendAttachmentsPointer = colorBlendAttachments.Length == 0?null : colorBlendAttachments,
                      stagesPointer = stages.Length == 0?null : stages)
                {
                    var vertexInputState = new PipelineVertexInputStateCreateInfo
                    {
                        StructureType = StructureType.PipelineVertexInputStateCreateInfo,
                        VertexAttributeDescriptionCount = (uint)inputAttributeCount,
                        VertexAttributeDescriptions     = (IntPtr)inputAttributesPointer,
                        VertexBindingDescriptionCount   = (uint)inputBindingCount,
                        VertexBindingDescriptions       = (IntPtr)inputBindingsPointer,
                    };

                    var colorBlendState = new PipelineColorBlendStateCreateInfo
                    {
                        StructureType   = StructureType.PipelineColorBlendStateCreateInfo,
                        AttachmentCount = (uint)renderTargetCount,
                        Attachments     = (IntPtr)colorBlendAttachmentsPointer,
                    };

                    var dynamicState = new PipelineDynamicStateCreateInfo
                    {
                        StructureType     = StructureType.PipelineDynamicStateCreateInfo,
                        DynamicStateCount = (uint)dynamicStates.Length,
                        DynamicStates     = (IntPtr)dynamicStatesPointer,
                    };

                    var createInfo = new GraphicsPipelineCreateInfo
                    {
                        StructureType = StructureType.GraphicsPipelineCreateInfo,
                        Layout        = NativeLayout,
                        StageCount    = (uint)stages.Length,
                        Stages        = (IntPtr)stagesPointer,
                        //TessellationState = new IntPtr(&tessellationState),
                        VertexInputState   = new IntPtr(&vertexInputState),
                        InputAssemblyState = new IntPtr(&inputAssemblyState),
                        RasterizationState = new IntPtr(&rasterizationState),
                        MultisampleState   = new IntPtr(&multisampleState),
                        DepthStencilState  = new IntPtr(&depthStencilState),
                        ColorBlendState    = new IntPtr(&colorBlendState),
                        DynamicState       = new IntPtr(&dynamicState),
                        ViewportState      = new IntPtr(&viewportState),
                        RenderPass         = NativeRenderPass,
                        Subpass            = 0,
                    };

                    try {
                        lock (GraphicsDevice.QueueLock) {
                            NativePipeline = GraphicsDevice.NativeDevice.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo);
                        }
                    } catch (AccessViolationException ae) {
                        // this happens extremely rarely and might be recoverable by reattempting the recreate
                        retry = true;
                    } catch (Exception e) {
                        errorDuringCreate = true;
                        NativePipeline    = Pipeline.Null;
                    }
                }
            }

            // Cleanup shader modules
            for (int i = 0; i < stages.Length; i++)
            {
                GraphicsDevice.NativeDevice.DestroyShaderModule(stages[i].Module);
            }

            if (retry)
            {
                Recreate();
            }
        }
コード例 #4
0
ファイル: Sample.cs プロジェクト: jwollen/SharpVulkan
        private void CreatePipeline()
        {
            var dynamicStates = new [] { DynamicState.Viewport, DynamicState.Scissor };

            var entryPointName = System.Text.Encoding.UTF8.GetBytes("main\0");

            fixed (byte* entryPointNamePointer = &entryPointName[0])
            fixed (DynamicState* dynamicStatesPointer = &dynamicStates[0])
            fixed (VertexInputAttributeDescription* vertexAttibutesPointer = &vertexAttributes[0])
            fixed (VertexInputBindingDescription* vertexBindingsPointer = &vertexBindings[0])
            {
                var dynamicState = new PipelineDynamicStateCreateInfo
                {
                    StructureType = StructureType.PipelineDynamicStateCreateInfo,
                    DynamicStateCount = (uint)dynamicStates.Length,
                    DynamicStates = new IntPtr(dynamicStatesPointer)
                };

                var viewportState = new PipelineViewportStateCreateInfo
                {
                    StructureType = StructureType.PipelineViewportStateCreateInfo,
                    ScissorCount = 1,
                    ViewportCount = 1,
                };

                var vertexInputState = new PipelineVertexInputStateCreateInfo
                {
                    StructureType = StructureType.PipelineVertexInputStateCreateInfo,
                    VertexAttributeDescriptionCount = (uint)vertexAttributes.Length,
                    VertexAttributeDescriptions = new IntPtr(vertexAttibutesPointer),
                    VertexBindingDescriptionCount = (uint)vertexBindings.Length,
                    VertexBindingDescriptions = new IntPtr(vertexBindingsPointer),
                };

                var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo
                {
                    StructureType = StructureType.PipelineInputAssemblyStateCreateInfo,
                    Topology = PrimitiveTopology.TriangleList
                };

                var rasterizerState = new PipelineRasterizationStateCreateInfo
                {
                    StructureType = StructureType.PipelineRasterizationStateCreateInfo,
                    PolygonMode = PolygonMode.Fill,
                    CullMode = CullModeFlags.None,
                    FrontFace = FrontFace.Clockwise,
                    LineWidth = 1.0f,
                };

                var colorBlendAttachment = new PipelineColorBlendAttachmentState { ColorWriteMask = ColorComponentFlags.R | ColorComponentFlags.G | ColorComponentFlags.B | ColorComponentFlags.A };
                var blendState = new PipelineColorBlendStateCreateInfo
                {
                    StructureType = StructureType.PipelineColorBlendStateCreateInfo,
                    AttachmentCount = 1,
                    Attachments = new IntPtr(&colorBlendAttachment)
                };

                var depthStencilState = new PipelineDepthStencilStateCreateInfo
                {
                    StructureType = StructureType.PipelineDepthStencilStateCreateInfo,
                    DepthTestEnable = false,
                    DepthWriteEnable = true,
                    DepthCompareOperation = CompareOperation.LessOrEqual,
                    Back = new StencilOperationState { CompareOperation = CompareOperation.Always },
                    Front = new StencilOperationState { CompareOperation = CompareOperation.Always }
                };

                var multisampleState = new PipelineMultisampleStateCreateInfo
                {
                    StructureType = StructureType.PipelineMultisampleStateCreateInfo,
                    RasterizationSamples = SampleCountFlags.Sample1,
                };

                var shaderStages = new[]
                {
                    new PipelineShaderStageCreateInfo
                    {
                        StructureType = StructureType.PipelineShaderStageCreateInfo,
                        Name = new IntPtr(entryPointNamePointer),
                        Stage = ShaderStageFlags.Vertex,
                        Module = CreateVertexShader()
                    },
                    new PipelineShaderStageCreateInfo
                    {
                        StructureType = StructureType.PipelineShaderStageCreateInfo,
                        Name = new IntPtr(entryPointNamePointer),
                        Stage = ShaderStageFlags.Fragment,
                        Module = CreateFragmentShader()
                    }
                };

                fixed (PipelineShaderStageCreateInfo* shaderStagesPointer = &shaderStages[0])
                {
                    var createInfo = new GraphicsPipelineCreateInfo
                    {
                        StructureType = StructureType.GraphicsPipelineCreateInfo,
                        Layout = pipelineLayout,
                        DynamicState = new IntPtr(&dynamicState),
                        ViewportState = new IntPtr(&viewportState),
                        VertexInputState = new IntPtr(&vertexInputState),
                        InputAssemblyState = new IntPtr(&inputAssemblyState),
                        RasterizationState = new IntPtr(&rasterizerState),
                        ColorBlendState = new IntPtr(&blendState),
                        DepthStencilState = new IntPtr(&depthStencilState),
                        MultisampleState = new IntPtr(&multisampleState),
                        StageCount = (uint)shaderStages.Length,
                        Stages = new IntPtr(shaderStagesPointer),
                        RenderPass = renderPass
                    };
                    pipeline = device.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo);
                }

                foreach (var shaderStage in shaderStages)
                {
                    device.DestroyShaderModule(shaderStage.Module);
                }
            }
        }
コード例 #5
0
ファイル: Sample.cs プロジェクト: jcapellman/SharpVulkan
        private void CreatePipeline()
        {
            var dynamicStates = new [] { DynamicState.Viewport, DynamicState.Scissor };

            var entryPointName = System.Text.Encoding.UTF8.GetBytes("main\0");

            fixed(byte *entryPointNamePointer = &entryPointName[0])
            fixed(DynamicState * dynamicStatesPointer = &dynamicStates[0])
            fixed(VertexInputAttributeDescription * vertexAttibutesPointer = &vertexAttributes[0])
            fixed(VertexInputBindingDescription * vertexBindingsPointer    = &vertexBindings[0])
            {
                var dynamicState = new PipelineDynamicStateCreateInfo
                {
                    StructureType     = StructureType.PipelineDynamicStateCreateInfo,
                    DynamicStateCount = (uint)dynamicStates.Length,
                    DynamicStates     = new IntPtr(dynamicStatesPointer)
                };

                var viewportState = new PipelineViewportStateCreateInfo
                {
                    StructureType = StructureType.PipelineViewportStateCreateInfo,
                    ScissorCount  = 1,
                    ViewportCount = 1,
                };

                var vertexInputState = new PipelineVertexInputStateCreateInfo
                {
                    StructureType = StructureType.PipelineVertexInputStateCreateInfo,
                    VertexAttributeDescriptionCount = (uint)vertexAttributes.Length,
                    VertexAttributeDescriptions     = new IntPtr(vertexAttibutesPointer),
                    VertexBindingDescriptionCount   = (uint)vertexBindings.Length,
                    VertexBindingDescriptions       = new IntPtr(vertexBindingsPointer),
                };

                var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo
                {
                    StructureType = StructureType.PipelineInputAssemblyStateCreateInfo,
                    Topology      = PrimitiveTopology.TriangleList
                };

                var rasterizerState = new PipelineRasterizationStateCreateInfo
                {
                    StructureType = StructureType.PipelineRasterizationStateCreateInfo,
                    PolygonMode   = PolygonMode.Fill,
                    CullMode      = CullModeFlags.None,
                    FrontFace     = FrontFace.Clockwise,
                    LineWidth     = 1.0f,
                };

                var colorBlendAttachment = new PipelineColorBlendAttachmentState {
                    ColorWriteMask = ColorComponentFlags.R | ColorComponentFlags.G | ColorComponentFlags.B | ColorComponentFlags.A
                };
                var blendState = new PipelineColorBlendStateCreateInfo
                {
                    StructureType   = StructureType.PipelineColorBlendStateCreateInfo,
                    AttachmentCount = 1,
                    Attachments     = new IntPtr(&colorBlendAttachment)
                };

                var depthStencilState = new PipelineDepthStencilStateCreateInfo
                {
                    StructureType         = StructureType.PipelineDepthStencilStateCreateInfo,
                    DepthTestEnable       = false,
                    DepthWriteEnable      = true,
                    DepthCompareOperation = CompareOperation.LessOrEqual,
                    Back = new StencilOperationState {
                        CompareOperation = CompareOperation.Always
                    },
                    Front = new StencilOperationState {
                        CompareOperation = CompareOperation.Always
                    }
                };

                var multisampleState = new PipelineMultisampleStateCreateInfo
                {
                    StructureType        = StructureType.PipelineMultisampleStateCreateInfo,
                    RasterizationSamples = SampleCountFlags.Sample1,
                };

                var shaderStages = new[]
                {
                    new PipelineShaderStageCreateInfo
                    {
                        StructureType = StructureType.PipelineShaderStageCreateInfo,
                        Name          = new IntPtr(entryPointNamePointer),
                        Stage         = ShaderStageFlags.Vertex,
                        Module        = CreateVertexShader()
                    },
                    new PipelineShaderStageCreateInfo
                    {
                        StructureType = StructureType.PipelineShaderStageCreateInfo,
                        Name          = new IntPtr(entryPointNamePointer),
                        Stage         = ShaderStageFlags.Fragment,
                        Module        = CreateFragmentShader()
                    }
                };

                fixed(PipelineShaderStageCreateInfo *shaderStagesPointer = &shaderStages[0])
                {
                    var createInfo = new GraphicsPipelineCreateInfo
                    {
                        StructureType      = StructureType.GraphicsPipelineCreateInfo,
                        Layout             = pipelineLayout,
                        DynamicState       = new IntPtr(&dynamicState),
                        ViewportState      = new IntPtr(&viewportState),
                        VertexInputState   = new IntPtr(&vertexInputState),
                        InputAssemblyState = new IntPtr(&inputAssemblyState),
                        RasterizationState = new IntPtr(&rasterizerState),
                        ColorBlendState    = new IntPtr(&blendState),
                        DepthStencilState  = new IntPtr(&depthStencilState),
                        MultisampleState   = new IntPtr(&multisampleState),
                        StageCount         = (uint)shaderStages.Length,
                        Stages             = new IntPtr(shaderStagesPointer),
                        RenderPass         = renderPass
                    };

                    pipeline = device.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo);
                }

                foreach (var shaderStage in shaderStages)
                {
                    device.DestroyShaderModule(shaderStage.Module);
                }
            }
        }
コード例 #6
0
ファイル: DeviceTest.cs プロジェクト: yongweisun/VulkanCore
        public void CreateGraphicsPipeline()
        {
            var attachment = new AttachmentDescription
            {
                Samples        = SampleCounts.Count1,
                Format         = Format.B8G8R8A8UNorm,
                InitialLayout  = ImageLayout.Undefined,
                FinalLayout    = ImageLayout.PresentSrcKhr,
                LoadOp         = AttachmentLoadOp.Clear,
                StoreOp        = AttachmentStoreOp.Store,
                StencilLoadOp  = AttachmentLoadOp.DontCare,
                StencilStoreOp = AttachmentStoreOp.DontCare
            };
            var subpass    = new SubpassDescription(new[] { new AttachmentReference(0, ImageLayout.ColorAttachmentOptimal) });
            var createInfo = new RenderPassCreateInfo(new[] { subpass }, new[] { attachment });

            using (PipelineCache cache = Device.CreatePipelineCache())
                using (RenderPass renderPass = Device.CreateRenderPass(createInfo))
                    using (PipelineLayout layout = Device.CreatePipelineLayout())
                        using (ShaderModule vertexShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.vert.spv"))))
                            using (ShaderModule fragmentShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.frag.spv"))))
                            {
                                var shaderStageCreateInfos = new[]
                                {
                                    new PipelineShaderStageCreateInfo(ShaderStages.Vertex, vertexShader, "main"),
                                    new PipelineShaderStageCreateInfo(ShaderStages.Fragment, fragmentShader, "main")
                                };
                                var vertexInputStateCreateInfo   = new PipelineVertexInputStateCreateInfo();
                                var inputAssemblyStateCreateInfo = new PipelineInputAssemblyStateCreateInfo(PrimitiveTopology.TriangleList);
                                var viewportStateCreateInfo      = new PipelineViewportStateCreateInfo(
                                    new Viewport(0, 0, 32, 32),
                                    new Rect2D(0, 0, 32, 32));
                                var rasterizationStateCreateInfo = new PipelineRasterizationStateCreateInfo
                                {
                                    PolygonMode = PolygonMode.Fill,
                                    CullMode    = CullModes.Back,
                                    FrontFace   = FrontFace.CounterClockwise,
                                    LineWidth   = 1.0f
                                };
                                var tessellationStateCreateInfo = new PipelineTessellationStateCreateInfo(4);
                                var multisampleStateCreateInfo  = new PipelineMultisampleStateCreateInfo
                                {
                                    RasterizationSamples = SampleCounts.Count1,
                                    MinSampleShading     = 1.0f
                                };
                                var colorBlendAttachmentState = new PipelineColorBlendAttachmentState
                                {
                                    SrcColorBlendFactor = BlendFactor.One,
                                    DstColorBlendFactor = BlendFactor.Zero,
                                    ColorBlendOp        = BlendOp.Add,
                                    SrcAlphaBlendFactor = BlendFactor.One,
                                    DstAlphaBlendFactor = BlendFactor.Zero,
                                    AlphaBlendOp        = BlendOp.Add,
                                    ColorWriteMask      = ColorComponents.All
                                };
                                var depthStencilStateCreateInfo = new PipelineDepthStencilStateCreateInfo();
                                var colorBlendStateCreateInfo   = new PipelineColorBlendStateCreateInfo(
                                    new[] { colorBlendAttachmentState });
                                var dynamicStateCreateInfo = new PipelineDynamicStateCreateInfo(DynamicState.LineWidth);

                                var pipelineCreateInfo = new GraphicsPipelineCreateInfo(
                                    layout, renderPass, 0,
                                    shaderStageCreateInfos,
                                    inputAssemblyStateCreateInfo,
                                    vertexInputStateCreateInfo,
                                    rasterizationStateCreateInfo,
                                    tessellationStateCreateInfo,
                                    viewportStateCreateInfo,
                                    multisampleStateCreateInfo,
                                    depthStencilStateCreateInfo,
                                    colorBlendStateCreateInfo,
                                    dynamicStateCreateInfo);
                                using (Device.CreateGraphicsPipelines(new[] { pipelineCreateInfo })[0]) { }
                                using (Device.CreateGraphicsPipelines(new[] { pipelineCreateInfo }, cache)[0]) { }
                                using (Device.CreateGraphicsPipelines(new[] { pipelineCreateInfo }, allocator: CustomAllocator)[0]) { }
                                using (Device.CreateGraphicsPipelines(new[] { pipelineCreateInfo }, cache, CustomAllocator)[0]) { }
                                using (Device.CreateGraphicsPipeline(pipelineCreateInfo)) { }
                                using (Device.CreateGraphicsPipeline(pipelineCreateInfo, allocator: CustomAllocator)) { }
                                using (Device.CreateGraphicsPipeline(pipelineCreateInfo, cache)) { }
                                using (Device.CreateGraphicsPipeline(pipelineCreateInfo, cache, CustomAllocator)) { }
                            }
        }
コード例 #7
0
        internal static Pipeline CreatePipeline(
            Device logicalDevice,
            RenderPass renderpass,
            PipelineLayout layout,
            ShaderModule vertModule,
            ShaderModule fragModule,
            SpecializationContainer specializationContainer,
            bool depthClamp,
            bool depthBias,
            ReadOnlySpan <DeviceTexture> targets,
            IInternalRenderObject renderObject)
        {
            if (logicalDevice == null)
            {
                throw new ArgumentNullException(nameof(logicalDevice));
            }
            if (renderpass == null)
            {
                throw new ArgumentNullException(nameof(renderpass));
            }

            var shaderStages = new []
            {
                new PipelineShaderStageCreateInfo(
                    stage: ShaderStages.Vertex, module: vertModule, name: "main",
                    specializationInfo: specializationContainer?.GetInfo()),
                new PipelineShaderStageCreateInfo(
                    stage: ShaderStages.Fragment,
                    module: fragModule, name: "main",
                    specializationInfo: specializationContainer?.GetInfo())
            };
            var depthTest = new PipelineDepthStencilStateCreateInfo {
                DepthTestEnable       = true,
                DepthWriteEnable      = true,
                DepthCompareOp        = CompareOp.LessOrEqual,
                DepthBoundsTestEnable = false,
                StencilTestEnable     = false
            };
            var rasterizer = new PipelineRasterizationStateCreateInfo(
                depthClampEnable: depthClamp,
                rasterizerDiscardEnable: false,
                polygonMode: PolygonMode.Fill,
                cullMode: CullModes.Back,
                frontFace: renderObject.GetFrontFace(),
                depthBiasEnable: depthBias,
                depthBiasConstantFactor: .1f,
                depthBiasSlopeFactor: 1.75f,
                lineWidth: 1f
                );

            //Gather all the color targets and setup a blend-state for them
            ResizeArray <PipelineColorBlendAttachmentState> blendAttachments =
                new ResizeArray <PipelineColorBlendAttachmentState>();

            for (int i = 0; i < targets.Length; i++)
            {
                if (!targets[i].DepthTexture)
                {
                    blendAttachments.Add(new PipelineColorBlendAttachmentState(
                                             colorWriteMask: ColorComponents.All, blendEnable: false));
                }
            }

            var blending = new PipelineColorBlendStateCreateInfo(
                attachments: blendAttachments.ToArray(),
                logicOpEnable: false
                );
            var multisampleState = new PipelineMultisampleStateCreateInfo(
                rasterizationSamples: SampleCounts.Count1,
                sampleShadingEnable: false
                );
            //Pass the viewport and scissor-rect as dynamic so we are not tied to swapchain size
            //the advantage is this is that we don't need to recreate the pipeline on swapchain
            //resize
            var dynamicState = new PipelineDynamicStateCreateInfo(
                DynamicState.Viewport,
                DynamicState.Scissor
                );

            return(logicalDevice.CreateGraphicsPipeline(new GraphicsPipelineCreateInfo(
                                                            layout: layout,
                                                            renderPass: renderpass,
                                                            subpass: 0,
                                                            stages: shaderStages,
                                                            inputAssemblyState: renderObject.GetInputAssemblyStateInfo(),
                                                            vertexInputState: renderObject.GetVertexInputState(),
                                                            rasterizationState: rasterizer,
                                                            tessellationState: null,
                                                            //Pass empty viewport and scissor-rect as we set them dynamically
                                                            viewportState: new PipelineViewportStateCreateInfo(new Viewport(), new Rect2D()),
                                                            multisampleState: multisampleState,
                                                            depthStencilState: depthTest,
                                                            colorBlendState: blending,
                                                            dynamicState: dynamicState,
                                                            flags: PipelineCreateFlags.None
                                                            )));
        }
コード例 #8
0
        private Pipeline CreateGraphicsPipeline()
        {
            using var pName = SilkMarshal.StringToMemory("main");

            var shaderStages = stackalloc PipelineShaderStageCreateInfo[2]
            {
                new PipelineShaderStageCreateInfo
                {
                    SType  = StructureType.PipelineShaderStageCreateInfo,
                    Stage  = ShaderStageFlags.ShaderStageVertexBit,
                    Module = this.VertexShader,
                    PName  = (byte *)pName
                },

                new PipelineShaderStageCreateInfo
                {
                    SType  = StructureType.PipelineShaderStageCreateInfo,
                    Stage  = ShaderStageFlags.ShaderStageFragmentBit,
                    Module = this.FragmentShader,
                    PName  = (byte *)pName
                }
            };

            var dynamicStates = stackalloc DynamicState[2] {
                DynamicState.Viewport, DynamicState.Scissor
            };

            PipelineDynamicStateCreateInfo dynamicState = new PipelineDynamicStateCreateInfo
            {
                SType             = StructureType.PipelineDynamicStateCreateInfo,
                DynamicStateCount = 2,
                PDynamicStates    = dynamicStates
            };

            var vertexBindings = stackalloc VertexInputBindingDescription[2]
            {
                new VertexInputBindingDescription(0, (uint)sizeof(PositionColorVertex), VertexInputRate.Vertex),
                new VertexInputBindingDescription(1, (uint)sizeof(InstanceData), VertexInputRate.Instance)
            };

            var vertexAttributes = stackalloc VertexInputAttributeDescription[3]
            {
                new VertexInputAttributeDescription(0, 0, Format.R32G32B32Sfloat, 0),
                new VertexInputAttributeDescription(1, 0, Format.R32G32B32Sfloat, (uint)sizeof(System.Numerics.Vector3)),
                new VertexInputAttributeDescription(2, 1, Format.R32G32B32Sfloat, 0)
            };

            var vertexInputInfo = new PipelineVertexInputStateCreateInfo
            {
                SType = StructureType.PipelineVertexInputStateCreateInfo,
                VertexBindingDescriptionCount   = 2,
                PVertexBindingDescriptions      = vertexBindings,
                VertexAttributeDescriptionCount = 3,
                PVertexAttributeDescriptions    = vertexAttributes
            };

            var inputAssembly = new PipelineInputAssemblyStateCreateInfo
            {
                SType    = StructureType.PipelineInputAssemblyStateCreateInfo,
                Topology = PrimitiveTopology.TriangleList,
                PrimitiveRestartEnable = false
            };

            //Marked as dynamic state, will be specified in the command buffer
            var viewportState = new PipelineViewportStateCreateInfo
            {
                SType         = StructureType.PipelineViewportStateCreateInfo,
                ViewportCount = 1,
                ScissorCount  = 1,
            };

            var rasterizer = new PipelineRasterizationStateCreateInfo
            {
                SType                   = StructureType.PipelineRasterizationStateCreateInfo,
                DepthClampEnable        = Vk.False,
                RasterizerDiscardEnable = Vk.False,
                PolygonMode             = PolygonMode.Fill,
                LineWidth               = 1.0f,
                CullMode                = CullModeFlags.CullModeNone,
                FrontFace               = FrontFace.Clockwise,
                DepthBiasEnable         = Vk.False
            };

            var multisampling = new PipelineMultisampleStateCreateInfo
            {
                SType = StructureType.PipelineMultisampleStateCreateInfo,
                SampleShadingEnable  = false,
                RasterizationSamples = SampleCountFlags.SampleCount1Bit
            };

            var colorBlendAttachment = new PipelineColorBlendAttachmentState
            {
                ColorWriteMask = ColorComponentFlags.ColorComponentRBit |
                                 ColorComponentFlags.ColorComponentGBit |
                                 ColorComponentFlags.ColorComponentBBit |
                                 ColorComponentFlags.ColorComponentABit,
                BlendEnable = Vk.False
            };

            var colorBlending = new PipelineColorBlendStateCreateInfo
            {
                SType           = StructureType.PipelineColorBlendStateCreateInfo,
                LogicOpEnable   = Vk.False,
                LogicOp         = LogicOp.Copy,
                AttachmentCount = 1,
                PAttachments    = &colorBlendAttachment
            };

            colorBlending.BlendConstants[0] = 0.0f;
            colorBlending.BlendConstants[1] = 0.0f;
            colorBlending.BlendConstants[2] = 0.0f;
            colorBlending.BlendConstants[3] = 0.0f;

            var depthState = new PipelineDepthStencilStateCreateInfo
            {
                SType                 = StructureType.PipelineDepthStencilStateCreateInfo,
                DepthTestEnable       = true,
                DepthWriteEnable      = true,
                DepthCompareOp        = CompareOp.LessOrEqual,
                DepthBoundsTestEnable = false,
                MinDepthBounds        = 0,
                MaxDepthBounds        = 0,
                StencilTestEnable     = false,
                Back =
                {
                    FailOp      = StencilOp.Keep,
                    PassOp      = StencilOp.Keep,
                    CompareOp   = CompareOp.Always,
                    CompareMask =                0,
                    Reference   =                0,
                    DepthFailOp = StencilOp.Keep,
                    WriteMask   = 0
                }
            };

            depthState.Front = depthState.Back;

            var pipelineInfo = new GraphicsPipelineCreateInfo
            {
                SType               = StructureType.GraphicsPipelineCreateInfo,
                StageCount          = 2,
                PStages             = shaderStages,
                PDynamicState       = &dynamicState,
                PDepthStencilState  = &depthState,
                PVertexInputState   = &vertexInputInfo,
                PInputAssemblyState = &inputAssembly,
                PViewportState      = &viewportState,
                PRasterizationState = &rasterizer,
                PMultisampleState   = &multisampling,
                PColorBlendState    = &colorBlending,
                Layout              = this.GraphicsPipelineLayout,
                RenderPass          = RenderPass,
                Subpass             = 0,
                BasePipelineHandle  = default
            };

            Pipeline pipeline;
            var      res = VkApi.CreateGraphicsPipelines(Device, default, 1, &pipelineInfo, null, &pipeline);
コード例 #9
0
        //[HandleProcessCorruptedStateExceptionsAttribute, SecurityCriticalAttribute]
        private unsafe void Recreate()
        {
            errorDuringCreate = false;

            if (Description.RootSignature == null)
            {
                return;
            }

            PipelineShaderStageCreateInfo[] stages;

            // create render pass
            bool hasDepthStencilAttachment = Description.Output.DepthStencilFormat != PixelFormat.None;

            var renderTargetCount = Description.Output.RenderTargetCount;

            var attachmentCount = renderTargetCount;

            if (hasDepthStencilAttachment)
            {
                attachmentCount++;
            }

            var attachments = new AttachmentDescription[attachmentCount];
            var colorAttachmentReferences = new AttachmentReference[renderTargetCount];

            fixed(PixelFormat *renderTargetFormat = &Description.Output.RenderTargetFormat0)
            fixed(BlendStateRenderTargetDescription * blendDescription = &Description.BlendState.RenderTarget0)
            {
                for (int i = 0; i < renderTargetCount; i++)
                {
                    var currentBlendDesc = Description.BlendState.IndependentBlendEnable ? (blendDescription + i) : blendDescription;

                    attachments[i] = new AttachmentDescription
                    {
                        Format                = VulkanConvertExtensions.ConvertPixelFormat(*(renderTargetFormat + i)),
                        Samples               = SampleCountFlags.Sample1,
                        LoadOperation         = currentBlendDesc->BlendEnable ? AttachmentLoadOperation.Load : AttachmentLoadOperation.DontCare, // TODO VULKAN: Only if any destination blend?
                        StoreOperation        = AttachmentStoreOperation.Store,
                        StencilLoadOperation  = AttachmentLoadOperation.DontCare,
                        StencilStoreOperation = AttachmentStoreOperation.DontCare,
                        InitialLayout         = ImageLayout.ColorAttachmentOptimal,
                        FinalLayout           = ImageLayout.ColorAttachmentOptimal,
                    };

                    colorAttachmentReferences[i] = new AttachmentReference
                    {
                        Attachment = (uint)i,
                        Layout     = ImageLayout.ColorAttachmentOptimal,
                    };
                }
            }

            if (hasDepthStencilAttachment)
            {
                attachments[attachmentCount - 1] = new AttachmentDescription
                {
                    Format                = Texture.GetFallbackDepthStencilFormat(GraphicsDevice, VulkanConvertExtensions.ConvertPixelFormat(Description.Output.DepthStencilFormat)),
                    Samples               = SampleCountFlags.Sample1,
                    LoadOperation         = AttachmentLoadOperation.Load,     // TODO VULKAN: Only if depth read enabled?
                    StoreOperation        = AttachmentStoreOperation.Store,   // TODO VULKAN: Only if depth write enabled?
                    StencilLoadOperation  = AttachmentLoadOperation.DontCare, // TODO VULKAN: Handle stencil
                    StencilStoreOperation = AttachmentStoreOperation.DontCare,
                    InitialLayout         = ImageLayout.DepthStencilAttachmentOptimal,
                    FinalLayout           = ImageLayout.DepthStencilAttachmentOptimal,
                };
            }

            var depthAttachmentReference = new AttachmentReference
            {
                Attachment = (uint)attachments.Length - 1,
                Layout     = ImageLayout.DepthStencilAttachmentOptimal,
            };

            var subpass = new SubpassDescription
            {
                PipelineBindPoint      = PipelineBindPoint.Graphics,
                ColorAttachmentCount   = (uint)renderTargetCount,
                ColorAttachments       = colorAttachmentReferences.Length > 0 ? new IntPtr(Interop.Fixed(colorAttachmentReferences)) : IntPtr.Zero,
                DepthStencilAttachment = hasDepthStencilAttachment ? new IntPtr(&depthAttachmentReference) : IntPtr.Zero,
            };

            var renderPassCreateInfo = new RenderPassCreateInfo
            {
                StructureType   = StructureType.RenderPassCreateInfo,
                AttachmentCount = (uint)attachmentCount,
                Attachments     = attachments.Length > 0 ? new IntPtr(Interop.Fixed(attachments)) : IntPtr.Zero,
                SubpassCount    = 1,
                Subpasses       = new IntPtr(&subpass)
            };

            // create pipeline layout
            // Remap descriptor set indices to those in the shader. This ordering generated by the ShaderCompiler
            var resourceGroups = Description.EffectBytecode.Reflection.ResourceBindings.Select(x => x.ResourceGroup ?? "Globals").Distinct().ToList();

            ResourceGroupCount = resourceGroups.Count;

            var layouts = Description.RootSignature.EffectDescriptorSetReflection.Layouts;

            // Get binding indices used by the shader
            var destinationBindings = Description.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" ? Description.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)
            };

            // Create shader stages
            Dictionary <int, string> inputAttributeNames;

            // Note: important to pin this so that stages[x].Name is valid during this whole function
            void *defaultEntryPointData = Interop.Fixed(defaultEntryPoint);

            stages = CreateShaderStages(Description, out inputAttributeNames);

            var inputAttributes     = new VertexInputAttributeDescription[Description.InputElements.Length];
            int inputAttributeCount = 0;
            var inputBindings       = new VertexInputBindingDescription[inputAttributes.Length];
            int inputBindingCount   = 0;

            for (int inputElementIndex = 0; inputElementIndex < inputAttributes.Length; inputElementIndex++)
            {
                var inputElement = Description.InputElements[inputElementIndex];
                var slotIndex    = inputElement.InputSlot;

                if (inputElement.InstanceDataStepRate > 1)
                {
                    throw new NotImplementedException();
                }

                Format format;
                int    size;
                bool   isCompressed;
                VulkanConvertExtensions.ConvertPixelFormat(inputElement.Format, out format, out size, out isCompressed);

                var location = inputAttributeNames.FirstOrDefault(x => x.Value == inputElement.SemanticName && inputElement.SemanticIndex == 0 || x.Value == inputElement.SemanticName + inputElement.SemanticIndex);
                if (location.Value != null)
                {
                    inputAttributes[inputAttributeCount++] = new VertexInputAttributeDescription
                    {
                        Format   = format,
                        Offset   = (uint)inputElement.AlignedByteOffset,
                        Binding  = (uint)inputElement.InputSlot,
                        Location = (uint)location.Key
                    };
                }

                inputBindings[slotIndex].Binding   = (uint)slotIndex;
                inputBindings[slotIndex].InputRate = inputElement.InputSlotClass == InputClassification.Vertex ? VertexInputRate.Vertex : VertexInputRate.Instance;

                // TODO VULKAN: This is currently an argument to Draw() overloads.
                if (inputBindings[slotIndex].Stride < inputElement.AlignedByteOffset + size)
                {
                    inputBindings[slotIndex].Stride = (uint)(inputElement.AlignedByteOffset + size);
                }

                if (inputElement.InputSlot >= inputBindingCount)
                {
                    inputBindingCount = inputElement.InputSlot + 1;
                }
            }

            var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo
            {
                StructureType          = StructureType.PipelineInputAssemblyStateCreateInfo,
                Topology               = VulkanConvertExtensions.ConvertPrimitiveType(Description.PrimitiveType),
                PrimitiveRestartEnable = VulkanConvertExtensions.ConvertPrimitiveRestart(Description.PrimitiveType),
            };

            // TODO VULKAN: Tessellation and multisampling
            var multisampleState = new PipelineMultisampleStateCreateInfo
            {
                StructureType        = StructureType.PipelineMultisampleStateCreateInfo,
                RasterizationSamples = SampleCountFlags.Sample1
            };

            //var tessellationState = new PipelineTessellationStateCreateInfo();

            var rasterizationState = new PipelineRasterizationStateCreateInfo
            {
                StructureType           = StructureType.PipelineRasterizationStateCreateInfo,
                CullMode                = VulkanConvertExtensions.ConvertCullMode(Description.RasterizerState.CullMode),
                FrontFace               = Description.RasterizerState.FrontFaceCounterClockwise ? FrontFace.CounterClockwise : FrontFace.Clockwise,
                PolygonMode             = VulkanConvertExtensions.ConvertFillMode(Description.RasterizerState.FillMode),
                DepthBiasEnable         = true, // TODO VULKAN
                DepthBiasConstantFactor = Description.RasterizerState.DepthBias,
                DepthBiasSlopeFactor    = Description.RasterizerState.SlopeScaleDepthBias,
                DepthBiasClamp          = Description.RasterizerState.DepthBiasClamp,
                LineWidth               = 1.0f,
                DepthClampEnable        = !Description.RasterizerState.DepthClipEnable,
                RasterizerDiscardEnable = false,
            };

            var depthStencilState = new PipelineDepthStencilStateCreateInfo
            {
                StructureType     = StructureType.PipelineDepthStencilStateCreateInfo,
                DepthTestEnable   = Description.DepthStencilState.DepthBufferEnable,
                StencilTestEnable = Description.DepthStencilState.StencilEnable,
                DepthWriteEnable  = Description.DepthStencilState.DepthBufferWriteEnable,

                MinDepthBounds        = 0.0f,
                MaxDepthBounds        = 1.0f,
                DepthCompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.DepthBufferFunction),
                Front = new StencilOperationState
                {
                    CompareOperation   = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.FrontFace.StencilFunction),
                    DepthFailOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilDepthBufferFail),
                    FailOperation      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilFail),
                    PassOperation      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilPass),
                    CompareMask        = Description.DepthStencilState.StencilMask,
                    WriteMask          = Description.DepthStencilState.StencilWriteMask
                },
                Back = new StencilOperationState
                {
                    CompareOperation   = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.BackFace.StencilFunction),
                    DepthFailOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilDepthBufferFail),
                    FailOperation      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilFail),
                    PassOperation      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilPass),
                    CompareMask        = Description.DepthStencilState.StencilMask,
                    WriteMask          = Description.DepthStencilState.StencilWriteMask
                }
            };

            var description = Description.BlendState;

            var colorBlendAttachments = new PipelineColorBlendAttachmentState[renderTargetCount];

            var renderTargetBlendState = &description.RenderTarget0;

            for (int i = 0; i < renderTargetCount; i++)
            {
                colorBlendAttachments[i] = new PipelineColorBlendAttachmentState
                {
                    BlendEnable                 = renderTargetBlendState->BlendEnable,
                    AlphaBlendOperation         = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->AlphaBlendFunction),
                    ColorBlendOperation         = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->ColorBlendFunction),
                    DestinationAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaDestinationBlend),
                    DestinationColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorDestinationBlend),
                    SourceAlphaBlendFactor      = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaSourceBlend),
                    SourceColorBlendFactor      = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorSourceBlend),
                    ColorWriteMask              = VulkanConvertExtensions.ConvertColorWriteChannels(renderTargetBlendState->ColorWriteChannels),
                };

                if (description.IndependentBlendEnable)
                {
                    renderTargetBlendState++;
                }
            }

            var viewportState = new PipelineViewportStateCreateInfo
            {
                StructureType = StructureType.PipelineViewportStateCreateInfo,
                ScissorCount  = 1,
                ViewportCount = 1,
            };

            fixed(void *dynamicStatesPointer   = dynamicStates.Length == 0?null : dynamicStates,
                  inputAttributesPointer       = inputAttributes.Length == 0?null : inputAttributes,
                  inputBindingsPointer         = inputBindings.Length == 0?null : inputBindings,
                  colorBlendAttachmentsPointer = colorBlendAttachments.Length == 0?null : colorBlendAttachments,
                  stagesPointer = stages.Length == 0?null : stages)
            {
                var vertexInputState = new PipelineVertexInputStateCreateInfo
                {
                    StructureType = StructureType.PipelineVertexInputStateCreateInfo,
                    VertexAttributeDescriptionCount = (uint)inputAttributeCount,
                    VertexAttributeDescriptions     = (IntPtr)inputAttributesPointer,
                    VertexBindingDescriptionCount   = (uint)inputBindingCount,
                    VertexBindingDescriptions       = (IntPtr)inputBindingsPointer,
                };

                var colorBlendState = new PipelineColorBlendStateCreateInfo
                {
                    StructureType   = StructureType.PipelineColorBlendStateCreateInfo,
                    AttachmentCount = (uint)renderTargetCount,
                    Attachments     = (IntPtr)colorBlendAttachmentsPointer,
                };

                var dynamicState = new PipelineDynamicStateCreateInfo
                {
                    StructureType     = StructureType.PipelineDynamicStateCreateInfo,
                    DynamicStateCount = (uint)dynamicStates.Length,
                    DynamicStates     = (IntPtr)dynamicStatesPointer,
                };

                var createInfo = new GraphicsPipelineCreateInfo
                {
                    StructureType = StructureType.GraphicsPipelineCreateInfo,
                    StageCount    = (uint)stages.Length,
                    Stages        = (IntPtr)stagesPointer,
                    //TessellationState = new IntPtr(&tessellationState),
                    VertexInputState   = new IntPtr(&vertexInputState),
                    InputAssemblyState = new IntPtr(&inputAssemblyState),
                    RasterizationState = new IntPtr(&rasterizationState),
                    MultisampleState   = new IntPtr(&multisampleState),
                    DepthStencilState  = new IntPtr(&depthStencilState),
                    ColorBlendState    = new IntPtr(&colorBlendState),
                    DynamicState       = new IntPtr(&dynamicState),
                    ViewportState      = new IntPtr(&viewportState),
                    Subpass            = 0,
                };

                using (GraphicsDevice.QueueLock.ReadLock())
                {
                    NativeRenderPass = GraphicsDevice.NativeDevice.CreateRenderPass(ref renderPassCreateInfo);
                    NativeLayout     = GraphicsDevice.NativeDevice.CreatePipelineLayout(ref pipelineLayoutCreateInfo);

                    createInfo.Layout     = NativeLayout;
                    createInfo.RenderPass = NativeRenderPass;

                    try {
                        NativePipeline = GraphicsDevice.NativeDevice.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo);
                    } catch (Exception e) {
                        errorDuringCreate = true;
                        NativePipeline    = Pipeline.Null;
                    }
                }
            }

            // Cleanup shader modules
            for (int i = 0; i < stages.Length; i++)
            {
                GraphicsDevice.NativeDevice.DestroyShaderModule(stages[i].Module);
            }
        }
コード例 #10
0
        private unsafe void Recreate()
        {
            if (Description.RootSignature == null)
                return;

            CreateRenderPass(Description);

            CreatePipelineLayout(Description);

            // Create shader stages
            Dictionary<int, string> inputAttributeNames;
            var stages = CreateShaderStages(Description, out inputAttributeNames);

            var inputAttributes = new VertexInputAttributeDescription[Description.InputElements.Length];
            int inputAttributeCount = 0;
            var inputBindings = new VertexInputBindingDescription[inputAttributes.Length];
            int inputBindingCount = 0;

            for (int inputElementIndex = 0; inputElementIndex < inputAttributes.Length; inputElementIndex++)
            {
                var inputElement = Description.InputElements[inputElementIndex];
                var slotIndex = inputElement.InputSlot;

                if (inputElement.InstanceDataStepRate > 1)
                {
                    throw new NotImplementedException();
                }

                Format format;
                int size;
                bool isCompressed;
                VulkanConvertExtensions.ConvertPixelFormat(inputElement.Format, out format, out size, out isCompressed);

                var location = inputAttributeNames.FirstOrDefault(x => x.Value == inputElement.SemanticName && inputElement.SemanticIndex == 0 || x.Value == inputElement.SemanticName + inputElement.SemanticIndex);
                if (location.Value != null)
                {
                    inputAttributes[inputAttributeCount++] = new VertexInputAttributeDescription
                    {
                        Format = format,
                        Offset = (uint)inputElement.AlignedByteOffset,
                        Binding = (uint)inputElement.InputSlot,
                        Location = (uint)location.Key
                    };
                }

                inputBindings[slotIndex].Binding = (uint)slotIndex;
                inputBindings[slotIndex].InputRate = inputElement.InputSlotClass == InputClassification.Vertex ? VertexInputRate.Vertex : VertexInputRate.Instance;

                // TODO VULKAN: This is currently an argument to Draw() overloads.
                if (inputBindings[slotIndex].Stride < inputElement.AlignedByteOffset + size)
                    inputBindings[slotIndex].Stride = (uint)(inputElement.AlignedByteOffset + size);

                if (inputElement.InputSlot >= inputBindingCount)
                    inputBindingCount = inputElement.InputSlot + 1;
            }

            var inputAssemblyState = new PipelineInputAssemblyStateCreateInfo
            {
                StructureType = StructureType.PipelineInputAssemblyStateCreateInfo,
                Topology = VulkanConvertExtensions.ConvertPrimitiveType(Description.PrimitiveType),
                PrimitiveRestartEnable = true,
            };

            // TODO VULKAN: Tessellation and multisampling
            var multisampleState = new PipelineMultisampleStateCreateInfo
            {
                StructureType = StructureType.PipelineMultisampleStateCreateInfo,
                RasterizationSamples = SampleCountFlags.Sample1
            };

            var tessellationState = new PipelineTessellationStateCreateInfo();

            var rasterizationState = CreateRasterizationState(Description.RasterizerState);

            var depthStencilState = CreateDepthStencilState(Description);

            var description = Description.BlendState;

            var renderTargetCount = Description.Output.RenderTargetCount;
            var colorBlendAttachments = new PipelineColorBlendAttachmentState[renderTargetCount];

            var renderTargetBlendState = &description.RenderTarget0;
            for (int i = 0; i < renderTargetCount; i++)
            {
                colorBlendAttachments[i] = new PipelineColorBlendAttachmentState
                {
                    BlendEnable = renderTargetBlendState->BlendEnable,
                    AlphaBlendOperation = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->AlphaBlendFunction),
                    ColorBlendOperation = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->ColorBlendFunction),
                    DestinationAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaDestinationBlend),
                    DestinationColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorDestinationBlend),
                    SourceAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaSourceBlend),
                    SourceColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorSourceBlend),
                    ColorWriteMask = VulkanConvertExtensions.ConvertColorWriteChannels(renderTargetBlendState->ColorWriteChannels),
                };

                if (description.IndependentBlendEnable)
                    renderTargetBlendState++;
            }

            var viewportState = new PipelineViewportStateCreateInfo
            {
                StructureType = StructureType.PipelineViewportStateCreateInfo,
                ScissorCount = 1,
                ViewportCount = 1,
            };

            fixed (DynamicState* dynamicStatesPointer = &dynamicStates[0])
            {
                var vertexInputState = new PipelineVertexInputStateCreateInfo
                {
                    StructureType = StructureType.PipelineVertexInputStateCreateInfo,
                    VertexAttributeDescriptionCount = (uint)inputAttributeCount,
                    VertexAttributeDescriptions = inputAttributes.Length > 0 ? new IntPtr(Interop.Fixed(inputAttributes)) : IntPtr.Zero,
                    VertexBindingDescriptionCount = (uint)inputBindingCount,
                    VertexBindingDescriptions = inputBindings.Length > 0 ? new IntPtr(Interop.Fixed(inputBindings)) : IntPtr.Zero,
                };

                var colorBlendState = new PipelineColorBlendStateCreateInfo
                {
                    StructureType = StructureType.PipelineColorBlendStateCreateInfo,
                    AttachmentCount = (uint)renderTargetCount,
                    Attachments = colorBlendAttachments.Length > 0 ? new IntPtr(Interop.Fixed(colorBlendAttachments)) : IntPtr.Zero,
                };

                var dynamicState = new PipelineDynamicStateCreateInfo
                {
                    StructureType = StructureType.PipelineDynamicStateCreateInfo,
                    DynamicStateCount = (uint)dynamicStates.Length,
                    DynamicStates = new IntPtr(dynamicStatesPointer)
                };

                var createInfo = new GraphicsPipelineCreateInfo
                {
                    StructureType = StructureType.GraphicsPipelineCreateInfo,
                    Layout = NativeLayout,
                    StageCount = (uint)stages.Length,
                    Stages = stages.Length > 0 ? new IntPtr(Interop.Fixed(stages)) : IntPtr.Zero,
                    //TessellationState = new IntPtr(&tessellationState),
                    VertexInputState = new IntPtr(&vertexInputState),
                    InputAssemblyState = new IntPtr(&inputAssemblyState),
                    RasterizationState = new IntPtr(&rasterizationState),
                    MultisampleState = new IntPtr(&multisampleState),
                    DepthStencilState = new IntPtr(&depthStencilState),
                    ColorBlendState = new IntPtr(&colorBlendState),
                    DynamicState = new IntPtr(&dynamicState),
                    ViewportState = new IntPtr(&viewportState),
                    RenderPass = NativeRenderPass,
                    Subpass = 0,
                };
                NativePipeline = GraphicsDevice.NativeDevice.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo);
            }

            // Cleanup shader modules
            foreach (var stage in stages)
            {
                GraphicsDevice.NativeDevice.DestroyShaderModule(stage.Module);
            }
        }