public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope) { var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector); BonesBuffer = factory.CreateBuffer(new BufferDescription((uint)(Marshal.SizeOf <Matrix4x4>() * MDLConstants.MaxBones), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); RenderArgumentsBuffer = factory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <StudioRenderArguments>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); TextureDataBuffer = factory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <StudioTextureData>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _sharedLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("Bones", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("RenderArguments", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("TextureData", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("LightingInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment))); TextureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment))); var vertexLayouts = new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("TextureCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3), new VertexElementDescription("VertexBoneIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.UInt1), new VertexElementDescription("NormalBoneIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.UInt1)) }; for (var cullMode = CullBack; cullMode < CullModeCount; ++cullMode) { for (var maskMode = MaskDisabled; maskMode < MaskModeCount; ++maskMode) { for (var additiveMode = AdditiveDisabled; additiveMode < AdditiveModeCount; ++additiveMode) { _pipelines[cullMode, maskMode, additiveMode] = CreatePipelines( gd, sc, vertexLayouts, _sharedLayout, TextureLayout, factory, cullMode == CullBack, maskMode == MaskEnabled, additiveMode == AdditiveEnabled); } } } SharedResourceSet = factory.CreateResourceSet(new ResourceSetDescription( _sharedLayout, sc.ProjectionMatrixBuffer, sc.ViewMatrixBuffer, sc.WorldAndInverseBuffer, BonesBuffer, RenderArgumentsBuffer, TextureDataBuffer, sc.MainSampler, sc.LightingInfoBuffer )); }
public void CreateDeviceObjects(IRendererContext context) { var c = (VeldridRendererContext)context; var cl = c.CommandList; var gd = c.GraphicsDevice; var sc = c.SceneContext; DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); var shaderCache = Resolve <IShaderCache>(); _shaders = shaderCache.GetShaderPair(gd.ResourceFactory, VertexShaderName, FragmentShaderName, shaderCache.GetGlsl(VertexShaderName), shaderCache.GetGlsl(FragmentShaderName)); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend, BlendAttachmentDescription.OverrideBlend), gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, _shaders, ShaderHelper.GetSpecializations(gd)), new[] { resourceLayout }, sc.DuplicatorFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _pipeline.Name = "P_ScreenDuplicator"; float[] verts = CoreUtil.GetFullScreenQuadVerts(gd.IsClipSpaceYInverted); _vb = factory.CreateBuffer(new BufferDescription(verts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer( new BufferDescription((uint)QuadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, QuadIndices); }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope) { if ((scope & ResourceScope.Global) == 0) { return; } DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); var shaderName = gd.IsUvOriginTopLeft ? "FinalPass_inverted" : "FinalPass"; (var vs, var fs) = sc.GlobalResourceCache.GetShaders(gd, gd.ResourceFactory, shaderName); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend), gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { vs, fs, }), new ResourceLayout[] { resourceLayout }, gd.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); float[] verts = Util.GetFullScreenQuadVerts(gd); _vb = factory.CreateBuffer(new BufferDescription(verts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer( new BufferDescription((uint)s_quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope) { if ((scope & ResourceScope.Map) == 0) { return; } var renderer = sc.Models.GetRenderer <SpriteModelRenderer>(); var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector); (var atlasImage, var vertexBuffers) = SPRResourceUtils.CreateSpriteAtlas(SpriteModel.SpriteFile, gd, disposeFactory, sc.TextureLoader); //TODO: disable mipmapping for certain sprites? var texture = sc.MapResourceCache.AddTexture2D(gd, disposeFactory, new ImageSharpTexture(atlasImage, true), $"{SpriteModel.Name}_atlas"); VertexBuffers = vertexBuffers; IndexBuffer = SPRResourceUtils.CreateIndexBuffer(gd, disposeFactory); RenderColorBuffer = disposeFactory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <Vector4>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); var view = sc.MapResourceCache.GetTextureView(gd.ResourceFactory, texture); ResourceSet = disposeFactory.CreateResourceSet(new ResourceSetDescription( renderer.Layout, sc.ProjectionMatrixBuffer, sc.ViewMatrixBuffer, sc.WorldAndInverseBuffer, view, sc.MainSampler, sc.LightingInfoBuffer, RenderColorBuffer)); }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope) { if ((scope & ResourceScope.Map) == 0) { return; } var renderer = sc.Models.GetRenderer <StudioModelRenderer>(); var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector); var vertices = new List <StudioVertex>(); var indices = new List <uint>(); //Construct the meshes for each body part var bodyParts = new List <BodyPartData>(StudioModel.StudioFile.BodyParts.Count); foreach (var bodyPart in StudioModel.StudioFile.BodyParts) { bodyParts.Add(StudioResourceUtils.CreateBodyPart(StudioModel.StudioFile, bodyPart, vertices, indices)); } BodyParts = bodyParts.ToArray(); var verticesArray = vertices.ToArray(); var indicesArray = indices.ToArray(); VertexBuffer = disposeFactory.CreateBuffer(new BufferDescription(verticesArray.SizeInBytes(), BufferUsage.VertexBuffer)); gd.UpdateBuffer(VertexBuffer, 0, verticesArray); IndexBuffer = disposeFactory.CreateBuffer(new BufferDescription(indicesArray.SizeInBytes(), BufferUsage.IndexBuffer)); gd.UpdateBuffer(IndexBuffer, 0, indicesArray); var uploadedTextures = StudioResourceUtils.CreateTextures(StudioModel.Name, StudioModel.StudioFile, gd, sc.TextureLoader, sc.MapResourceCache); Textures = new ResourceSet[uploadedTextures.Count]; for (var i = 0; i < uploadedTextures.Count; ++i) { var view = sc.MapResourceCache.GetTextureView(gd.ResourceFactory, uploadedTextures[i]); Textures[i] = disposeFactory.CreateResourceSet(new ResourceSetDescription(renderer.TextureLayout, view)); } }
public void CreateDeviceObjects(IRendererContext context) { var c = (VeldridRendererContext)context; var cl = c.CommandList; var gd = c.GraphicsDevice; var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; var layout = factory.CreateResourceLayout(new ResourceLayoutDescription( ResourceLayoutHelper.Texture("SourceTexture"), ResourceLayoutHelper.Sampler("SourceSampler"))); var shaderCache = Resolve <IShaderCache>(); _shaders = shaderCache.GetShaderPair(gd.ResourceFactory, VertexShaderName, FragmentShaderName, shaderCache.GetGlsl(VertexShaderName), shaderCache.GetGlsl(FragmentShaderName)); var rasterizerState = new RasterizerStateDescription( FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, false); var pd = new GraphicsPipelineDescription( new BlendStateDescription(RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend), DepthStencilStateDescription.Disabled, rasterizerState, PrimitiveTopology.TriangleList, new ShaderSetDescription(new[] { VertexLayoutHelper.Vertex2DTextured }, _shaders, ShaderHelper.GetSpecializations(gd)), new[] { layout }, gd.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _pipeline.Name = "P_FullScreenQuad"; float[] verts = CoreUtil.GetFullScreenQuadVerts(gd.IsClipSpaceYInverted); _vb = factory.CreateBuffer(new BufferDescription(verts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer(new BufferDescription(QuadIndices.SizeInBytes(), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, QuadIndices); }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); (Shader vs, Shader fs) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "ScreenDuplicator"); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend, BlendAttachmentDescription.OverrideBlend), gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { vs, fs, }, ShaderHelper.GetSpecializations(gd)), new ResourceLayout[] { resourceLayout }, sc.DuplicatorFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); float[] verts = Util.GetFullScreenQuadVerts(gd); _vb = factory.CreateBuffer(new BufferDescription(verts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer( new BufferDescription((uint)s_quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend, BlendAttachmentDescription.OverrideBlend), DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { ShaderHelper.LoadShader(gd, factory, "ScreenDuplicator", ShaderStages.Vertex, "VS"), ShaderHelper.LoadShader(gd, factory, "ScreenDuplicator", ShaderStages.Fragment, "FS"), }), new ResourceLayout[] { resourceLayout }, sc.DuplicatorFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _vb = factory.CreateBuffer(new BufferDescription((uint)s_quadVerts.Length * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, s_quadVerts); _ib = factory.CreateBuffer( new BufferDescription((uint)s_quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, GraphicsSystem sc) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); (Shader vs, Shader fs) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "FullScreenQuad"); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend), DepthStencilStateDescription.Disabled, new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, false), PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { vs, fs }), new ResourceLayout[] { resourceLayout }, gd.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); float[] verts = Util.GetFullScreenQuadVerts(gd.BackendType); _vb = factory.CreateBuffer(new BufferDescription(verts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer( new BufferDescription(s_quadIndices.SizeInBytes(), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; //ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription()); (Shader vs, Shader fs) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "FullScreenQuad"); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend), new DepthStencilStateDescription(true, true, ComparisonKind.Always), new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, false), PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { vs, fs }, ShaderHelper.GetSpecializations(gd)), new ResourceLayout[] { }, gd.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); float[] verts = Utils.GetFullScreenQuadVerts(gd); _vb = factory.CreateBuffer(new BufferDescription((uint)verts.Length * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer( new BufferDescription((uint)s_quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
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"; }
public unsafe void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, GraphicsSystem sc) { ResourceFactory disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector); _vb = _meshData.CreateVertexBuffer(disposeFactory, cl); _vb.Name = _name + "_VB"; _ib = _meshData.CreateIndexBuffer(disposeFactory, cl, out _indexCount); _ib.Name = _name + "_IB"; _worldAndInverseBuffer = disposeFactory.CreateBuffer(new BufferDescription(64 * 2, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); if (_materialPropsOwned) { _materialProps.CreateDeviceObjects(gd, cl, sc); } if (_textureData != null) { _texture = StaticResourceCache.GetTexture2D(gd, gd.ResourceFactory, _textureData); } else { _texture = disposeFactory.CreateTexture(TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled)); RgbaByte color = RgbaByte.Pink; gd.UpdateTexture(_texture, (IntPtr)(&color), 4, 0, 0, 0, 1, 1, 1, 0, 0); } _textureView = StaticResourceCache.GetTextureView(gd.ResourceFactory, _texture); if (_alphaTextureData != null) { _alphamapTexture = _alphaTextureData.CreateDeviceTexture(gd, disposeFactory); } else { _alphamapTexture = StaticResourceCache.GetPinkTexture(gd, gd.ResourceFactory); } _alphaMapView = StaticResourceCache.GetTextureView(gd.ResourceFactory, _alphamapTexture); VertexLayoutDescription[] shadowDepthVertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }; (Shader depthVS, Shader depthFS) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "ShadowDepth"); ResourceLayout projViewCombinedLayout = StaticResourceCache.GetResourceLayout( gd.ResourceFactory, new ResourceLayoutDescription( new ResourceLayoutElementDescription("ViewProjection", ResourceKind.UniformBuffer, ShaderStages.Vertex))); ResourceLayout worldLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription( new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex))); GraphicsPipelineDescription depthPD = new GraphicsPipelineDescription( BlendStateDescription.Empty, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription(shadowDepthVertexLayouts, new[] { depthVS, depthFS }), new ResourceLayout[] { projViewCombinedLayout, worldLayout }, sc.NearShadowMapFramebuffer.OutputDescription); _shadowMapPipeline = StaticResourceCache.GetPipeline(gd.ResourceFactory, ref depthPD); _shadowMapResourceSets = CreateShadowMapResourceSets(gd.ResourceFactory, disposeFactory, cl, sc, projViewCombinedLayout, worldLayout); VertexLayoutDescription[] mainVertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }; (Shader mainVS, Shader mainFS) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "ShadowMain"); ResourceLayout projViewLayout = StaticResourceCache.GetResourceLayout( gd.ResourceFactory, StaticResourceCache.ProjViewLayoutDescription); ResourceLayout mainSharedLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription( new ResourceLayoutElementDescription("LightViewProjection1", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("LightViewProjection2", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("LightViewProjection3", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("DepthLimits", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("LightInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("CameraInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("PointLights", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment))); ResourceLayout mainPerObjectLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription( new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("MaterialProperties", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("RegularSampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("AlphaMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("AlphaMapSampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShadowMapNear", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShadowMapMid", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShadowMapFar", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShadowMapSampler", ResourceKind.Sampler, ShaderStages.Fragment))); ResourceLayout reflectionLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription( new ResourceLayoutElementDescription("ReflectionMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("ReflectionSampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("ReflectionViewProj", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("ClipPlaneInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment))); GraphicsPipelineDescription mainPD = new GraphicsPipelineDescription( _alphamapTexture != null ? BlendStateDescription.SingleAlphaBlend : BlendStateDescription.SingleOverrideBlend, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription(mainVertexLayouts, new[] { mainVS, mainFS }), new ResourceLayout[] { projViewLayout, mainSharedLayout, mainPerObjectLayout, reflectionLayout }, sc.MainSceneFramebuffer.OutputDescription); _pipeline = StaticResourceCache.GetPipeline(gd.ResourceFactory, ref mainPD); _pipeline.Name = "MeshRenderer Main Pipeline"; mainPD.RasterizerState.CullMode = FaceCullMode.Front; mainPD.Outputs = sc.ReflectionFramebuffer.OutputDescription; _pipelineFrontCull = StaticResourceCache.GetPipeline(gd.ResourceFactory, ref mainPD); _mainProjViewRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(projViewLayout, sc.ProjectionMatrixBuffer, sc.ViewMatrixBuffer)); _mainSharedRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(mainSharedLayout, sc.LightViewProjectionBuffer0, sc.LightViewProjectionBuffer1, sc.LightViewProjectionBuffer2, sc.DepthLimitsBuffer, sc.LightInfoBuffer, sc.CameraInfoBuffer, sc.PointLightsBuffer)); _mainPerObjectRS = disposeFactory.CreateResourceSet(new ResourceSetDescription(mainPerObjectLayout, _worldAndInverseBuffer, _materialProps.UniformBuffer, _textureView, gd.Aniso4xSampler, _alphaMapView, gd.LinearSampler, sc.NearShadowMapView, sc.MidShadowMapView, sc.FarShadowMapView, gd.PointSampler)); _reflectionRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(reflectionLayout, _alphaMapView, // Doesn't really matter -- just don't bind the actual reflection map since it's being rendered to. gd.PointSampler, sc.ReflectionViewProjBuffer, sc.MirrorClipPlaneBuffer)); _noReflectionRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(reflectionLayout, sc.ReflectionColorView, gd.PointSampler, sc.ReflectionViewProjBuffer, sc.NoClipPlaneBuffer)); }
public void CreateDeviceResources(GraphicsDevice gd) { var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory, disposeCollector); vertexBuffer = model.CreateVertexBuffer(gd); indexBuffer = model.CreateIndexBuffer(gd, out indexCount); transformationBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); projectionBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); viewBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); texture = textureData.CreateDeviceTexture(gd, factory); lightDirectionBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); lightColorBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); shineDamperBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); reflectivityBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); var vertexLayoutDesc = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementFormat.Float3, VertexElementSemantic.TextureCoordinate), new VertexElementDescription("TexCoord", VertexElementFormat.Float2, VertexElementSemantic.TextureCoordinate), new VertexElementDescription("Normal", VertexElementFormat.Float3, VertexElementSemantic.TextureCoordinate) ) }; var transformationResourceLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription[] { new ResourceLayoutElementDescription("TransformationBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("ViewBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex) } )); var textureResourceLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription[] { new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("LightDirectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("LightColorBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShineDamperBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("ReflectivityBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment) } )); transformationResourceSet = factory.CreateResourceSet( new ResourceSetDescription( transformationResourceLayout, transformationBuffer, projectionBuffer, viewBuffer)); textureResourceSet = factory.CreateResourceSet( new ResourceSetDescription( textureResourceLayout, texture, gd.Aniso4xSampler, lightDirectionBuffer, lightColorBuffer, shineDamperBuffer, reflectivityBuffer)); var pipelineDesc = 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.CounterClockwise, depthClipEnabled: true, scissorTestEnabled: false), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { transformationResourceLayout, textureResourceLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: vertexLayoutDesc, shaders: new[] { vertexShader, fragmentShader }), Outputs = gd.SwapchainFramebuffer.OutputDescription }; pipeline = factory.CreateGraphicsPipeline(pipelineDesc); }
public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope) { if ((scope & ResourceScope.Map) == 0) { return; } var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector); _sharedLayout = disposeFactory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("LightingInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("LightStyles", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("RenderColor", ResourceKind.UniformBuffer, ShaderStages.Fragment))); TextureLayout = disposeFactory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment))); LightmapLayout = disposeFactory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Lightmaps", ResourceKind.TextureReadOnly, ShaderStages.Fragment))); var vertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("TextureCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("LightmapCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), //Used for multiple light styles; this is the offset to apply to lightmap X coordinates new VertexElementDescription("LightmapXOffset", VertexElementSemantic.Position, VertexElementFormat.Float1), new VertexElementDescription("StyleIndices", VertexElementSemantic.Position, VertexElementFormat.Int4)) }; (var vs, var fs) = sc.MapResourceCache.GetShaders(gd, gd.ResourceFactory, "LightMappedGeneric"); //Create render mode pipelines var rasterizerState = new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, true); const PrimitiveTopology primitiveTopology = PrimitiveTopology.TriangleList; var shaderSets = new ShaderSetDescription(vertexLayouts, new[] { vs, fs }); var resourceLayouts = new ResourceLayout[] { _sharedLayout, TextureLayout, LightmapLayout }; var outputDescription = sc.MainSceneFramebuffer.OutputDescription; var pipelines = new Pipeline[(int)RenderMode.Last + 1]; var pd = new GraphicsPipelineDescription( BlendStateDescription.SingleDisabled, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, rasterizerState, primitiveTopology, shaderSets, resourceLayouts, outputDescription); pipelines[(int)RenderMode.Normal] = disposeFactory.CreateGraphicsPipeline(ref pd); pipelines[(int)RenderMode.TransColor] = disposeFactory.CreateGraphicsPipeline(ref pd); pd = new GraphicsPipelineDescription( BlendStateDescription.SingleAlphaBlend, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqualRead : DepthStencilStateDescription.DepthOnlyLessEqualRead, rasterizerState, primitiveTopology, shaderSets, resourceLayouts, outputDescription); pipelines[(int)RenderMode.TransTexture] = disposeFactory.CreateGraphicsPipeline(ref pd); //Glow uses the same pipeline as texture pipelines[(int)RenderMode.Glow] = pipelines[(int)RenderMode.TransTexture]; pd = new GraphicsPipelineDescription( BlendStateDescription.SingleDisabled, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, rasterizerState, primitiveTopology, shaderSets, resourceLayouts, outputDescription); pipelines[(int)RenderMode.TransAlpha] = disposeFactory.CreateGraphicsPipeline(ref pd); pd = new GraphicsPipelineDescription( BlendStates.SingleAdditiveOneOneBlend, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqualRead : DepthStencilStateDescription.DepthOnlyLessEqualRead, rasterizerState, primitiveTopology, shaderSets, resourceLayouts, outputDescription); pipelines[(int)RenderMode.TransAdd] = disposeFactory.CreateGraphicsPipeline(ref pd); Pipelines = new RenderModePipelines(pipelines); RenderArgumentsBuffer = disposeFactory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <BSPRenderArguments>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _sharedResourceSet = disposeFactory.CreateResourceSet(new ResourceSetDescription( _sharedLayout, sc.ProjectionMatrixBuffer, sc.ViewMatrixBuffer, sc.WorldAndInverseBuffer, sc.LightingInfoBuffer, sc.LightStylesBuffer, RenderArgumentsBuffer)); }
/// <summary> /// Sets delegates for runtime command generation. /// Also updates index and vertex buffers, sets pipeline /// </summary> /// <param name="modelDescriptor">Model descriptor.</param> /// <param name="sceneRuntimeDescriptor">Scene runtime descriptor.</param> /// <param name="instancingData">Instance data enumerable.</param> /// <typeparam name="T">The type of Vertex sent to the GPU</typeparam> protected void FillRuntimeDescriptor <T>(ModelRuntimeDescriptor <T> modelDescriptor, SceneRuntimeDescriptor sceneRuntimeDescriptor, IEnumerable <InstanceData> instancingData) where T : struct, VertexRuntime, VertexLocateable { var model = modelDescriptor.Model; modelDescriptor.TextureResourceLayout = modelDescriptor.InvokeTextureResourceLayoutGeneration(_factory); modelDescriptor.TextureSampler = modelDescriptor.InvokeSamplerGeneration(_factory); modelDescriptor.LoadShaders(_graphicsDevice); byte vertexSizeInBytes = model.GetMesh(0).Vertices[0].GetSizeInBytes(); var meshCount = model.MeshCount; for (int i = 0; i < meshCount; i++) { var mesh = model.GetMesh(i); var meshBVH = model.GetMeshBVH(i); DeviceBuffer vertexBuffer = _factory.CreateBuffer(new BufferDescription(mesh.Vertices.LengthUnsigned() * vertexSizeInBytes, BufferUsage.VertexBuffer)); DeviceBuffer indexBuffer = _factory.CreateBuffer(new BufferDescription(mesh.Indices.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer)); modelDescriptor.VertexBufferList.Add(vertexBuffer); modelDescriptor.IndexBufferList.Add(indexBuffer); var allInstancePreEffects = RenderFlags.GetAllPreEffectFor(modelDescriptor.PreEffectsInstancingFlag); foreach (var instanceData in instancingData) { var instanceDataBuffer = ResourceGenerator.AllocateInstanceDataBuffer(instanceData, _graphicsDevice, _factory); if (instanceDataBuffer != null) { modelDescriptor.InstanceBufferLists[RenderFlags.NORMAL_ARRAY_INDEX].Add(instanceDataBuffer); foreach (var preEffect in allInstancePreEffects) { modelDescriptor.InstanceBufferLists[RenderFlags.GetArrayIndexForFlag(preEffect)].Add(instanceDataBuffer); } } } _graphicsDevice.UpdateBuffer <T>(vertexBuffer, 0, ref mesh.Vertices[0], (vertexSizeInBytes * mesh.VertexCount).ToUnsigned()); _graphicsDevice.UpdateBuffer <ushort>(indexBuffer, 0, ref mesh.Indices[0], (sizeof(ushort) * mesh.IndexCount).ToUnsigned()); var resourceSet = modelDescriptor.InvokeTextureResourceSetGeneration(i, _factory, _graphicsDevice); if (resourceSet != null) { modelDescriptor.TextureResourceSetsList.Add(resourceSet); } } var rasterizerStateCullBack = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ); var rasterizerStateCullFront = new RasterizerStateDescription( cullMode: FaceCullMode.Front, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ); var rasterizerStateCullNone = new RasterizerStateDescription( cullMode: FaceCullMode.None, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ); modelDescriptor.InvokeVertexLayoutGeneration(); var shadowMapIndex = RenderFlags.GetArrayIndexForFlag(RenderFlags.SHADOW_MAP); var omniShadowMapIndex = RenderFlags.GetArrayIndexForFlag(RenderFlags.OMNI_SHADOW_MAPS); modelDescriptor.Pipelines[shadowMapIndex] = modelDescriptor.ShadowMapEnabled ? _factory.CreateGraphicsPipeline(PipelineGenerator.GenerateShadowMappingPreEffectPipeline(modelDescriptor, _childrenPre[RenderFlags.GetPreEffectArrayIndexForFlag(RenderFlags.SHADOW_MAP)].SceneRuntimeDescriptor, rasterizerStateCullFront, RenderFlags.SHADOW_MAP, _childrenPre[RenderFlags.GetPreEffectArrayIndexForFlag(RenderFlags.SHADOW_MAP)].FrameBuffer)) : null; modelDescriptor.Pipelines[omniShadowMapIndex] = modelDescriptor.OmniShadowMapEnabled ? _factory.CreateGraphicsPipeline(PipelineGenerator.GenerateOmniShadowMappingPreEffectPipeline(modelDescriptor, _childrenPre[0].SceneRuntimeDescriptor, rasterizerStateCullNone, RenderFlags.OMNI_SHADOW_MAPS, _childrenPre[0].FrameBuffer)) : null; var effectLayoutArray = modelDescriptor.FillEffectsResourceSet(_factory, sceneRuntimeDescriptor, _childrenPre); var normalIndex = RenderFlags.GetArrayIndexForFlag(RenderFlags.NORMAL); switch (modelDescriptor.VertexRuntimeType) { // Only cube maps for now case VertexRuntimeTypes.VertexPosition: //TODO: Use proper constants from RenderFlags.cs modelDescriptor.Pipelines[normalIndex] = _factory.CreateGraphicsPipeline(PipelineGenerator.GeneratePipelineP(modelDescriptor, sceneRuntimeDescriptor, rasterizerStateCullFront, _graphicsDevice.SwapchainFramebuffer, effectLayoutArray)); break; case VertexRuntimeTypes.VertexPositionNormal: modelDescriptor.Pipelines[normalIndex] = _factory.CreateGraphicsPipeline(PipelineGenerator.GeneratePipelinePN(modelDescriptor, sceneRuntimeDescriptor, rasterizerStateCullBack, _graphicsDevice.SwapchainFramebuffer, effectLayoutArray)); break; case VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent: modelDescriptor.Pipelines[normalIndex] = _factory.CreateGraphicsPipeline(PipelineGenerator.GeneratePipelinePNTTB(modelDescriptor, sceneRuntimeDescriptor, rasterizerStateCullBack, _graphicsDevice.SwapchainFramebuffer, effectLayoutArray)); break; case VertexRuntimeTypes.VertexPositionColor: modelDescriptor.Pipelines[normalIndex] = _factory.CreateGraphicsPipeline(PipelineGenerator.GeneratePipelinePC(modelDescriptor, sceneRuntimeDescriptor, rasterizerStateCullBack, _graphicsDevice.SwapchainFramebuffer, effectLayoutArray)); break; case VertexRuntimeTypes.VertexPositionTexture: modelDescriptor.Pipelines[normalIndex] = _factory.CreateGraphicsPipeline(PipelineGenerator.GeneratePipelinePT(modelDescriptor, sceneRuntimeDescriptor, rasterizerStateCullBack, _graphicsDevice.SwapchainFramebuffer, effectLayoutArray)); break; default: throw new NotImplementedException($"{modelDescriptor.VertexRuntimeType.ToString("g")} not implemented"); } }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope) { if ((scope & ResourceScope.Map) == 0) { return; } var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector); //Build a list of buffers, each buffer containing all of the faces that have the same texture //This reduces the number of buffers we have to create from a set for each face to a set for each texture and all of the faces referencing it //TODO: further split by visleaf when vis data is available var sortedFaces = BSPModel.SubModel.Faces.GroupBy(face => face.TextureInfo.MipTexture.Name); sortedFaces = sortedFaces.OrderByDescending(grouping => grouping.Count()); var lightmapBuilders = new List <LightmapBuilder> { new LightmapBuilder(LightmapPoolSize, LightmapPoolSize) }; var vertices = new List <BSPSurfaceData>(); var indices = new List <uint>(); //A white texture is used so when rendering surfaces with no lightmaps, the surface is fullbright //Since surfaces like these are typically triggers it makes things a lot easier using (var defaultLightmapTexture = Image.LoadPixelData(new[] { Rgba32.White }, 1, 1)) { foreach (var faces in sortedFaces) { if (faces.Key != "sky") { var facesList = faces.ToList(); var mipTexture = facesList[0].TextureInfo.MipTexture; var texture = sc.MapResourceCache.GetTexture2D(mipTexture.Name); //If not found, fallback to have a valid texture texture = texture ?? sc.MapResourceCache.GetPinkTexture(gd, gd.ResourceFactory); var view = sc.MapResourceCache.GetTextureView(gd.ResourceFactory, texture); var textureResourceSet = gd.ResourceFactory.CreateResourceSet(new ResourceSetDescription(sc.ModelRenderer.BrushRenderer.TextureLayout, view, sc.MainSampler)); BSPResourceUtils.BuildFacesBuffer( BSPModel.BSPFile, facesList, mipTexture, textureResourceSet, defaultLightmapTexture, lightmapBuilders, vertices, indices); } } } Lightmaps = lightmapBuilders .Select(builder => builder.Build(sc.ModelRenderer.BrushRenderer.LightmapLayout, sc.MapResourceCache, gd, gd.ResourceFactory)) .ToArray(); Array.ForEach(Lightmaps, lightmap => _disposeCollector.Add(lightmap)); var verticesArray = vertices.ToArray(); var indicesArray = indices.ToArray(); VertexBuffer = disposeFactory.CreateBuffer(new BufferDescription(verticesArray.SizeInBytes(), BufferUsage.VertexBuffer)); cl.UpdateBuffer(VertexBuffer, 0, verticesArray); IndexBuffer = disposeFactory.CreateBuffer(new BufferDescription(indicesArray.SizeInBytes(), BufferUsage.IndexBuffer)); cl.UpdateBuffer(IndexBuffer, 0, indicesArray); }
public static void CreateIfNullBuffer(this DisposeCollectorResourceFactory f, ref DeviceBuffer b, BufferDescription desc) { b = b ?? f.CreateBuffer(desc); }
private void CreateResources() { _factory = new DisposeCollectorResourceFactory(_gd.ResourceFactory); _cl = _factory.CreateCommandList(); _cl.Begin(); _projectionBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); _viewBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); _modelBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); _projectionBufferForShadowShader = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); _viewBufferShadow = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); _modelBufferShadow = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); // TODO: no idea why this buffer requires 48 bytes instead of 32 bytes, padding? //_directionLightBuffer = _factory.CreateBuffer(new BufferDescription(48, BufferUsage.UniformBuffer)); // addition of shadowmatrix, now requires (48+64=) 112 bytes _directionLightBuffer = _factory.CreateBuffer(new BufferDescription(112, BufferUsage.UniformBuffer)); _cl.End(); _gd.SubmitCommands(_cl); _gd.WaitForIdle(); ShaderSetDescription shaderSet = new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3)) }, new[] { LoadShader(_factory, "ColorShader", ShaderStages.Vertex, "VS"), LoadShader(_factory, "ColorShader", ShaderStages.Fragment, "FS") }); ShaderSetDescription shaderSetShadow = new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3)) }, new[] { LoadShader(_factory, "ShadowShader", ShaderStages.Vertex, "VS"), LoadShader(_factory, "ShadowShader", ShaderStages.Fragment, "FS") }); ResourceLayout projectionViewMatricesLightLayout = _factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("DirectionalLight", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment), new ResourceLayoutElementDescription("ShadowMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShadowMapSampler", ResourceKind.Sampler, ShaderStages.Fragment) )); ResourceLayout perObjectLayout = _factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Model", ResourceKind.UniformBuffer, ShaderStages.Vertex) )); ResourceLayout projectionViewMatricesLayoutShadow = _factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex) )); ResourceLayout modelLayoutShadow = _factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Model", ResourceKind.UniformBuffer, ShaderStages.Vertex) )); _pipeline = _factory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, shaderSet, new[] { projectionViewMatricesLightLayout, perObjectLayout }, _gd.SwapchainFramebuffer.OutputDescription)); TextureDescription desc = TextureDescription.Texture2D(2048, 2048, 1, 1, PixelFormat.D32_Float_S8_UInt, TextureUsage.DepthStencil | TextureUsage.Sampled); _shadowMap = _factory.CreateTexture(desc); _shadowMap.Name = "Shadow Map"; _shadowMapView = _factory.CreateTextureView(_shadowMap); _shadowMapFramebuffer = _factory.CreateFramebuffer(new FramebufferDescription( new FramebufferAttachmentDescription(_shadowMap, 0), Array.Empty <FramebufferAttachmentDescription>())); _pipelineShadow = _factory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.Empty, DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, shaderSetShadow, new[] { projectionViewMatricesLayoutShadow, modelLayoutShadow }, _shadowMapFramebuffer.OutputDescription)); _projectionViewMatricesLightSet = _factory.CreateResourceSet(new ResourceSetDescription( projectionViewMatricesLightLayout, _projectionBuffer, _viewBuffer, _directionLightBuffer, _shadowMapView, _gd.PointSampler)); _perObjectSet = _factory.CreateResourceSet(new ResourceSetDescription( perObjectLayout, _modelBuffer)); _projectionViewMatricesSetShadow = _factory.CreateResourceSet(new ResourceSetDescription( projectionViewMatricesLayoutShadow, _projectionBufferForShadowShader, _viewBufferShadow)); _modelMatrixSetShadow = _factory.CreateResourceSet(new ResourceSetDescription( modelLayoutShadow, _modelBufferShadow)); }
public DeviceBuffer CreateBuffer(BufferDescription bufferDescription) => _factory.CreateBuffer(bufferDescription);
static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine($"ImageTint <image-path> <out>: Tints the image at <image-path> and saves it to <out>."); return(1); } string inPath = args[0]; string outPath = args[1]; // This demo uses WindowState.Hidden to avoid popping up an unnecessary window to the user. VeldridStartup.CreateWindowAndGraphicsDevice( new WindowCreateInfo { WindowInitialState = WindowState.Hidden, }, new GraphicsDeviceOptions() { ResourceBindingModel = ResourceBindingModel.Improved }, out Sdl2Window window, out GraphicsDevice gd); DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); ImageSharpTexture inputImage = new ImageSharpTexture(inPath, false); Texture inputTexture = inputImage.CreateDeviceTexture(gd, factory); TextureView view = factory.CreateTextureView(inputTexture); Texture output = factory.CreateTexture(TextureDescription.Texture2D( inputImage.Width, inputImage.Height, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.RenderTarget)); Framebuffer framebuffer = factory.CreateFramebuffer(new FramebufferDescription(null, output)); DeviceBuffer vertexBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.VertexBuffer)); Vector4[] quadVerts = { new Vector4(-1, 1, 0, 0), new Vector4(1, 1, 1, 0), new Vector4(-1, -1, 0, 1), new Vector4(1, -1, 1, 1), }; gd.UpdateBuffer(vertexBuffer, 0, quadVerts); ShaderSetDescription shaderSet = new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TextureCoordinates", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, factory.CreateFromSpirv( new ShaderDescription(ShaderStages.Vertex, ReadEmbeddedAssetBytes("TintShader-vertex.glsl"), "main"), new ShaderDescription(ShaderStages.Fragment, ReadEmbeddedAssetBytes("TintShader-fragment.glsl"), "main"))); ResourceLayout layout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Input", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("Tint", ResourceKind.UniformBuffer, ShaderStages.Fragment))); Pipeline pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.Disabled, RasterizerStateDescription.Default, PrimitiveTopology.TriangleStrip, shaderSet, layout, framebuffer.OutputDescription)); DeviceBuffer tintInfoBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); gd.UpdateBuffer( tintInfoBuffer, 0, new TintInfo( new Vector3(1f, 0.2f, 0.1f), // Change this to modify the tint color. 0.25f)); ResourceSet resourceSet = factory.CreateResourceSet( new ResourceSetDescription(layout, view, gd.PointSampler, tintInfoBuffer)); // RenderTarget textures are not CPU-visible, so to get our tinted image back, we need to first copy it into // a "staging Texture", which is a Texture that is CPU-visible (it can be Mapped). Texture stage = factory.CreateTexture(TextureDescription.Texture2D( inputImage.Width, inputImage.Height, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Staging)); CommandList cl = factory.CreateCommandList(); cl.Begin(); cl.SetFramebuffer(framebuffer); cl.SetFullViewports(); cl.SetVertexBuffer(0, vertexBuffer); cl.SetPipeline(pipeline); cl.SetGraphicsResourceSet(0, resourceSet); cl.Draw(4, 1, 0, 0); cl.CopyTexture( output, 0, 0, 0, 0, 0, stage, 0, 0, 0, 0, 0, stage.Width, stage.Height, 1, 1); cl.End(); gd.SubmitCommands(cl); gd.WaitForIdle(); // When a texture is mapped into a CPU-visible region, it is often not laid out linearly. // Instead, it is laid out as a series of rows, which are all spaced out evenly by a "row pitch". // This spacing is provided in MappedResource.RowPitch. // It is also possible to obtain a "structured view" of a mapped data region, which is what is done below. // With a structured view, you can read individual elements from the region. // The code below simply iterates over the two-dimensional region and places each texel into a linear buffer. // ImageSharp requires the pixel data be contained in a linear buffer. MappedResourceView <Rgba32> map = gd.Map <Rgba32>(stage, MapMode.Read); // Rgba32 is synonymous with PixelFormat.R8_G8_B8_A8_UNorm. Rgba32[] pixelData = new Rgba32[stage.Width * stage.Height]; for (int y = 0; y < stage.Height; y++) { for (int x = 0; x < stage.Width; x++) { int index = (int)(y * stage.Width + x); pixelData[index] = map[x, y]; } } gd.Unmap(stage); // Resources should be Unmapped when the region is no longer used. Image <Rgba32> outputImage = Image.LoadPixelData(pixelData, (int)stage.Width, (int)stage.Height); outputImage.Save(outPath); factory.DisposeCollector.DisposeAll(); gd.Dispose(); window.Close(); return(0); }