Esempio n. 1
0
        public void ReflectionFromSpirv_Succeeds(
            string vertex, string fragment,
            VertexElementDescription[] verts,
            ResourceLayoutDescription[] layouts)
        {
            byte[] vsBytes = TestUtil.LoadBytes(vertex);
            byte[] fsBytes = TestUtil.LoadBytes(fragment);
            VertexFragmentCompilationResult result = SpirvCompilation.CompileVertexFragment(
                vsBytes,
                fsBytes,
                CrossCompileTarget.HLSL);

            VertexElementDescription[] reflectedVerts = result.Reflection.VertexElements;
            Assert.Equal(verts.Length, reflectedVerts.Length);
            for (int i = 0; i < verts.Length; i++)
            {
                Assert.Equal(verts[i], reflectedVerts[i]);
            }

            ResourceLayoutDescription[] reflectedLayouts = result.Reflection.ResourceLayouts;
            Assert.Equal(layouts.Length, reflectedLayouts.Length);
            for (int i = 0; i < layouts.Length; i++)
            {
                ResourceLayoutDescription layout          = layouts[i];
                ResourceLayoutDescription reflectedLayout = reflectedLayouts[i];
                Assert.Equal(layout.Elements.Length, reflectedLayout.Elements.Length);
                for (int j = 0; j < layout.Elements.Length; j++)
                {
                    Assert.Equal(layout.Elements[j], reflectedLayout.Elements[j]);
                }
            }
        }
Esempio n. 2
0
        public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl)
        {
            var factory = new DisposingResourceFactoryFacade(gd.ResourceFactory, _disposer);

            DeviceBuffer MakeBuffer(uint size, string name)
            {
                var buffer = factory.CreateBuffer(
                    new BufferDescription(size, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

                buffer.Name = name;
                return(buffer);
            }

            ProjectionMatrixBuffer = MakeBuffer(64, "M_Projection");
            ModelViewMatrixBuffer  = MakeBuffer(64, "M_View");
            IdentityMatrixBuffer   = MakeBuffer(64, "M_Id");
            DepthLimitsBuffer      = MakeBuffer((uint)Unsafe.SizeOf <DepthCascadeLimits>(), "B_DepthLimits");
            CameraInfoBuffer       = MakeBuffer((uint)Unsafe.SizeOf <CameraInfo>(), "B_CameraInfo");

            cl.UpdateBuffer(IdentityMatrixBuffer, 0, Matrix4x4.Identity);

            var commonLayoutDescription = new ResourceLayoutDescription(
                ResourceLayoutHelper.Uniform("vdspv_1_0"),  // CameraInfo / common data buffer
                ResourceLayoutHelper.UniformV("vdspv_1_1"), // Perspective Matrix
                ResourceLayoutHelper.UniformV("vdspv_1_2"), // View Matrix
                ResourceLayoutHelper.Texture("vdspv_1_3")); // PaletteTexture

            CommonResourceLayout      = factory.CreateResourceLayout(commonLayoutDescription);
            CommonResourceLayout.Name = "RL_Common";

            _windowSized = new WindowSizedSceneContext(gd, MainSceneSampleCount);
            _disposer.Add(_windowSized, CommonResourceLayout);
        }
Esempio n. 3
0
        public VkResourceLayout(VkGraphicsDevice gd, ref ResourceLayoutDescription description)
        {
            _gd = gd;
            VkDescriptorSetLayoutCreateInfo dslCI = VkDescriptorSetLayoutCreateInfo.New();

            ResourceLayoutElementDescription[] elements = description.Elements;
            _descriptorTypes = new VkDescriptorType[elements.Length];
            VkDescriptorSetLayoutBinding *bindings = stackalloc VkDescriptorSetLayoutBinding[elements.Length];

            for (uint i = 0; i < elements.Length; i++)
            {
                bindings[i].binding         = i;
                bindings[i].descriptorCount = 1;
                VkDescriptorType descriptorType = VkFormats.VdToVkDescriptorType(elements[i].Kind);
                bindings[i].descriptorType = descriptorType;
                bindings[i].stageFlags     = VkFormats.VdToVkShaderStages(elements[i].Stages);

                _descriptorTypes[i] = descriptorType;
            }

            dslCI.bindingCount = (uint)elements.Length;
            dslCI.pBindings    = bindings;

            VkResult result = vkCreateDescriptorSetLayout(_gd.Device, ref dslCI, null, out _dsl);

            CheckResult(result);
        }
Esempio n. 4
0
        private List <IDisposable> createTransformationPipelineUniform()
        {
            _transformationPipelineBuffer = _factory.CreateBuffer(new BufferDescription(192, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            ResourceLayoutElementDescription resourceLayoutElementDescription = new ResourceLayoutElementDescription("transformPipeline", ResourceKind.UniformBuffer, ShaderStages.Vertex);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription };
            ResourceLayoutDescription          resourceLayoutDescription         = new ResourceLayoutDescription(resourceLayoutElementDescriptions);

            BindableResource[] bindableResources = new BindableResource[] { _transformationPipelineBuffer };

            _transformationPipelineResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription);
            ResourceSetDescription resourceSetDescription = new ResourceSetDescription(_transformationPipelineResourceLayout, bindableResources);

            _transformationPipelineResourceSet = _factory.CreateResourceSet(resourceSetDescription);

            //_graphicsDevice.UpdateBuffer(_transformationPipelineBuffer,0,_camera.ViewMatrix);
            GraphicsDevice.UpdateBuffer(_transformationPipelineBuffer, 64, Camera.ProjectionMatrix);

            return(new List <IDisposable>()
            {
                _transformationPipelineBuffer,
                _transformationPipelineResourceLayout,
                _transformationPipelineResourceSet
            });
        }
Esempio n. 5
0
        public override ResourceLayout CreateResourceLayout(ref ResourceLayoutDescription description)
        {
            ResourceLayout layout = Factory.CreateResourceLayout(ref description);

            DisposeCollector.Add(layout);
            return(layout);
        }
Esempio n. 6
0
        public static ResourceLayout GenerateResourceLayout(DisposeCollectorResourceFactory factory, string name, ResourceKind resourceKind, ShaderStages shaderStages)
        {
            var resourceLayoutElementDescription = new ResourceLayoutElementDescription(name, resourceKind, shaderStages);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription };
            var resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions);

            return(factory.CreateResourceLayout(resourceLayoutDescription));
        }
Esempio n. 7
0
        public MTLResourceLayout(ref ResourceLayoutDescription description, MTLGraphicsDevice gd)
            : base(ref description)
        {
            ResourceLayoutElementDescription[] elements = description.Elements;
#if !VALIDATE_USAGE
            ResourceKinds = new ResourceKind[elements.Length];
            for (int i = 0; i < elements.Length; i++)
            {
                ResourceKinds[i] = elements[i].Kind;
            }
#endif

            _bindingInfosByVdIndex = new ResourceBindingInfo[elements.Length];

            uint bufferIndex  = 0;
            uint texIndex     = 0;
            uint samplerIndex = 0;

            for (int i = 0; i < _bindingInfosByVdIndex.Length; i++)
            {
                uint slot;
                switch (elements[i].Kind)
                {
                case ResourceKind.UniformBuffer:
                    slot = bufferIndex++;
                    break;

                case ResourceKind.StructuredBufferReadOnly:
                    slot = bufferIndex++;
                    break;

                case ResourceKind.StructuredBufferReadWrite:
                    slot = bufferIndex++;
                    break;

                case ResourceKind.TextureReadOnly:
                    slot = texIndex++;
                    break;

                case ResourceKind.TextureReadWrite:
                    slot = texIndex++;
                    break;

                case ResourceKind.Sampler:
                    slot = samplerIndex++;
                    break;

                default: throw Illegal.Value <ResourceKind>();
                }

                _bindingInfosByVdIndex[i] = new ResourceBindingInfo(slot, elements[i].Stages, elements[i].Kind);
            }

            BufferCount  = bufferIndex;
            TextureCount = texIndex;
            SamplerCount = samplerIndex;
        }
Esempio n. 8
0
        public TexturePool(GraphicsDevice d, string name, uint poolsize)
        {
            _resourceName = name;
            TextureCount  = poolsize;

            var layoutdesc = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription(_resourceName, ResourceKind.TextureReadOnly, ShaderStages.Fragment, TextureCount));

            _poolLayout = d.ResourceFactory.CreateResourceLayout(layoutdesc);
        }
Esempio n. 9
0
        public D3D11ResourceLayout(ref ResourceLayoutDescription description)
            : base(ref description)
        {
            ResourceLayoutElementDescription[] elements = description.Elements;
            _bindingInfosByVdIndex = new ResourceBindingInfo[elements.Length];

            int cbIndex              = 0;
            int texIndex             = 0;
            int samplerIndex         = 0;
            int unorderedAccessIndex = 0;

            for (int i = 0; i < _bindingInfosByVdIndex.Length; i++)
            {
                int slot;
                switch (elements[i].Kind)
                {
                case ResourceKind.UniformBuffer:
                    slot = cbIndex++;
                    break;

                case ResourceKind.StructuredBufferReadOnly:
                    slot = texIndex++;
                    break;

                case ResourceKind.StructuredBufferReadWrite:
                    slot = unorderedAccessIndex++;
                    break;

                case ResourceKind.TextureReadOnly:
                    slot = texIndex++;
                    break;

                case ResourceKind.TextureReadWrite:
                    slot = unorderedAccessIndex++;
                    break;

                case ResourceKind.Sampler:
                    slot = samplerIndex++;
                    break;

                default: throw Illegal.Value <ResourceKind>();
                }

                _bindingInfosByVdIndex[i] = new ResourceBindingInfo(
                    slot,
                    elements[i].Stages,
                    elements[i].Kind,
                    (elements[i].Options & ResourceLayoutElementOptions.DynamicBinding) != 0);
            }

            UniformBufferCount = cbIndex;
            StorageBufferCount = unorderedAccessIndex;
            TextureCount       = texIndex;
            SamplerCount       = samplerIndex;
        }
        private ResourceLayout _createLayoutOfResource(string name, ResourceKind resourceKind, ShaderStages shaderStages)
        {
            var resourceLayoutDescription = new ResourceLayoutDescription(new ResourceLayoutElementDescription[]
            {
                new ResourceLayoutElementDescription(name, resourceKind, shaderStages),
            });

            var resourceLayout = _resourceFactory.CreateResourceLayout(resourceLayoutDescription);

            _resourceLayouts.Add(resourceLayout);

            return(resourceLayout);
        }
Esempio n. 11
0
        public Shader(string path)
        {
            var vertexCode   = File.ReadAllText($"{path}.vert");
            var fragmentCode = File.ReadAllText($"{path}.frag");

            // TODO: Make generic, together with RenderObject
            // Probably requires waiting for Veldrid.SPIRV update
            var shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                Renderer.ResourceFactory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexCode), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragmentCode), "main")));

            var matrixDescription = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("MVP", ResourceKind.UniformBuffer, ShaderStages.Vertex));

            var textureDescription = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly,
                                                     ShaderStages.Fragment),
                new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler,
                                                     ShaderStages.Fragment));

            MatrixLayout = Renderer.ResourceFactory.CreateResourceLayout(matrixDescription);

            TextureLayout = Renderer.ResourceFactory.CreateResourceLayout(textureDescription);

            var pipelineDescription = new GraphicsPipelineDescription
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerState   = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid,
                    frontFace: FrontFace.Clockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                ResourceLayouts   = new[] { MatrixLayout, TextureLayout },
                ShaderSet         = shaderSet,
                Outputs           = Renderer.GraphicsDevice.SwapchainFramebuffer.OutputDescription
            };

            Pipeline = Renderer.ResourceFactory.CreateGraphicsPipeline(pipelineDescription);
        }
Esempio n. 12
0
        public static void Init(GraphicsDevice Dev)
        {
            ResourceLayoutDescription TexDesc = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                new ResourceLayoutElementDescription("Smp", ResourceKind.Sampler, ShaderStages.Fragment)
                );

            TextureLayout = Dev.ResourceFactory.CreateResourceLayout(TexDesc);

            ResourceLayoutDescription UniformsDesc = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("Uniforms", ResourceKind.UniformBuffer, ShaderStages.Fragment)
                );

            UniformsLayout = Dev.ResourceFactory.CreateResourceLayout(UniformsDesc);
        }
Esempio n. 13
0
        public TexturePool(GraphicsDevice d, string name, uint poolsize)
        {
            _resourceName = name;
            TextureCount  = poolsize;
            _allocator    = new FreeListAllocator(poolsize);
            for (int i = 0; i < poolsize; i++)
            {
                _handles.Add(null);
            }

            var layoutdesc = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription(_resourceName, ResourceKind.TextureReadOnly, ShaderStages.Fragment, TextureCount));

            _poolLayout = d.ResourceFactory.CreateResourceLayout(layoutdesc);
        }
Esempio n. 14
0
        public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl)
        {
            if (gd == null)
            {
                throw new ArgumentNullException(nameof(gd));
            }
            if (cl == null)
            {
                throw new ArgumentNullException(nameof(cl));
            }
            var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposer);

            DeviceBuffer MakeBuffer(uint size, string name)
            {
                var buffer = factory.CreateBuffer(
                    new BufferDescription(size, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

                buffer.Name = name;
                return(buffer);
            }

            ProjectionMatrixBuffer = MakeBuffer(64, "M_Projection");
            ModelViewMatrixBuffer  = MakeBuffer(64, "M_View");
            IdentityMatrixBuffer   = MakeBuffer(64, "M_Id");
            DepthLimitsBuffer      = MakeBuffer((uint)Unsafe.SizeOf <DepthCascadeLimits>(), "B_DepthLimits");
            CameraInfoBuffer       = MakeBuffer((uint)Unsafe.SizeOf <CameraInfo>(), "B_CameraInfo");

            cl.UpdateBuffer(IdentityMatrixBuffer, 0, Matrix4x4.Identity);

            var commonLayoutDescription = new ResourceLayoutDescription(
                ResourceLayoutHelper.Uniform("_Shared"),      // CameraInfo / common data buffer
                ResourceLayoutHelper.UniformV("_Projection"), // Perspective Matrix
                ResourceLayoutHelper.UniformV("_View"),       // View Matrix
                ResourceLayoutHelper.Texture("uPalette"));    // PaletteTexture

            CommonResourceLayout      = factory.CreateResourceLayout(commonLayoutDescription);
            CommonResourceLayout.Name = "RL_Common";
        }
Esempio n. 15
0
        public static void Initialize(GraphicsDevice d)
        {
            var layoutdesc = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("linearSampler", ResourceKind.Sampler, ShaderStages.Fragment, ResourceLayoutElementOptions.None),
                new ResourceLayoutElementDescription("anisoLinearSampler", ResourceKind.Sampler, ShaderStages.Fragment, ResourceLayoutElementOptions.None));

            SamplersLayout = d.ResourceFactory.CreateResourceLayout(layoutdesc);

            _linearSampler = d.ResourceFactory.CreateSampler(new SamplerDescription(
                                                                 SamplerAddressMode.Wrap, SamplerAddressMode.Wrap, SamplerAddressMode.Wrap,
                                                                 SamplerFilter.MinLinear_MagLinear_MipLinear,
                                                                 null, 0, 0, 15, 0, SamplerBorderColor.OpaqueBlack
                                                                 ));
            _anisoLinearSampler = d.ResourceFactory.CreateSampler(new SamplerDescription(
                                                                      SamplerAddressMode.Wrap, SamplerAddressMode.Wrap, SamplerAddressMode.Wrap,
                                                                      SamplerFilter.Anisotropic,
                                                                      null, 16, 0, 15, 0, SamplerBorderColor.OpaqueBlack
                                                                      ));

            var setdesc = new ResourceSetDescription(SamplersLayout, new [] { _linearSampler, _anisoLinearSampler });

            SamplersSet = d.ResourceFactory.CreateResourceSet(setdesc);
        }
Esempio n. 16
0
        public D3D11ResourceLayout(ref ResourceLayoutDescription description)
        {
            ResourceLayoutElementDescription[] elements = description.Elements;
            _bindingInfosByVdIndex = new ResourceBindingInfo[elements.Length];

            int cbIndex      = 0;
            int texIndex     = 0;
            int samplerIndex = 0;

            for (int i = 0; i < _bindingInfosByVdIndex.Length; i++)
            {
                int slot;
                switch (elements[i].Kind)
                {
                case ResourceKind.Uniform:
                    slot = cbIndex++;
                    break;

                case ResourceKind.Texture:
                    slot = texIndex++;
                    break;

                case ResourceKind.Sampler:
                    slot = samplerIndex++;
                    break;

                default: throw Illegal.Value <ResourceKind>();
                }

                _bindingInfosByVdIndex[i] = new ResourceBindingInfo(slot, elements[i].Stages);
            }

            UniformBufferCount = cbIndex;
            TextureCount       = texIndex;
            SamplerCount       = samplerIndex;
        }
Esempio n. 17
0
        override protected void CreateResources()
        {
            _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(128, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            ResourceLayoutElementDescription resourceLayoutElementDescription = new ResourceLayoutElementDescription("projView", ResourceKind.UniformBuffer, ShaderStages.Vertex);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription };
            ResourceLayoutDescription          resourceLayoutDescription         = new ResourceLayoutDescription(resourceLayoutElementDescriptions);

            BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer };

            _resourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription);
            ResourceSetDescription resourceSetDescription = new ResourceSetDescription(_resourceLayout, bindableResources);

            _resourceSet = _factory.CreateResourceSet(resourceSetDescription);

            Mesh <VertexPositionNDCColor> coloredQuad
                = GeometryFactory.GenerateColorQuadNDC_XY(RgbaFloat.Red, RgbaFloat.Green, RgbaFloat.Blue, RgbaFloat.Yellow);

            ushort[] quadIndicies = GeometryFactory.GenerateQuadIndicies_TriangleStrip_CW();

            float[] _xOffset = { -2f, 2f };

            // declare (VBO) buffers
            _vertexBuffer
                = _factory.CreateBuffer(new BufferDescription(coloredQuad.Vertices.LengthUnsigned() * VertexPositionNDCColor.SizeInBytes, BufferUsage.VertexBuffer));
            _indexBuffer
                = _factory.CreateBuffer(new BufferDescription(quadIndicies.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer));
            _xOffsetBuffer
                = _factory.CreateBuffer(new BufferDescription(_xOffset.LengthUnsigned() * sizeof(float), BufferUsage.VertexBuffer));

            // fill buffers with data
            GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, coloredQuad.Vertices);
            GraphicsDevice.UpdateBuffer(_indexBuffer, 0, quadIndicies);
            GraphicsDevice.UpdateBuffer(_xOffsetBuffer, 0, _xOffset);
            GraphicsDevice.UpdateBuffer(_cameraProjViewBuffer, 0, Camera.ViewMatrix);
            GraphicsDevice.UpdateBuffer(_cameraProjViewBuffer, 64, Camera.ProjectionMatrix);

            VertexLayoutDescription vertexLayout
                = new VertexLayoutDescription(
                      new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2),
                      new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float4)
                      );

            VertexElementDescription vertexElementPerInstance
                = new VertexElementDescription("xOff", VertexElementSemantic.Position, VertexElementFormat.Float1);

            VertexLayoutDescription vertexLayoutPerInstance
                = new VertexLayoutDescription(
                      stride: 4,
                      instanceStepRate: 1,
                      elements: new VertexElementDescription[] { vertexElementPerInstance }
                      );

            _vertexShader   = IO.LoadShader("OffsetXNDCColor", ShaderStages.Vertex, GraphicsDevice);
            _fragmentShader = IO.LoadShader("Color", ShaderStages.Fragment, GraphicsDevice);

            GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription()
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = new DepthStencilStateDescription(
                    depthTestEnabled: true,
                    depthWriteEnabled: true,
                    comparisonKind: ComparisonKind.LessEqual),
                RasterizerState = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid,
                    frontFace: FrontFace.Clockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false
                    ),
                PrimitiveTopology = PrimitiveTopology.TriangleStrip,
                ResourceLayouts   = new ResourceLayout[] { _resourceLayout },
                ShaderSet         = new ShaderSetDescription(
                    vertexLayouts: new VertexLayoutDescription[] { vertexLayout, vertexLayoutPerInstance },
                    shaders: new Shader[] { _vertexShader, _fragmentShader }
                    ),
                Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription
            };

            _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription);
        }
Esempio n. 18
0
 public OpenGLResourceLayout(ref ResourceLayoutDescription description)
     : base(ref description)
 {
     Description = description;
 }
Esempio n. 19
0
 public override ResourceLayout CreateResourceLayout(ref ResourceLayoutDescription description)
 {
     return(new D3D11ResourceLayout(ref description));
 }
Esempio n. 20
0
 /// <summary>
 /// Creates a new <see cref="ResourceLayout"/>.
 /// </summary>
 /// <param name="description">The desired properties of the created object.</param>
 /// <returns>A new <see cref="ResourceLayout"/>.</returns>
 public abstract ResourceLayout CreateResourceLayout(ref ResourceLayoutDescription description);
Esempio n. 21
0
        protected override async void InternalLoad()
        {
            var swapChainDescription = this.swapChain?.SwapChainDescription;

            this.width  = swapChainDescription.Value.Width;
            this.height = swapChainDescription.Value.Height;

            // Create Scene
            BasicScene();

            // Compute Resources
            var spheresBufferDescription = new BufferDescription(
                (uint)(Unsafe.SizeOf <Sphere>() * spheres.Length),
                BufferFlags.UnorderedAccess | BufferFlags.ShaderResource | BufferFlags.BufferStructured,
                ResourceUsage.Default,
                ResourceCpuAccess.None,
                Unsafe.SizeOf <Sphere>());

            spheresBuffer = this.graphicsContext.Factory.CreateBuffer(spheres, ref spheresBufferDescription);

            var materialsBufferDescription = new BufferDescription(
                (uint)(Unsafe.SizeOf <Material>() * spheres.Length),
                BufferFlags.UnorderedAccess | BufferFlags.ShaderResource | BufferFlags.BufferStructured,
                ResourceUsage.Default,
                ResourceCpuAccess.None,
                Unsafe.SizeOf <Material>());

            materialsBuffer = this.graphicsContext.Factory.CreateBuffer(materials, ref materialsBufferDescription);

            this.threadGroupX = this.width / 16u;
            this.threadGroupY = this.height / 16u;

            CompilerParameters parameters = new CompilerParameters()
            {
                CompilationMode = CompilationMode.None,
                Profile         = GraphicsProfile.Level_11_0,
            };

            var computeShaderDescription = await this.assetsDirectory.ReadAndCompileShader(this.graphicsContext, "CS", "ComputeShader", ShaderStages.Compute, "CS", parameters);

            var computeShader = this.graphicsContext.Factory.CreateShader(ref computeShaderDescription);

            var textureDescription = new TextureDescription()
            {
                Type        = TextureType.Texture2D,
                Usage       = ResourceUsage.Default,
                Flags       = TextureFlags.UnorderedAccess | TextureFlags.ShaderResource,
                Format      = PixelFormat.R8G8B8A8_UNorm,
                Width       = this.width,
                Height      = this.height,
                Depth       = 1,
                MipLevels   = 1,
                ArraySize   = 1,
                CpuAccess   = ResourceCpuAccess.None,
                SampleCount = TextureSampleCount.None,
            };

            Texture texture2D = this.graphicsContext.Factory.CreateTexture(ref textureDescription);

            this.computeData = new ComputeData()
            {
                time        = 0,
                width       = this.width,
                height      = this.height,
                framecount  = 0,
                samples     = 25,
                recursion   = 5,
                spherecount = (uint)spheres.Length,
                cam         = this.cam
            };

            var constantBufferDescription = new BufferDescription((uint)Unsafe.SizeOf <ComputeData>(), BufferFlags.ConstantBuffer, ResourceUsage.Default);

            this.constantBuffer = this.graphicsContext.Factory.CreateBuffer(ref this.computeData, ref constantBufferDescription);

            ResourceLayoutDescription computeLayoutDescription = new ResourceLayoutDescription(
                new LayoutElementDescription(0, ResourceType.StructuredBuffer, ShaderStages.Compute),
                new LayoutElementDescription(1, ResourceType.StructuredBuffer, ShaderStages.Compute),
                new LayoutElementDescription(0, ResourceType.ConstantBuffer, ShaderStages.Compute),
                new LayoutElementDescription(0, ResourceType.TextureReadWrite, ShaderStages.Compute));

            ResourceLayout computeResourceLayout = this.graphicsContext.Factory.CreateResourceLayout(ref computeLayoutDescription);

            ResourceSetDescription computeResourceSetDescription = new ResourceSetDescription(computeResourceLayout, this.spheresBuffer, this.materialsBuffer, this.constantBuffer, texture2D);

            this.computeResourceSet = this.graphicsContext.Factory.CreateResourceSet(ref computeResourceSetDescription);

            var computePipelineDescription = new ComputePipelineDescription()
            {
                ComputeShader    = computeShader,
                ResourceLayouts  = new[] { computeResourceLayout },
                ThreadGroupSizeX = 16,
                ThreadGroupSizeY = 16,
                ThreadGroupSizeZ = 1,
            };

            this.computePipelineState = this.graphicsContext.Factory.CreateComputePipeline(ref computePipelineDescription);

            // Graphics Resources
            var vertexShaderDescription = await this.assetsDirectory.ReadAndCompileShader(this.graphicsContext, "HLSL", "VertexShader", ShaderStages.Vertex, "VS");

            var pixelShaderDescription = await this.assetsDirectory.ReadAndCompileShader(this.graphicsContext, "HLSL", "FragmentShader", ShaderStages.Pixel, "PS");

            var vertexShader = this.graphicsContext.Factory.CreateShader(ref vertexShaderDescription);
            var pixelShader  = this.graphicsContext.Factory.CreateShader(ref pixelShaderDescription);

            var samplerDescription = SamplerStates.LinearClamp;
            var samplerState       = this.graphicsContext.Factory.CreateSamplerState(ref samplerDescription);

            // Set Params
            this.paramsData.Samples       = 1;
            this.paramsData.IsPathTracing = false;

            var paramsBufferDescription = new BufferDescription((uint)Unsafe.SizeOf <Params>(), BufferFlags.ConstantBuffer, ResourceUsage.Default);

            this.paramsBuffer = this.graphicsContext.Factory.CreateBuffer(ref paramsBufferDescription);

            ResourceLayoutDescription layoutDescription = new ResourceLayoutDescription(
                new LayoutElementDescription(0, ResourceType.ConstantBuffer, ShaderStages.Pixel),
                new LayoutElementDescription(0, ResourceType.Texture, ShaderStages.Pixel),
                new LayoutElementDescription(0, ResourceType.Sampler, ShaderStages.Pixel));
            ResourceLayout resourceLayout = this.graphicsContext.Factory.CreateResourceLayout(ref layoutDescription);

            ResourceSetDescription resourceSetDescription = new ResourceSetDescription(resourceLayout, this.paramsBuffer, texture2D, samplerState);

            this.resourceSet = this.graphicsContext.Factory.CreateResourceSet(ref resourceSetDescription);

            BlendStateDescription blend = BlendStateDescription.Default;

            if (this.paramsData.IsPathTracing)
            {
                blend.RenderTarget0.BlendEnable           = true;
                blend.RenderTarget0.SourceBlendColor      = Blend.SourceAlpha;
                blend.RenderTarget0.DestinationBlendColor = Blend.InverseSourceAlpha;
            }
            else
            {
                blend = BlendStates.Opaque;
            }

            var pipelineDescription = new GraphicsPipelineDescription()
            {
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                InputLayouts      = null,
                ResourceLayouts   = new[] { resourceLayout },
                Shaders           = new ShaderStateDescription()
                {
                    VertexShader = vertexShader,
                    PixelShader  = pixelShader,
                },
                RenderStates = new RenderStateDescription()
                {
                    RasterizerState   = RasterizerStates.CullBack,
                    BlendState        = blend,
                    DepthStencilState = DepthStencilStates.Read,
                },
                Outputs = this.frameBuffer.OutputDescription,
            };

            this.graphicsPipelineState = this.graphicsContext.Factory.CreateGraphicsPipeline(ref pipelineDescription);
            this.graphicsCommandQueue  = this.graphicsContext.Factory.CreateCommandQueue(CommandQueueType.Graphics);
            this.computeCommandQueue   = this.graphicsContext.Factory.CreateCommandQueue(CommandQueueType.Compute);

            this.viewports    = new Viewport[1];
            this.viewports[0] = new Viewport(0, 0, this.width, this.height);
            this.scissors     = new Rectangle[1];
            this.scissors[0]  = new Rectangle(0, 0, (int)this.width, (int)this.height);
        }
Esempio n. 22
0
 public ResourceLayout CreateResourceLayout(ResourceLayoutDescription resourceLayoutDescription) => _factory.CreateResourceLayout(resourceLayoutDescription);
Esempio n. 23
0
 /// <summary>
 /// Creates a new <see cref="ResourceLayout"/>.
 /// </summary>
 /// <param name="description">The desired properties of the created object.</param>
 /// <returns>A new <see cref="ResourceLayout"/>.</returns>
 public ResourceLayout CreateResourceLayout(ResourceLayoutDescription description) => CreateResourceLayout(ref description);
Esempio n. 24
0
        override protected void CreateResources()
        {
            _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(Camera.SizeInBytes, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            ResourceLayoutElementDescription resourceLayoutElementDescription = new ResourceLayoutElementDescription("projView", ResourceKind.UniformBuffer, ShaderStages.Vertex);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription };
            ResourceLayoutDescription          resourceLayoutDescription         = new ResourceLayoutDescription(resourceLayoutElementDescriptions);

            BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer };

            _resourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription);
            ResourceSetDescription resourceSetDescription = new ResourceSetDescription(_resourceLayout, bindableResources);

            _cameraResourceSet = _factory.CreateResourceSet(resourceSetDescription);

            ImageSharpTexture NameImage       = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "Name.png"));
            Texture           cubeTexture     = NameImage.CreateDeviceTexture(GraphicsDevice, _factory);
            TextureView       cubeTextureView = _factory.CreateTextureView(cubeTexture);

            ResourceLayout textureLayout = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            _textureResourceSet = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                 textureLayout,
                                                                 cubeTextureView,
                                                                 GraphicsDevice.LinearSampler));

            Mesh <VertexPositionTexture> texturedCube
                = GeometryFactory.GenerateTexturedCube(false);

            ushort[] cubeIndicies = GeometryFactory.generateCubeIndicies_TriangleList_CW();

            // declare (VBO) buffers
            _vertexBuffer
                = _factory.CreateBuffer(new BufferDescription(texturedCube.Vertices.LengthUnsigned() * VertexPositionTexture.SizeInBytes, BufferUsage.VertexBuffer));
            _indexBuffer
                = _factory.CreateBuffer(new BufferDescription(cubeIndicies.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer));

            // fill buffers with data
            GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, texturedCube.Vertices);
            GraphicsDevice.UpdateBuffer(_indexBuffer, 0, cubeIndicies);
            //graphicsDevice.UpdateBuffer(_cameraProjViewBuffer,0,camera.ViewMatrix);
            //graphicsDevice.UpdateBuffer(_cameraProjViewBuffer,64,camera.ProjectionMatrix);

            VertexLayoutDescription vertexLayout
                = new VertexLayoutDescription(
                      new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                      new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)
                      );

            _vertexShader   = IO.LoadShader("Texture", ShaderStages.Vertex, GraphicsDevice);
            _fragmentShader = IO.LoadShader("Texture", ShaderStages.Fragment, GraphicsDevice);

            GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription()
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerState   = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid,
                    frontFace: FrontFace.Clockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false
                    ),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                ResourceLayouts   = new ResourceLayout[] { _resourceLayout, textureLayout },
                ShaderSet         = new ShaderSetDescription(
                    vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
                    shaders: new Shader[] { _vertexShader, _fragmentShader }
                    ),
                Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription
            };

            _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription);
        }
Esempio n. 25
0
 public OpenGLResourceLayout(ref ResourceLayoutDescription description)
     : base(ref description)
 {
     Elements = Util.ShallowClone(description.Elements);
 }
Esempio n. 26
0
 public override ResourceLayout CreateResourceLayout(ref ResourceLayoutDescription description)
 {
     return(new MTLResourceLayout(ref description, _gd));
 }
 public VertexArray(GraphicsDevice device, int capacity, PrimitiveTopology geometryType, List <Shader> shaders, uint vertexSize, ResourceLayoutDescription resourceLayoutDescription, VertexLayoutDescription vertexLayoutDescription, bool hasTexture)
 {
     this.device       = device;
     factory           = device.ResourceFactory;
     this.capacity     = (uint)capacity;
     this.geometryType = geometryType;
     Shaders           = shaders;
     this.hasTexture   = hasTexture;
     CreateResources(vertexSize, resourceLayoutDescription, vertexLayoutDescription);
 }
Esempio n. 28
0
    public static bool TryLoad(string filePath, out ShaderCacheFile result)
    {
        if (!File.Exists(filePath))
        {
            result = null;
            return(false);
        }

        using var fileStream   = File.OpenRead(filePath);
        using var binaryReader = new BinaryReader(fileStream);

        var version = binaryReader.ReadInt32();

        if (version != Version)
        {
            result = null;
            return(false);
        }

        var vsEntryPoint = binaryReader.ReadString();

        var vsBytesLength = binaryReader.ReadInt32();
        var vsBytes       = new byte[vsBytesLength];

        for (var i = 0; i < vsBytesLength; i++)
        {
            vsBytes[i] = binaryReader.ReadByte();
        }

        var fsEntryPoint = binaryReader.ReadString();

        var fsBytesLength = binaryReader.ReadInt32();
        var fsBytes       = new byte[fsBytesLength];

        for (var i = 0; i < fsBytesLength; i++)
        {
            fsBytes[i] = binaryReader.ReadByte();
        }

        var numResourceLayoutDescriptions = binaryReader.ReadInt32();
        var resourceLayoutDescriptions    = new ResourceLayoutDescription[numResourceLayoutDescriptions];

        for (var i = 0; i < numResourceLayoutDescriptions; i++)
        {
            var numElements = binaryReader.ReadInt32();

            resourceLayoutDescriptions[i] = new ResourceLayoutDescription
            {
                Elements = new ResourceLayoutElementDescription[numElements]
            };

            for (var j = 0; j < numElements; j++)
            {
                resourceLayoutDescriptions[i].Elements[j] = new ResourceLayoutElementDescription
                {
                    Name    = binaryReader.ReadString(),
                    Kind    = (ResourceKind)binaryReader.ReadByte(),
                    Stages  = (ShaderStages)binaryReader.ReadByte(),
                    Options = (ResourceLayoutElementOptions)binaryReader.ReadByte(),
                };
            }
        }

        result = new ShaderCacheFile(
            new ShaderDescription(ShaderStages.Vertex, vsBytes, vsEntryPoint),
            new ShaderDescription(ShaderStages.Fragment, fsBytes, fsEntryPoint),
            resourceLayoutDescriptions);

        return(true);
    }
 public override ResourceLayout CreateResourceLayout(ref ResourceLayoutDescription description)
 => Track(_factory.CreateResourceLayout(description));
Esempio n. 30
0
        public VkResourceLayout(VkGraphicsDevice gd, ref ResourceLayoutDescription description)
            : base(ref description)
        {
            _gd = gd;
            VkDescriptorSetLayoutCreateInfo dslCI = VkDescriptorSetLayoutCreateInfo.New();

            ResourceLayoutElementDescription[] elements = description.Elements;
            _descriptorTypes = new VkDescriptorType[elements.Length];
            VkDescriptorSetLayoutBinding *bindings = stackalloc VkDescriptorSetLayoutBinding[elements.Length];

            uint uniformBufferCount = 0;
            uint sampledImageCount  = 0;
            uint samplerCount       = 0;
            uint storageBufferCount = 0;
            uint storageImageCount  = 0;

            for (uint i = 0; i < elements.Length; i++)
            {
                bindings[i].binding         = i;
                bindings[i].descriptorCount = 1;
                VkDescriptorType descriptorType = VkFormats.VdToVkDescriptorType(elements[i].Kind, elements[i].Options);
                bindings[i].descriptorType = descriptorType;
                bindings[i].stageFlags     = VkFormats.VdToVkShaderStages(elements[i].Stages);
                if ((elements[i].Options & ResourceLayoutElementOptions.DynamicBinding) != 0)
                {
                    DynamicBufferCount += 1;
                }

                _descriptorTypes[i] = descriptorType;

                switch (descriptorType)
                {
                case VkDescriptorType.Sampler:
                    samplerCount += 1;
                    break;

                case VkDescriptorType.SampledImage:
                    sampledImageCount += 1;
                    break;

                case VkDescriptorType.StorageImage:
                    storageImageCount += 1;
                    break;

                case VkDescriptorType.UniformBuffer:
                    uniformBufferCount += 1;
                    break;

                case VkDescriptorType.StorageBuffer:
                    storageBufferCount += 1;
                    break;
                }
            }

            DescriptorResourceCounts = new DescriptorResourceCounts(
                uniformBufferCount,
                sampledImageCount,
                samplerCount,
                storageBufferCount,
                storageImageCount);

            dslCI.bindingCount = (uint)elements.Length;
            dslCI.pBindings    = bindings;

            VkResult result = vkCreateDescriptorSetLayout(_gd.Device, ref dslCI, null, out _dsl);

            CheckResult(result);
        }