private ID3D11RasterizerState CreateNewRasterizerState(ref D3D11RasterizerStateCacheKey key) { RasterizerDescription rssDesc = new RasterizerDescription { CullMode = D3D11Formats.VdToD3D11CullMode(key.VeldridDescription.CullMode), FillMode = D3D11Formats.VdToD3D11FillMode(key.VeldridDescription.FillMode), DepthClipEnable = key.VeldridDescription.DepthClipEnabled, ScissorEnable = key.VeldridDescription.ScissorTestEnabled, FrontCounterClockwise = key.VeldridDescription.FrontFace == FrontFace.CounterClockwise, MultisampleEnable = key.Multisampled }; return(_device.CreateRasterizerState(rssDesc)); }
private void MakeBothSidesRendered() { RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntiAliasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = Microsoft.WindowsAPICodePack.DirectX.Direct3D10.FillMode.Solid; rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState(rsDesc); device.RS.State = rasterizerState; }
/// <summary> /// Renders the mesh with the specified transformation. This alternate render method /// supplements the base class rendering to provide part-by-part texturing support. /// </summary> /// <param name="modelTransform"></param> public void Render(Matrix3D modelTransform) { // setup rasterization RasterizerDescription rasterizerDescription = new RasterizerDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, FrontCounterclockwise = false, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, DepthClipEnable = true, ScissorEnable = false, MultisampleEnable = true, AntiAliasedLineEnable = true }; try { solidRasterizerState = this.manager.device.CreateRasterizerState(rasterizerDescription); rasterizerDescription.FillMode = FillMode.Wireframe; wireframeRasterizerState = this.manager.device.CreateRasterizerState(rasterizerDescription); base.Render(modelTransform.ToMatrix4x4F()); } finally { if (solidRasterizerState != null) { solidRasterizerState.Dispose(); solidRasterizerState = null; } if (wireframeRasterizerState != null) { wireframeRasterizerState.Dispose(); wireframeRasterizerState = null; } currentRasterizerState = null; } }
private static GraphicsPipelineStateDescription CreateGraphicsPipelineStateDescription(GraphicsDevice device, RootSignature rootSignature, InputElementDescription[] inputElements, byte[] vertexShader, byte[] pixelShader, byte[]?geometryShader, byte[]?hullShader, byte[]?domainShader) { RasterizerDescription rasterizerDescription = RasterizerDescription.CullNone; rasterizerDescription.FrontCounterClockwise = true; BlendDescription blendDescription = BlendDescription.AlphaBlend; InputLayoutDescription inputLayoutDescription = new InputLayoutDescription(inputElements.Select(i => Unsafe.As <InputElementDescription, Vortice.Direct3D12.InputElementDescription>(ref i)).ToArray()); GraphicsPipelineStateDescription pipelineStateDescription = new GraphicsPipelineStateDescription { InputLayout = inputLayoutDescription, RootSignature = rootSignature.NativeRootSignature, VertexShader = vertexShader, PixelShader = pixelShader, GeometryShader = geometryShader, HullShader = hullShader, DomainShader = domainShader, RasterizerState = rasterizerDescription, BlendState = blendDescription, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, StreamOutput = new StreamOutputDescription() }; DepthStencilView?depthStencilBuffer = device.CommandList.DepthStencilBuffer; if (depthStencilBuffer != null) { pipelineStateDescription.DepthStencilFormat = (Format)depthStencilBuffer.Resource.Description.Format; } Format[] renderTargetFormats = new Format[device.CommandList.RenderTargets.Length]; for (int i = 0; i < renderTargetFormats.Length; i++) { renderTargetFormats[i] = (Format)device.CommandList.RenderTargets[i].Resource.Description.Format; } pipelineStateDescription.RenderTargetFormats = renderTargetFormats; return(pipelineStateDescription); }
private static GraphicsPipelineStateDescription CreateGraphicsPipelineStateDescription(GraphicsDevice device, InputElementDescription[] inputElements, ID3D12RootSignature rootSignature, ShaderBytecode vertexShader, ShaderBytecode pixelShader, ShaderBytecode geometryShader, ShaderBytecode hullShader, ShaderBytecode domainShader) { RasterizerDescription rasterizerDescription = RasterizerDescription.CullNone; rasterizerDescription.FrontCounterClockwise = true; BlendDescription blendDescription = BlendDescription.AlphaBlend; GraphicsPipelineStateDescription pipelineStateDescription = new GraphicsPipelineStateDescription { InputLayout = new InputLayoutDescription(inputElements), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, GeometryShader = geometryShader, HullShader = hullShader, DomainShader = domainShader, RasterizerState = rasterizerDescription, BlendState = blendDescription, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, StreamOutput = new StreamOutputDescription() }; Texture?depthStencilBuffer = device.CommandList.DepthStencilBuffer; if (depthStencilBuffer != null) { pipelineStateDescription.DepthStencilFormat = (Format)depthStencilBuffer.Description.Format; } Format[] renderTargetFormats = new Format[device.CommandList.RenderTargets.Length]; for (int i = 0; i < renderTargetFormats.Length; i++) { renderTargetFormats[i] = (Format)((Texture)device.CommandList.RenderTargets[i]).Description.Format; } pipelineStateDescription.RenderTargetFormats = renderTargetFormats; return(pipelineStateDescription); }
void CreateDeviceResources() { uint width = (uint) host.ActualWidth; uint height = (uint) host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); DXGIFactory dxgiFactory = DXGIFactory.CreateFactory(); SwapChainDescription swapDesc = new SwapChainDescription(); swapDesc.BufferDescription.Width = width; swapDesc.BufferDescription.Height = height; swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM; swapDesc.BufferDescription.RefreshRate.Numerator = 60; swapDesc.BufferDescription.RefreshRate.Denominator = 1; swapDesc.SampleDescription.Count = 1; swapDesc.SampleDescription.Quality = 0; swapDesc.BufferUsage = UsageOption.RenderTargetOutput; swapDesc.BufferCount = 1; swapDesc.OutputWindowHandle = host.Handle; swapDesc.Windowed = true; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntialiasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.SetState( rasterizerState ); // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.SetRenderTargets(new RenderTargetView[] {null}); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8_UNORM; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; renderDesc.Texture2D.MipSlice = 0; using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsage.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription; tex2DDescription.ArraySize = 1; tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource; tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified; tex2DDescription.Format = Format.R8G8B8A8_UNORM; tex2DDescription.Height = 4096; tex2DDescription.Width = 512; tex2DDescription.MipLevels = 1; tex2DDescription.MiscFlags = 0; tex2DDescription.SampleDescription.Count = 1; tex2DDescription.SampleDescription.Quality = 0; tex2DDescription.Usage = Usage.Default; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GetDXGISurface()) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix(); viewMatrixVariable = shader.GetVariableByName("View").AsMatrix(); projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix(); diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource(); // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.SetInputLayout( vertexLayout ); IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindFlags = BindFlag.VertexBuffer; bd.CpuAccessFlags = CpuAccessFlag.Unspecified; bd.MiscFlags = ResourceMiscFlag.Undefined; SubresourceData InitData = new SubresourceData() { SysMem = verticesDataPtr }; vertexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] {vertexBuffer}, new uint[] {stride}, new uint[] {offset} ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindFlags = BindFlag.IndexBuffer; bd.CpuAccessFlags = 0; bd.MiscFlags = 0; InitData.SysMem = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float) Math.PI*0.1f, width/(float) height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(Colors.Yellow)), new GradientStop(1.0f, new ColorF(Colors.Black)) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.Gamma_22, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
public ID3D12PipelineState GetState(GraphicsDevice device, PSODesc desc, RootSignature rootSignature) { foreach (var psoCombind in PSOCombinds) { if (psoCombind.PSODesc == desc && psoCombind.rootSignature == rootSignature) { if (psoCombind.pipelineState == null) { throw new Exception("pipeline state error"); } return(psoCombind.pipelineState); } } InputLayoutDescription inputLayoutDescription; if (device.inputLayouts.TryGetValue(desc.InputLayout, out inputLayoutDescription)) { } else { inputLayoutDescription = new InputLayoutDescription(new InputElementDescription("POSITION", 0, Format.R32G32B32_Float, 0)); } GraphicsPipelineStateDescription graphicsPipelineStateDescription = new GraphicsPipelineStateDescription(); graphicsPipelineStateDescription.RootSignature = rootSignature.rootSignature; graphicsPipelineStateDescription.VertexShader = vertexShader; graphicsPipelineStateDescription.GeometryShader = geometryShader; graphicsPipelineStateDescription.PixelShader = pixelShader; graphicsPipelineStateDescription.PrimitiveTopologyType = PrimitiveTopologyType.Triangle; graphicsPipelineStateDescription.InputLayout = inputLayoutDescription; graphicsPipelineStateDescription.DepthStencilFormat = desc.DepthStencilFormat; graphicsPipelineStateDescription.RenderTargetFormats = new Format[desc.RenderTargetCount]; Array.Fill(graphicsPipelineStateDescription.RenderTargetFormats, desc.RenderTargetFormat); if (desc.BlendState == "Alpha") { graphicsPipelineStateDescription.BlendState = blendStateAlpha(); } else if (desc.BlendState == "Add") { graphicsPipelineStateDescription.BlendState = BlendDescription.Additive; } else { graphicsPipelineStateDescription.BlendState = BlendDescription.Opaque; } graphicsPipelineStateDescription.DepthStencilState = new DepthStencilDescription(desc.DepthStencilFormat != Format.Unknown, desc.DepthStencilFormat != Format.Unknown); graphicsPipelineStateDescription.SampleMask = uint.MaxValue; var RasterizerState = new RasterizerDescription(CullMode.None, FillMode.Solid); RasterizerState.DepthBias = desc.DepthBias; RasterizerState.SlopeScaledDepthBias = desc.SlopeScaledDepthBias; graphicsPipelineStateDescription.RasterizerState = RasterizerState; var pipelineState = device.device.CreateGraphicsPipelineState <ID3D12PipelineState>(graphicsPipelineStateDescription); if (pipelineState == null) { throw new Exception("pipeline state error"); } PSOCombinds.Add(new PSOCombind { PSODesc = desc, pipelineState = pipelineState, rootSignature = rootSignature }); return(pipelineState); }
GraphicsPipelineState makeTriangle(ResourceCreateContext ctx) { var triangleVertex = UniqueCreator.Graphics.Gpu.Shaders.triangle_vertex.Factory.Create(); var trianglePixel = UniqueCreator.Graphics.Gpu.Shaders.triangle_pixel.Factory.Create(); var description2 = new GraphicsPipelineStateDescription(); var rasterizerState = new RasterizerDescription(); var samples = new SampleDescription { Count = 1, Quality = 0 }; var depthStencil = new DepthStencilDescription { DepthEnable = true, StencilEnable = false, DepthWriteMask = DepthWriteMask.All, DepthFunc = ComparisonFunction.Less }; depthStencil.BackFace.StencilFailOperation = StencilOperation.Keep; depthStencil.BackFace.StencilPassOperation = StencilOperation.Keep; depthStencil.BackFace.StencilFunction = ComparisonFunction.Always; depthStencil.BackFace.StencilDepthFailOperation = StencilOperation.Keep; depthStencil.FrontFace = depthStencil.BackFace; depthStencil.StencilReadMask = 0xff; depthStencil.StencilWriteMask = 0xff; rasterizerState.CullMode = CullMode.Back; rasterizerState.FillMode = FillMode.Solid; rasterizerState.FrontCounterClockwise = true; rasterizerState.AntialiasedLineEnable = false; rasterizerState.ConservativeRaster = ConservativeRasterizationMode.Off; rasterizerState.DepthBias = 0; rasterizerState.DepthBiasClamp = 0.0f; rasterizerState.SlopeScaledDepthBias = 0.0f; rasterizerState.DepthClipEnable = true; rasterizerState.ForcedSampleCount = 0; rasterizerState.MultisampleEnable = false; var blendState = new BlendDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; var blend = new RenderTargetBlendDescription { BlendEnable = false, LogicOperationEnable = false, BlendOperation = BlendOperation.Add, BlendOperationAlpha = BlendOperation.Add, LogicOperation = LogicOperation.Clear, DestinationBlend = Blend.DestinationColor, DestinationBlendAlpha = Blend.DestinationAlpha, SourceBlend = Blend.SourceColor, SourceBlendAlpha = Blend.SourceAlpha, RenderTargetWriteMask = 0xF }; blendState.RenderTargets = new RenderTargetBlendDescription[] { blend }; description2.VS = triangleVertex; description2.PS = trianglePixel; description2.SampleMask = 0xFFFFFFFF; description2.RasterizerState = rasterizerState; description2.PrimitiveTopology = PrimitiveTopologyType.Triangle; description2.Samples = samples; description2.DepthStencilState = depthStencil; description2.DsvFormat = GraphicsFormat.D32_Single; description2.IbStripCutValue = IndexBufferStripCut.ValueDisabled; description2.BlendState = blendState; description2.RtvFormats.Add(GraphicsFormat.R8G8B8A8_UNORM); return(new GraphicsPipelineState(ctx, description2)); }
/// <summary> /// Renders the mesh with the specified transformation. This render overrides the base class rendering /// to provide part-by-part texturing support. /// </summary> /// <param name="modelTransform"></param> public void Render(Matrix3D modelTransform) { // setup rasterization RasterizerDescription rDescription = new RasterizerDescription() { FillMode = ShowWireFrame ? FillMode.Wireframe : FillMode.Solid, CullMode = CullMode.Back, FrontCounterClockwise = false, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, DepthClipEnable = true, ScissorEnable = false, MultisampleEnable = true, AntialiasedLineEnable = true, }; RasterizerState rState = this.manager.device.CreateRasterizerState(rDescription); this.manager.device.RS.SetState(rState); this.manager.brightnessVariable.FloatValue = this.LightIntensity; // start rendering foreach (Part part in scene.parts) { if(showOneTexture && (part.name != partEmphasis)) { rDescription.FillMode = FillMode.Wireframe; RasterizerState state = this.manager.device.CreateRasterizerState(rDescription); this.manager.device.RS.SetState(state); } else { rDescription.FillMode = FillMode.Solid; RasterizerState state = this.manager.device.CreateRasterizerState(rDescription); this.manager.device.RS.SetState(state); } EffectTechnique technique = null; if (part.material == null) { technique = this.manager.techniqueRenderVertexColor; } else { if (part.material.textureResource != null) { technique = this.manager.techniqueRenderTexture; ShaderResourceView texture = part.material.textureResource; if (alternateTextures.ContainsKey(part.name)) texture = alternateTextures[part.name]; this.manager.diffuseVariable.SetResource(texture); } else { technique = this.manager.techniqueRenderMaterialColor; this.manager.materialColorVariable.FloatVector = part.material.materialColor; } } // set part transform Transform3DGroup partGroup = new Transform3DGroup(); partGroup.Children.Add( new MatrixTransform3D(PartAnimation(part.name))); partGroup.Children.Add( new MatrixTransform3D( part.partTransform.ToMatrix3D() )); partGroup.Children.Add( new MatrixTransform3D( scene.sceneTransform.ToMatrix3D() ) ); partGroup.Children.Add( new MatrixTransform3D(modelTransform)); this.manager.worldVariable.Matrix = partGroup.Value.ToMatrix4x4F(); if (part.vertexBuffer != null) { // set up vertex buffer and index buffer uint stride = (uint)Marshal.SizeOf(typeof(XMeshVertex)); uint offset = 0; this.manager.device.IA.SetVertexBuffers(0, new D3DBuffer[] { part.vertexBuffer }, new uint[] { stride }, new uint[] { offset }); // Set primitive topology this.manager.device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); TechniqueDescription techDesc = technique.Description; for (uint p = 0; p < techDesc.Passes; ++p) { technique.GetPassByIndex(p).Apply(); PassDescription passDescription = technique.GetPassByIndex(p).Description; // set vertex layout this.manager.device.IA.SetInputLayout( this.manager.device.CreateInputLayout( part.dataDescription, passDescription.InputAssemblerInputSignature, passDescription.InputAssemblerInputSignatureSize)); // draw part this.manager.device.Draw((uint)part.vertexCount, 0); } } } }
void CreateDeviceObjects() { var vertexShaderCode = @" cbuffer vertexBuffer : register(b0) { float4x4 ProjectionMatrix; }; struct VS_INPUT { float2 pos : POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; struct PS_INPUT { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; PS_INPUT main(VS_INPUT input) { PS_INPUT output; output.pos = mul(ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f)); output.col = input.col; output.uv = input.uv; return output; }"; Compiler.Compile(vertexShaderCode, "main", "vs", "vs_4_0", out vertexShaderBlob, out var errorBlob); if (vertexShaderBlob == null) { throw new Exception("error compiling vertex shader"); } vertexShader = device.CreateVertexShader(vertexShaderBlob.GetBytes()); var inputElements = new[] { new InputElementDescription("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElementDescription("TEXCOORD", 0, Format.R32G32_Float, 8, 0, InputClassification.PerVertexData, 0), new InputElementDescription("COLOR", 0, Format.R8G8B8A8_UNorm, 16, 0, InputClassification.PerVertexData, 0), }; inputLayout = device.CreateInputLayout(inputElements, vertexShaderBlob); var constBufferDesc = new BufferDescription { SizeInBytes = VertexConstantBufferSize, Usage = Vortice.Direct3D11.Usage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write }; constantBuffer = device.CreateBuffer(constBufferDesc); var pixelShaderCode = @"struct PS_INPUT { float4 pos : SV_POSITION; float4 col : COLOR0; float2 uv : TEXCOORD0; }; sampler sampler0; Texture2D texture0; float4 main(PS_INPUT input) : SV_Target { float4 out_col = input.col * texture0.Sample(sampler0, input.uv); return out_col; }"; Compiler.Compile(pixelShaderCode, "main", "ps", "ps_4_0", out pixelShaderBlob, out errorBlob); if (pixelShaderBlob == null) { throw new Exception("error compiling pixel shader"); } pixelShader = device.CreatePixelShader(pixelShaderBlob.GetBytes()); var blendDesc = new BlendDescription { AlphaToCoverageEnable = false }; blendDesc.RenderTarget[0] = new RenderTargetBlendDescription { IsBlendEnabled = true, SourceBlend = Blend.SourceAlpha, DestinationBlend = Blend.InverseSourceAlpha, BlendOperation = BlendOperation.Add, SourceBlendAlpha = Blend.InverseSourceAlpha, DestinationBlendAlpha = Blend.Zero, BlendOperationAlpha = BlendOperation.Add, RenderTargetWriteMask = ColorWriteEnable.All }; blendState = device.CreateBlendState(blendDesc); var rasterDesc = new RasterizerDescription { FillMode = FillMode.Solid, CullMode = CullMode.None, ScissorEnable = true, DepthClipEnable = true }; rasterizerState = device.CreateRasterizerState(rasterDesc); var stencilOpDesc = new DepthStencilOperationDescription(StencilOperation.Keep, StencilOperation.Keep, StencilOperation.Keep, ComparisonFunction.Always); var depthDesc = new DepthStencilDescription { DepthEnable = false, DepthWriteMask = DepthWriteMask.All, DepthFunc = ComparisonFunction.Always, StencilEnable = false, FrontFace = stencilOpDesc, BackFace = stencilOpDesc }; depthStencilState = device.CreateDepthStencilState(depthDesc); CreateFontsTexture(); }
void CreateDeviceResources() { uint width = (uint)host.ActualWidth; uint height = (uint)host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); Factory dxgiFactory = Factory.Create(); SwapChainDescription swapDesc = new SwapChainDescription { BufferDescription = new ModeDescription { Width = width, Height = height, Format = Format.R8G8B8A8UNorm, RefreshRate = new Rational { Numerator = 60, Denominator = 1 } }, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, BufferUsage = UsageOptions.RenderTargetOutput, BufferCount = 1, OutputWindowHandle = host.Handle, Windowed = true }; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntiAliasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.State = rasterizerState; // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null }); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8UNorm; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; Texture2DRenderTargetView renderView = renderDesc.Texture2D; renderView.MipSlice = 0; renderDesc.Texture2D = renderView; using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsages.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription = new Texture2DDescription { ArraySize = 1, BindingOptions = BindingOptions.RenderTarget | BindingOptions.ShaderResource, CpuAccessOptions = CpuAccessOptions.None, Format = Format.R8G8B8A8UNorm, Height = 4096, Width = 512, MipLevels = 1, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, Usage = Usage.Default }; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GraphicsSurface) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix; viewMatrixVariable = shader.GetVariableByName("View").AsMatrix; projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix; diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource; // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.InputLayout = vertexLayout; IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindingOptions = BindingOptions.VertexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; SubresourceData InitData = new SubresourceData { SystemMemory = verticesDataPtr }; vertexBuffer = device.CreateBuffer(bd, InitData); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] { vertexBuffer }, new uint[] { stride }, new uint[] { offset } ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindingOptions = BindingOptions.IndexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; InitData.SystemMemory = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float)Math.PI * 0.1f, width / (float)height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))), new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black))) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.StandardRgb, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
public bool Init(IntPtr WindowHandle) { var factory = DXGI.CreateDXGIFactory1 <IDXGIFactory1>(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); var adapterDescription = adapter.Description; //VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; //VideoCardDescription = adapterDescription.Description.Trim('\0'); monitor.Dispose(); adapter.Dispose(); var swapChainDesc = new SwapChainDescription() { BufferCount = 2, BufferDescription = new ModeDescription(1920, 1080, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputWindow = WindowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; // Create Device and DeviceContext ID3D11Device TempDevice = null; ID3D11DeviceContext TempDeviceContext = null; D3D11.D3D11CreateDevice(adapter, DriverType.Hardware, DeviceCreationFlags.None, null, out TempDevice, out TempDeviceContext); Device = TempDevice.QueryInterface <ID3D11Device1>(); DeviceContext = TempDeviceContext.QueryInterface <ID3D11DeviceContext1>(); TempDevice.Dispose(); TempDeviceContext.Dispose(); // Create SwapChain SwapChain = factory.CreateSwapChain(Device, swapChainDesc); factory.MakeWindowAssociation(WindowHandle, WindowAssociationFlags.IgnoreAltEnter); var backBuffer = SwapChain.GetBuffer <ID3D11Texture2D>(0); m_RenderTargetView = Device.CreateRenderTargetView(backBuffer); backBuffer.Dispose(); // Create blend state BlendDescription bsd = new BlendDescription() { AlphaToCoverageEnable = false,//true, IndependentBlendEnable = false, }; bsd.RenderTarget[0].BlendOperationAlpha = BlendOperation.Add; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].DestinationBlendAlpha = Blend.One; bsd.RenderTarget[0].DestinationBlend = Blend.InverseSourceAlpha; bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteEnable.All; bsd.RenderTarget[0].SourceBlendAlpha = Blend.Zero; bsd.RenderTarget[0].SourceBlend = Blend.SourceAlpha; bsd.AlphaToCoverageEnable = true; ID3D11BlendState bsAlpha = Device.CreateBlendState(bsd); // Set Blend State DeviceContext.OMSetBlendState(bsAlpha); BuildDepthStencilView(1920, 1080); // Create rasterizers m_RSDesc = new RasterizerDescription() { AntialiasedLineEnable = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, DepthClipEnable = false, FillMode = FillMode.Solid, FrontCounterClockwise = true, MultisampleEnable = true, ScissorEnable = false, SlopeScaledDepthBias = .0f }; m_RSCullSolid = Device.CreateRasterizerState(m_RSDesc); m_RSDesc.CullMode = CullMode.None; m_RSSolid = Device.CreateRasterizerState(m_RSDesc); m_RSDesc.FillMode = FillMode.Wireframe; m_RSWireFrame = Device.CreateRasterizerState(m_RSDesc); m_RSDesc.CullMode = CullMode.Back; m_RSCullWireFrame = Device.CreateRasterizerState(m_RSDesc); UpdateRasterizer(); return(true); }