public PathShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(FileName, "VS", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(FileName, "PS", "ps_4_0", ShaderFlags); var geometryShaderByteCode = ShaderBytecode.CompileFromFile(FileName, "GS", "gs_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); GeometryShader = new GeometryShader(device, geometryShaderByteCode); Layout = VertexDefinition.Path.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); geometryShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); ConstantPathDataBuffer = new Buffer(device, new BufferDescription { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<PathData>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }); SamplerState = new SamplerState(device, WrapSamplerStateDescription); }
public WorldTerrainShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TerrainVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TerrainPixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.PositionTexture.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); var samplerDescMap = new SamplerStateDescription { Filter = Filter.MinMagMipPoint, AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = Color.Transparent, MinimumLod = 0, MaximumLod = float.MaxValue }; SamplerStateMap = new SamplerState(device, samplerDescMap); }
private void InitializeShaders() { using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile( Path.Combine(Properties.Resources.ShadersFolder, "vertexShader.hlsl"), "main", "vs_5_0", ShaderFlags.Debug)) { _inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); _vertexShader = new D3D11.VertexShader(_d3DDevice, vertexShaderByteCode.Bytecode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile( Path.Combine(Properties.Resources.ShadersFolder, "pixelShader.hlsl"), "main", "ps_5_0", ShaderFlags.Debug)) { _pixelShader = new D3D11.PixelShader(_d3DDevice, pixelShaderByteCode); } // Set as current vertex and pixel shaders _d3DDeviceContext.VertexShader.Set(_vertexShader); _d3DDeviceContext.PixelShader.Set(_pixelShader); _d3DDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; _inputLayout = new D3D11.InputLayout(_d3DDevice, _inputSignature, _inputElements); _d3DDeviceContext.InputAssembler.InputLayout = _inputLayout; }
protected override void Load(ResourceDesc resourceDescription) { ShaderResourceDesc desc = (ShaderResourceDesc)resourceDescription; string file = System.IO.File.ReadAllText(resourceDescription.FileName); InputElements = Rendering.ShaderPreprocessor.Preprocess(file); // Creates a string with specified Defines string defines = ""; if (desc.Defines != null) { foreach (string str in desc.Defines) { defines += String.Format("#define {0}\n", str); } file = defines + file; } ShaderInclude shaderInclude = new ShaderInclude("data/shaders/"); ShaderBytecode vsShaderByteCode = ShaderBytecode.Compile(file, "vs_main", "vs_5_0", ShaderFlags.Debug, EffectFlags.None, null, shaderInclude); ShaderBytecode psShaderByteCode = ShaderBytecode.Compile(file, "ps_main", "ps_5_0", ShaderFlags.Debug, EffectFlags.None, null, shaderInclude); shaderInclude.Dispose(); InputSignature = ShaderSignature.GetInputSignature(vsShaderByteCode); VertexShader = new D3D11.VertexShader(desc.Device, vsShaderByteCode); PixelShader = new D3D11.PixelShader(desc.Device, psShaderByteCode); Shader = new Rendering.Shader(desc.Device, VertexShader, PixelShader, InputSignature, InputElements, resourceDescription.Alias); }
private void InitializeShaders() { ConstantBuffer data = new ConstantBuffer(); data.worldViewProjectionMatrix = Matrix.Identity; data.worldMatrix = Matrix.Identity; data.viewProjectionMatrix = Matrix.Identity; data.time = 0.0f; constantBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.ConstantBuffer, ref data); using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\MainVS.hlsl", "main", "vs_5_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, include: new StreamInclude())) { Debug.Assert(vertexShaderByteCode.Bytecode != null, vertexShaderByteCode.Message); mainVertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); using (var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode)) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\MainPS.hlsl", "main", "ps_5_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, include: new StreamInclude())) { Debug.Assert(pixelShaderByteCode.Bytecode != null, pixelShaderByteCode.Message); mainPixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } }
private void InitializeShaders() { // Compile the vertex shader code using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { // Read input signature from shader code inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode); } // Compile the pixel shader code using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode); } // Set as current vertex and pixel shaders d3dDeviceContext.VertexShader.Set(vertexShader); d3dDeviceContext.PixelShader.Set(pixelShader); d3dDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; // Create the input layout from the input signature and the input elements inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); // Set input layout to use d3dDeviceContext.InputAssembler.InputLayout = inputLayout; }
public FilterPixelShader(Device device, int imageWidth, int imageHeight, int constantBufferSize, string pixelShaderBytecodeFilename) { vertexShader = new VertexShader(device, new ShaderBytecode(File.ReadAllBytes("Content/FullScreenQuadVS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes(pixelShaderBytecodeFilename))); var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = false, IsFrontCounterClockwise = true, IsMultisampleEnabled = false, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); if (constantBufferSize > 0) { var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = constantBufferSize, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new Buffer(device, constantBufferDesc); } viewport = new Viewport(0, 0, imageWidth, imageHeight); // TODO: get these dimensions vertexBufferBinding = new VertexBufferBinding(null, 0, 0); }
public static void BuildAndBindShaders() { D3D11.InputElement[] inputElements = { new D3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, D3D11.InputClassification.PerVertexData, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32_Float, 12, 0, D3D11.InputClassification.PerVertexData, 0) }; using (var byteCode = ShaderBytecode.CompileFromFile("vertex.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { _inputSignature = ShaderSignature.GetInputOutputSignature(byteCode); _inputLayout = new D3D11.InputLayout(_d3dDevice, _inputSignature, inputElements); _d3dDeviceContext.InputAssembler.InputLayout = _inputLayout; _vertexShader = new D3D11.VertexShader(_d3dDevice, byteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixel.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { _pixelShader = new D3D11.PixelShader(_d3dDevice, pixelShaderByteCode); } _d3dDeviceContext.VertexShader.Set(_vertexShader); _d3dDeviceContext.PixelShader.Set(_pixelShader); _d3dDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; }
public TextureShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TextureVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TexturePixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.PositionTexture.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription { Filter = Filter.Anisotropic, AddressU = TextureAddressMode.Mirror, AddressV = TextureAddressMode.Mirror, AddressW = TextureAddressMode.Mirror, MipLodBias = 0, MaximumAnisotropy = 16, ComparisonFunction = Comparison.Always, BorderColor = new Color4(1, 1, 1, 1), MinimumLod = 0, MaximumLod = 0 }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); }
private void InitScene() { D3D11.InputElement[] inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0) }; using (CompilationResult vsResult = ShaderBytecode.CompileFromFile("vs.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { vs = new D3D11.VertexShader(device, vsResult.Bytecode.Data); vertLayout = new D3D11.InputLayout(device, vsResult.Bytecode, inputElements); } using (CompilationResult psResult = ShaderBytecode.CompileFromFile("ps.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) ps = new D3D11.PixelShader(device, psResult.Bytecode.Data); deviceContext.VertexShader.Set(vs); deviceContext.PixelShader.Set(ps); verts = new RawVector3[] { new RawVector3(0.0f, 0.5f, 0.5f), new RawVector3(0.5f, -0.5f, 0.5f), new RawVector3(-0.5f, -0.5f, 0.5f) }; vertBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.VertexBuffer, verts); deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertBuffer, Utilities.SizeOf <RawVector3>(), 0)); deviceContext.InputAssembler.InputLayout = vertLayout; deviceContext.InputAssembler.PrimitiveTopology = D3D.PrimitiveTopology.TriangleList; }
/// <summary> /// Loads the resource. /// </summary> protected internal override void LoadShader(EngineDevice device, byte[] shaderBytecode) { if (m_vertexShader == null) { m_vertexShader = new D3D11.VertexShader(device.DeviceD3D11_1, shaderBytecode); } }
private void RenderDots() { LoadData(); d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178)); swapChain.Present(1, PresentFlags.None); vertexBuffer = D3D11.Buffer.Create <Vector3>(d3dDevice, D3D11.BindFlags.VertexBuffer, dots.ToArray()); //Shader Code using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode); inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode); } inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); d3dDeviceContext.InputAssembler.InputLayout = inputLayout; LoadData(); //DRAW d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 166, 178)); d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vector3>(), 0)); d3dDeviceContext.Draw(dotsArray.Count(), 0); swapChain.Present(1, PresentFlags.None); }
public IShader LoadVS(string path, Type constantsType = null) { using (var cr = ShaderBytecode.CompileFromFile(path, "main", "vs_5_0", DEBUG_FLAG)) { if (cr.Bytecode == null) { throw new Exception(cr.Message); } var gpuShader = new D3D11.VertexShader(Graphics.Device, cr); var inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new D3D11.InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }; var inputSignature = ShaderSignature.GetInputSignature(cr); var inputLayout = new D3D11.InputLayout(Graphics.Device, inputSignature, inputElements); var shader = new SharpDXShader(Graphics, gpuShader, inputLayout, constantsType); m_Shaders.Add(shader); return(shader); } }
public PhysicsDebugDraw(DeviceManager manager) { device = manager.Direct3DDevice; inputAssembler = device.ImmediateContext.InputAssembler; lineArray = new PositionColored[0]; using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "VSMain", "vs_5_0")) { vertexShader = new VertexShader(device, bc); InputElement[] elements = new InputElement[] { new InputElement("SV_POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; inputLayout = new InputLayout(device, bc, elements); } vertexBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "PSMain", "ps_5_0")) pixelShader = new PixelShader(device, bc); }
private Shader(GraphicsDevice device, ShaderStage shaderStage, byte[] shaderBytecode) : base(device) { this.stage = shaderStage; switch (shaderStage) { case ShaderStage.Vertex: NativeDeviceChild = new VertexShader(device.NativeDevice, shaderBytecode); NativeInputSignature = shaderBytecode; break; case ShaderStage.Hull: NativeDeviceChild = new HullShader(device.NativeDevice, shaderBytecode); break; case ShaderStage.Domain: NativeDeviceChild = new DomainShader(device.NativeDevice, shaderBytecode); break; case ShaderStage.Geometry: NativeDeviceChild = new GeometryShader(device.NativeDevice, shaderBytecode); break; case ShaderStage.Pixel: NativeDeviceChild = new PixelShader(device.NativeDevice, shaderBytecode); break; case ShaderStage.Compute: NativeDeviceChild = new ComputeShader(device.NativeDevice, shaderBytecode); break; default: throw new ArgumentOutOfRangeException("shaderStage"); } }
/// <summary> /// /// </summary> void SetupShadersAndLayouts() { ps = PixelShader == null ? null : new D3DPixelShader(device.Device, PixelShader.Bytecode); vs = VertexShader == null ? null : new D3DVertexShader(device.Device, VertexShader.Bytecode); gs = GeometryShader == null ? null : new D3DGeometryShader(device.Device, GeometryShader.Bytecode); hs = HullShader == null ? null : new D3DHullShader(device.Device, HullShader.Bytecode); ds = DomainShader == null ? null : new D3DDomainShader(device.Device, DomainShader.Bytecode); cs = ComputeShader == null ? null : new D3DComputeShader(device.Device, ComputeShader.Bytecode); if (cs != null) { if (ps != null || vs != null || gs != null || hs != null || ds != null) { throw new InvalidOperationException("If ComputeShader is set, other shader must be set null."); } } else { if (vs == null) { throw new InvalidOperationException("Vertex shader must be set."); } } if (VertexInputElements == null) { inputLayout = null; } else { inputLayout = new InputLayout(device.Device, VertexShader.Bytecode, VertexInputElement.Convert(VertexInputElements)); } if (VertexOutputElements != null) { if (GeometryShader == null) { throw new InvalidOperationException("Geometry shader is required for vertex output."); } var outputElements = VertexOutputElement.Convert(VertexOutputElements); int maxBuffers = outputElements.Max(oe => oe.OutputSlot) + 1; var bufferedStrides = new int[maxBuffers]; for (int i = 0; i < maxBuffers; i++) { bufferedStrides[i] = outputElements .Where(oe1 => oe1.OutputSlot == i) .Sum(oe2 => oe2.ComponentCount) * 4; } gs = new D3DGeometryShader(device.Device, GeometryShader.Bytecode, outputElements, bufferedStrides, RasterizedStream); } }
public TerrainMinimapShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "MinimapTerrainVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "MinimapTerrainPixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.TerrainVertex.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); ConstantSelectionBuffer = new Buffer(device, new BufferDescription { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<SelectionBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }); var samplerDescBorder = new SamplerStateDescription { Filter = Filter.Anisotropic, AddressU = TextureAddressMode.MirrorOnce, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, MipLodBias = 0, MaximumAnisotropy = 16, ComparisonFunction = Comparison.Always, BorderColor = Color.Transparent, MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SamplerStateBorder = new SamplerState(device, samplerDescBorder); var samplerDescColor = new SamplerStateDescription { Filter = Filter.Anisotropic, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 16, ComparisonFunction = Comparison.Always, BorderColor = Color.Transparent, MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SamplerStateColor = new SamplerState(device, samplerDescColor); }
public ProjectiveTexturingShader(Device device) { var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso")); vertexShader = new VertexShader(device, shaderByteCode); geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer states var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // constant buffer var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = Constants.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); // user view sampler state var colorSamplerStateDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f), BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f), }; colorSamplerState = new SamplerState(device, colorSamplerStateDesc); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
public LightShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "LightVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "LightPixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.PositionTextureNormal.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var lightBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<LightBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantLightBuffer = new Buffer(device, lightBufferDesc); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var cameraBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<CameraBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantCameraBuffer = new Buffer(device, cameraBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription { Filter = Filter.Anisotropic, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 16, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 10 }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); }
/// <summary> /// Initializes a new instance of the <see cref="GorgonVertexShader" /> class. /// </summary> /// <param name="graphics">The graphics interface that owns this object.</param> /// <param name="name">The name for this shader.</param> /// <param name="isDebug"><b>true</b> if debug information is included in the byte code, <b>false</b> if not.</param> /// <param name="byteCode">The byte code for the shader..</param> internal GorgonVertexShader(GorgonGraphics graphics, string name, bool isDebug, ShaderBytecode byteCode) : base(graphics, name, isDebug, byteCode) { graphics.Log.Print($"Creating {ShaderType} '{name}' ({ID})", LoggingLevel.Verbose); _nativeShader = new D3D11.VertexShader(graphics.D3DDevice, byteCode) { DebugName = name + " D3D11VertexShader" }; }
private void CreateShaders() { foreach (var shaderBytecode in effectBytecode.Stages) { var bytecodeRaw = shaderBytecode.Data; var reflection = effectBytecode.Reflection; // TODO CACHE Shaders with a bytecode hash switch (shaderBytecode.Stage) { case ShaderStage.Vertex: vertexShader = new VertexShader(GraphicsDevice.NativeDevice, bytecodeRaw); // Note: input signature can be reused when reseting device since it only stores non-GPU data, // so just keep it if it has already been created before. if (inputSignature == null) inputSignature = EffectInputSignature.GetOrCreateLayout(new EffectInputSignature(shaderBytecode.Id, bytecodeRaw)); break; case ShaderStage.Domain: domainShader = new DomainShader(GraphicsDevice.NativeDevice, bytecodeRaw); break; case ShaderStage.Hull: hullShader = new HullShader(GraphicsDevice.NativeDevice, bytecodeRaw); break; case ShaderStage.Geometry: if (reflection.ShaderStreamOutputDeclarations != null && reflection.ShaderStreamOutputDeclarations.Count > 0) { // Calculate the strides var soStrides = new List<int>(); foreach (var streamOutputElement in reflection.ShaderStreamOutputDeclarations) { for (int i = soStrides.Count; i < (streamOutputElement.Stream + 1); i++) { soStrides.Add(0); } soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float); } var soElements = new StreamOutputElement[0]; // TODO CREATE StreamOutputElement from bytecode.Reflection.ShaderStreamOutputDeclarations geometryShader = new GeometryShader(GraphicsDevice.NativeDevice, bytecodeRaw, soElements, soStrides.ToArray(), reflection.StreamOutputRasterizedStream); } else { geometryShader = new GeometryShader(GraphicsDevice.NativeDevice, bytecodeRaw); } break; case ShaderStage.Pixel: pixelShader = new PixelShader(GraphicsDevice.NativeDevice, bytecodeRaw); break; case ShaderStage.Compute: computeShader = new ComputeShader(GraphicsDevice.NativeDevice, bytecodeRaw); break; } } }
/// <summary> /// Function to compile the shader. /// </summary> /// <param name="byteCode">Byte code for the shader.</param> protected override void CreateShader(ShaderBytecode byteCode) { if (D3DShader != null) { D3DShader.Dispose(); } D3DShader = new D3D.VertexShader(Graphics.D3DDevice, byteCode) { DebugName = "Gorgon Vertex Shader '" + Name + "'" }; }
public Style(String vertexShaderFilename, String pixelShaderFilename, InputElement[] layoutElements, int floatsPerVertex, DeviceManager deviceManager) { var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; // Read pre-compiled shader byte code relative to current directory var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\" + vertexShaderFilename); this.pixelShader = new PixelShader(deviceManager.DeviceDirect3D, NativeFile.ReadAllBytes(path + "\\" + pixelShaderFilename)); this.vertexShader = new VertexShader(deviceManager.DeviceDirect3D, vertexShaderByteCode); // Specify the input layout for the new style this.layout = new InputLayout(deviceManager.DeviceDirect3D, vertexShaderByteCode, layoutElements); this.floatsPerVertex = floatsPerVertex; }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { D3D11.VertexShader shader = Interlocked.Exchange(ref _nativeShader, null); if (shader != null) { Graphics.Log.Print($"Destroying {ShaderType} '{Name}' ({ID})", LoggingLevel.Verbose); shader.Dispose(); } base.Dispose(); }
public Shader(D3D11.Device device, D3D11.VertexShader vertexShader, D3D11.PixelShader pixelShader, ShaderSignature inputSignature, D3D11.InputElement[] inputElements, string alias) { this.VertexShader = vertexShader; this.PixelShader = pixelShader; this.InputSignature = inputSignature; this.InputLayout = new D3D11.InputLayout(device, InputSignature, inputElements); this.Alias = alias; }
internal unsafe void RecordCommands(MyRenderableProxy proxy, MyFoliageStream stream, int voxelMatId, VertexShader vertexShader, InputLayout inputLayout, int materialIndex, int indexCount, int startIndex, int baseVertex) { if (stream.m_stream == VertexBufferId.NULL) return; //var worldMatrix = proxy.WorldMatrix; //worldMatrix.Translation = Vector3D.Zero; //MyObjectData objectData = proxy.ObjectData; //objectData.LocalMatrix = Matrix.Identity; var worldMat = proxy.WorldMatrix; //worldMat.Translation -= MyRender11.Environment.CameraPosition; MyObjectDataCommon objectData = proxy.CommonObjectData; objectData.LocalMatrix = worldMat; MyMapping mapping = MyMapping.MapDiscard(RC, proxy.ObjectBuffer); mapping.WriteAndPosition(ref proxy.VoxelCommonObjectData); mapping.WriteAndPosition(ref objectData); mapping.Unmap(); RC.AllShaderStages.SetConstantBuffer(MyCommon.OBJECT_SLOT, proxy.ObjectBuffer); BindProxyGeometry(proxy, RC); RC.VertexShader.Set(vertexShader); RC.SetInputLayout(inputLayout); int offset = -1; if (!stream.Append) { offset = 0; stream.Append = true; } RC.SetTarget(stream.m_stream.Buffer, offset); RC.AllShaderStages.SetConstantBuffer(MyCommon.FOLIAGE_SLOT, MyCommon.FoliageConstants); float densityFactor = MyVoxelMaterials1.Table[voxelMatId].FoliageDensity * MyRender11.Settings.GrassDensityFactor; float zero = 0; mapping = MyMapping.MapDiscard(RC, MyCommon.FoliageConstants); mapping.WriteAndPosition(ref densityFactor); mapping.WriteAndPosition(ref materialIndex); mapping.WriteAndPosition(ref voxelMatId); mapping.WriteAndPosition(ref zero); mapping.Unmap(); RC.DrawIndexed(indexCount, startIndex, baseVertex); }
private void InitializeEffect() { var vsBytecode = ShaderBytecode.CompileFromFile(string.Format(@"Content\{0}", FileName), "VS_Main", "vs_5_0"); var psBytecode = ShaderBytecode.CompileFromFile(string.Format(@"Content\{0}", FileName), "PS_Main", "ps_5_0"); _pixelShader = new PixelShader(_myGame.GraphicsDevice, psBytecode); _vertexShader = new VertexShader(_myGame.GraphicsDevice, vsBytecode); _layout = new InputLayout(_myGame.GraphicsDevice, ShaderSignature.GetInputSignature(vsBytecode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0) }); }
public ColorShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "ColorVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "ColorPixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.PositionColor.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); }
public ColorShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(VertexShaderFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(PixelShaderFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); var inputElements = new InputElement[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = ColorShader.Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<MatrixBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); }
public FontShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "FontVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "FontPixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.PositionTextureColor.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); SamplerState = new SamplerState(device, WrapSamplerStateDescription); }
private void InitializeShaders() { var assembly = Assembly.GetExecutingAssembly(); using (var vxShaderStream = assembly.GetManifestResourceStream("D3D11Shaders.PostProcessingQuad.cso")) using (var psShaderStream = assembly.GetManifestResourceStream("D3D11Shaders.PostProcessingColor.cso")) { using (var vbc = D3DCompiler.ShaderBytecode.FromStream(vxShaderStream)) using (var pbcTm = D3DCompiler.ShaderBytecode.FromStream(psShaderStream)) { psToneMapping = new D3D11.PixelShader(d3dDevice, pbcTm); vsQuad = new D3D11.VertexShader(d3dDevice, vbc); shaderInputSigVsQuad = D3DCompiler.ShaderSignature.GetInputSignature(vbc); } } }
void InitializeShaders(ShaderBytecode vertexShaderBytecode, ShaderBytecode pixelShaderBytecode) { vertexShader = new D3D11.VertexShader(device, vertexShaderBytecode); deviceContext.VertexShader.Set(vertexShader); pixelShader = new D3D11.PixelShader(device, pixelShaderBytecode); deviceContext.PixelShader.Set(pixelShader); D3D11.InputElement[] inputElements = new[] { new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0), new D3D11.InputElement("TEXTCOORD", 0, DXGI.Format.R32G32_Float, 0), new D3D11.InputElement("TEXTCOORD", 1, DXGI.Format.R32G32_Float, 0), new D3D11.InputElement("MODE", 0, DXGI.Format.R32_UInt, 0), }; deviceContext.InputAssembler.InputLayout = new D3D11.InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderBytecode), inputElements); }
public CVertexShader(ICDevice device, CShaderReflection reflection) : base(device, reflection) { Profile = ParseProfile(Reflection.Profile); var text = GenerateText<CVertexShader>(WriteIOAndCode); try { Bytecode = ShaderBytecode.Compile(text, "main", ProfileToString(Profile), ShaderFlags.PackMatrixColumnMajor | ShaderFlags.OptimizationLevel3, EffectFlags.None, Name); } catch (Exception e) { throw new ArgumentException(string.Format("Failed to compile a vertex shader '{0}'\r\n--- Code ---\r\n{1}\r\n--- Errors ---\r\n{2}", Name, text, e.Message), e); } D3DVertexShader = new VertexShader(device.D3DDevice, Bytecode); D3DInputElementsDraft = CreateVertexElementsDraft(reflection); }
public void Compile() { // Compilo Vertex y Pixel Shaders CompilationResult vertexShaderBytecode = ShaderBytecode.CompileFromFile(_path, _vertexShaderEntryPoint, "vs_4_0", ShaderFlags.None, EffectFlags.None); CompilationResult pixelShaderBytecode = ShaderBytecode.CompileFromFile(_path, _pixelShaderEntryPoint, "ps_4_0", ShaderFlags.None, EffectFlags.None); _vertexShader = new VertexShader(GraphicManager.Device, vertexShaderBytecode); _pixelShader = new PixelShader(GraphicManager.Device, pixelShaderBytecode); Layout = new InputLayout(GraphicManager.Device, ShaderSignature.GetInputSignature(vertexShaderBytecode), VertexDescription.PosNormVertexInput); vertexShaderBytecode.Dispose(); pixelShaderBytecode.Dispose(); _compiled = true; }
private void InitializeShaders() { using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode); } d3dDeviceContext.VertexShader.Set(vertexShader); d3dDeviceContext.PixelShader.Set(pixelShader); d3dDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); d3dDeviceContext.InputAssembler.InputLayout = inputLayout; }
protected void InitializeShaders() { using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0", ShaderFlags.Debug)) { InputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); VertexShader = new Direct3D11.VertexShader(GameDevice, vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0", ShaderFlags.Debug)) { PixelShader = new Direct3D11.PixelShader(GameDevice, pixelShaderByteCode); } DeviceContext.VertexShader.Set(VertexShader); DeviceContext.PixelShader.Set(PixelShader); InputLayoutMain = new InputLayout(GameDevice, InputSignature, inputElements); DeviceContext.InputAssembler.InputLayout = InputLayoutMain; }
public static void Init(SharpDX.Direct3D11.Device device) { vertexShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/VertexShader.hlsl", "vertex", "vs_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null); vertexShader = new VertexShader(device, vertexShaderByteCode, null); vertices = SharpDX.Direct3D11.Buffer.Create<Vertex>(device, BindFlags.VertexBuffer, new Vertex[] { new Vertex(new Vector4(-1f, -1f, 0.5f, 1f), new Vector2(0f, 1f)), new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)), new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)), new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)), new Vertex(new Vector4(1f, 1f, 0.5f, 1f), new Vector2(1f, 0f)), new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)) }, 144, ResourceUsage.Default, CpuAccessFlags.None, ResourceOptionFlags.None, 0); layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), Vertex.elements); binding = new VertexBufferBinding(vertices, 24, 0); buffer = new SharpDX.Direct3D11.Buffer(device, 64, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); data.offset = 0f; data.scale = 1f; }
public Shader(Device device, string shaderFile, string vertexTarget, string pixelTraget, InputElement[] layouts) { var shaderString = ShaderBytecode.PreprocessFromFile(shaderFile); using (var bytecode = ShaderBytecode.Compile(shaderString, vertexTarget, "vs_4_0")) { layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), layouts); vertShader = new VertexShader(device, bytecode); } using (var bytecode = ShaderBytecode.Compile(shaderString, pixelTraget, "ps_4_0")) { pixShader = new PixelShader(device, bytecode); } OnCleanup += vertShader.Dispose; OnCleanup += pixShader.Dispose; OnCleanup += layout.Dispose; }
private void InitializeShader() { //creating shaderbytecode from a file and using it for initializing shader (data, start methode, version to use, flag) using (var vertextShaderByteCode = ShaderBytecode.CompileFromFile("Shader/standardVertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { //get the signature for the input inputSignature = ShaderSignature.GetInputSignature(vertextShaderByteCode); //creating a vertex shader for the device vertexShader = new D3D11.VertexShader(device, vertextShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shader/standardPixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { //creating a pixel shader for the device pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } //creating the Input Layout (device, signature, inputElements) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); //set the device, to use the shader deviceContext.VertexShader.Set(vertexShader); deviceContext.PixelShader.Set(pixelShader); //set the primitive topology (how to treat the input) deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; //set the device to use the input Layout deviceContext.InputAssembler.InputLayout = inputLayout; deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0)); float ratio = (float)Size.X / (float)Size.Y; Matrix ratioMatrix = new Matrix(1 / ratio, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); ratioBuffer = D3D11.Buffer.Create <Matrix>(device, D3D11.BindFlags.ConstantBuffer, ref ratioMatrix); deviceContext.VertexShader.SetConstantBuffer(0, ratioBuffer); Matrix invCamara = camara.GetInvertedCamaraPosition(); camaraBuffer = D3D11.Buffer.Create <Matrix>(device, D3D11.BindFlags.ConstantBuffer, ref invCamara); deviceContext.VertexShader.SetConstantBuffer(1, camaraBuffer); }
void InitializeShaders() { using (var vertexShaderByteCode = D3DCompiler.ShaderBytecode.CompileFromFile("../../src/vertexShader.hlsl", "main", "vs_4_0", D3DCompiler.ShaderFlags.Debug)) { m_inputSignature = D3DCompiler.ShaderSignature.GetInputOutputSignature(vertexShaderByteCode); m_vertexShader = new D3D11.VertexShader(m_d3d11Device, vertexShaderByteCode); } using (var pixelShaderByteCode = D3DCompiler.ShaderBytecode.CompileFromFile("../../src/pixelShader.hlsl", "main", "ps_4_0", D3DCompiler.ShaderFlags.Debug)) { m_pixelShader = new D3D11.PixelShader(m_d3d11Device, pixelShaderByteCode); } m_d3d11DeviceContext.VertexShader.Set(m_vertexShader); m_d3d11DeviceContext.PixelShader.Set(m_pixelShader); m_d3d11DeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; m_inputLayout = new D3D11.InputLayout(m_d3d11Device, m_inputSignature, m_inputElments); m_d3d11DeviceContext.InputAssembler.InputLayout = m_inputLayout; }
void Create(ShaderBytecode bytecode) { var context = m_device.ImmediateContext; m_vertexShader = ToDispose(new VertexShader(m_device, bytecode)); context.VertexShader.Set(m_vertexShader); m_shaderDataBuffer = ToDispose(new Buffer(m_device, Utilities.SizeOf<ShaderData>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); //create world matrix Matrix w = Matrix.Identity; w *= Matrix.Scaling(2.0f, 2.0f, 0); w *= Matrix.Translation(-1.0f, -1.0f, 0); w.Transpose(); m_shaderData.WorldMatrix = w; context.UpdateSubresource(ref m_shaderData, m_shaderDataBuffer); context.VertexShader.SetConstantBuffer(0, m_shaderDataBuffer); }
/// <summary> /// Binds the effect shader to the specified <see cref="Device"/>. /// </summary> /// <param name="device">The device to bind the shader to.</param> /// <returns>If the binding was successful.</returns> public bool Initialize(Device device) { try { matrixBuffer = new Buffer(device, Matrix.SizeInBytes * 3, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0) {DebugName = "Matrix buffer"}; using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Texture.vs", "TextureVertexShader", "vs_4_0")) { layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), TextureDrawingVertex.VertexDeclaration) { DebugName = "Color vertex layout" }; vertexShader = new VertexShader(device, bytecode) { DebugName = "Texture vertex shader" }; } using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Texture.ps", "TexturePixelShader", "ps_4_0")) { pixelShader = new PixelShader(device, bytecode) { DebugName = "Texture pixel shader" }; } var samplerDesc = new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.ComparisonMinMagMipLinear, MaximumAnisotropy = 1, MipLodBias = 0f, MinimumLod = 0, MaximumLod = float.MaxValue, BorderColor = Color.LimeGreen, ComparisonFunction = Comparison.Always }; pixelSampler = new SamplerState(device, samplerDesc); texture = new Texture(); return texture.Initialize(device, "Textures/dirt.dds"); } catch (Exception e) { MessageBox.Show("Shader error: " + e.Message); return false; } }
void InitializeDevice() { // Create Direct3D 11 Device without SwapChain device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport); deviceContext = device.ImmediateContext; // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new D3D11.InputLayout( device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new D3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = D3D11.Buffer.Create(device, D3D11.BindFlags.VertexBuffer, new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); // Prepare All the stages deviceContext.InputAssembler.InputLayout = layout; deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertices, 32, 0)); deviceContext.VertexShader.Set(vertexShader); deviceContext.PixelShader.Set(pixelShader); }
private void InitializeShaders() { ConstantBufferCPU data = new ConstantBufferCPU(); data.worldViewProjectionMatrix = Matrix.Identity; data.time = 0.0f; data.padding = Vector3.Zero; constantBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.ConstantBuffer, ref data); string textVS = System.IO.File.ReadAllText("Shaders\\MainVS.hlsl"); using (var vertexShaderByteCode = ShaderBytecode.Compile(textVS, "main", "vs_4_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, EffectFlags.None, null, new StreamInclude(), sourceFileName: "Shaders\\MainVS.hlsl")) { if (vertexShaderByteCode.Bytecode == null) { MessageBox.Show(vertexShaderByteCode.Message, "Shader Compilation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(-1); } vertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); using (var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode)) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); } string textPS = System.IO.File.ReadAllText("Shaders\\MainPS.hlsl"); using (var pixelShaderByteCode = ShaderBytecode.Compile(textPS, "main", "ps_4_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, EffectFlags.None, null, new StreamInclude(), sourceFileName: "Shaders\\MainPS.hlsl")) { if (pixelShaderByteCode.Bytecode == null) { MessageBox.Show(pixelShaderByteCode.Message, "Shader Compilation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(-1); } pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } }
public Shader(string file, D3D11.Device device, D3D11.DeviceContext context, params D3D11.InputElement[] inputElements) { if (File.Exists(file + "_vs.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_vs.cso")) { Signature = ShaderSignature.GetInputSignature(byteCode); VertexShader = new D3D11.VertexShader(device, byteCode); InputLayout = new D3D11.InputLayout(device, Signature, inputElements); } } if (File.Exists(file + "_ps.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_ps.cso")) PixelShader = new D3D11.PixelShader(device, byteCode); } if (File.Exists(file + "_gs.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_gs.cso")) GeometryShader = new D3D11.GeometryShader(device, byteCode); } }
private void InitializeShaders() { using (var vertexShaderCode = ShaderBytecode.CompileFromFile("vertex_shader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { inputSignature = ShaderSignature.GetInputSignature(vertexShaderCode); vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderCode); } using (var pixelShaderCode = ShaderBytecode.CompileFromFile("pixel_shader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderCode); } constantBuffer = new D3D11.Buffer(d3dDevice, Utilities.SizeOf <VertexShaderConstants>(), D3D11.ResourceUsage.Default, D3D11.BindFlags.ConstantBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); d3dDeviceContext.VertexShader.SetConstantBuffer(0, constantBuffer); d3dDeviceContext.VertexShader.Set(vertexShader); d3dDeviceContext.PixelShader.Set(pixelShader); d3dDeviceContext.PixelShader.SetShaderResource(0, textureView); d3dDeviceContext.PixelShader.SetSampler(0, samplerState); d3dDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); d3dDeviceContext.InputAssembler.InputLayout = inputLayout; }
/// <summary> /// Binds the effect shader to the specified <see cref="Device"/>. /// </summary> /// <param name="device">The device to bind the shader to.</param> /// <returns>If the binding was successful.</returns> public bool Initialize(Device device) { try { matrixBuffer = new Buffer(device, Matrix.SizeInBytes * 3, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0) {DebugName = "Matrix buffer"}; using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Color.vs", "ColorVertexShader", "vs_4_0")) { layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), ColorDrawingVertex.VertexDeclaration) { DebugName = "Color vertex layout" }; vertexShader = new VertexShader(device, bytecode) { DebugName = "Color vertex shader" }; } using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Color.ps", "ColorPixelShader", "ps_4_0")) { pixelShader = new PixelShader(device, bytecode) { DebugName = "Color pixel shader" }; } return true; } catch (Exception e) { MessageBox.Show("Shader error: " + e.Message); return false; } }
public BasicEffect(Device device) { // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("BasicEffect.fx", "VS", "vs_4_0"); vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("BasicEffect.fx", "PS", "ps_4_0"); pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXTURECOORD", 0, Format.R32G32_Float, 24, 0) }); // Create Constant Buffer constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); Utilities.Dispose(ref vertexShaderByteCode); Utilities.Dispose(ref pixelShaderByteCode); }
/// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (Graphics.Shaders.VertexShader.Current == this) { Graphics.Shaders.VertexShader.Current = null; } if (D3DShader != null) { D3DShader.Dispose(); } } D3DShader = null; _disposed = true; } base.Dispose(disposing); }
private void InitializeShaders() { ConstantBuffer data = new ConstantBuffer(); data.parameters = Vector4.Zero; constantBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.ConstantBuffer, ref data); using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\PostEffectVS.hlsl", "main", "vs_5_0", ShaderFlags.Debug, include: new StreamInclude())) { Debug.Assert(vertexShaderByteCode.Bytecode != null, vertexShaderByteCode.Message); vertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); using (var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode)) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\PostEffectPS.hlsl", "main", "ps_5_0", ShaderFlags.Debug, include: new StreamInclude())) { Debug.Assert(pixelShaderByteCode.Bytecode != null, pixelShaderByteCode.Message); pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } }
/// <inheritdoc/> public void Initialize(Device device) { this.device = device; // Compile Vertex and Pixel shaders var bytecode = ShaderBytecode.CompileFromFile("minmax.hlsl", "MipMapMinMaxVS", "vs_4_0"); vertexShader = ToDispose(new VertexShader(device, bytecode)); // Layout from VertexShader input signature layout = ToDispose(new InputLayout(device,ShaderSignature.GetInputSignature(bytecode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0) })); bytecode.Dispose(); pixelShaderMinMaxBegin = new PixelShader[3]; pixelShaderMinMax = new PixelShader[3]; for (int i = 0; i < 3; i++) { bytecode = ShaderBytecode.CompileFromFile("minmax.hlsl", "MipMapMinMaxBegin" + (i + 1) + "PS", "ps_4_0"); pixelShaderMinMaxBegin[i] = ToDispose(new PixelShader(device, bytecode)); bytecode.Dispose(); bytecode = ShaderBytecode.CompileFromFile("minmax.hlsl", "MipMapMinMax" + (i + 1) + "PS", "ps_4_0"); pixelShaderMinMax[i]= ToDispose(new PixelShader(device, bytecode)); bytecode.Dispose(); } // Instantiate Vertex buiffer from vertex data vertices = ToDispose(Buffer.Create(device,BindFlags.VertexBuffer, new[] { -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, })); sampler = ToDispose(new SamplerState(device, new SamplerStateDescription() { Filter = Filter.MinMagMipPoint, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16, })); // Create result 2D texture to readback by CPU textureReadback = ToDispose(new Texture2D( device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, Format = Format.R32G32_Float, Width = 1, Height = 1, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging })); UpdateMinMaxTextures(); }
// Set up the pipeline for drawing a shape then draw it. public void Draw(Shape shape) { // Set pipeline components to suit the shape if necessary. if (currVertexBinding.Buffer != shape.vertexBinding.Buffer) { context.InputAssembler.SetVertexBuffers(0, shape.vertexBinding); currVertexBinding = shape.vertexBinding; } if (currLayout != shape.style.layout) { context.InputAssembler.InputLayout = shape.style.layout; currLayout = shape.style.layout; } if (currTopology != shape.topology) { context.InputAssembler.PrimitiveTopology = shape.topology; currTopology = shape.topology; } if (currVertexShader != shape.style.vertexShader) { context.VertexShader.Set(shape.style.vertexShader); currVertexShader = shape.style.vertexShader; } if (currPixelShader != shape.style.pixelShader) { context.PixelShader.Set(shape.style.pixelShader); currPixelShader = shape.style.pixelShader; } if (currTextureView != shape.textureView) { context.PixelShader.SetShaderResource(0, shape.textureView); currTextureView = shape.textureView; } // Calculate the vertex transformation and update the constant buffer. worldViewProj = world * view * proj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, constantBuffer); // Draw the shape. context.Draw(shape.vertexCount, 0); }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<Matrix>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); return true; } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return false; }; }
/// <summary> /// Unloads the resource. /// </summary> protected internal override void UnloadShader() { m_vertexShader = GraphicsHelper.DisposeObject(m_vertexShader); }
private void ShuddownShader() { // Release the sampler state. if (SampleState != null) { SampleState.Dispose(); SampleState = null; } // Release the matrix constant buffer. if (ConstantMatrixBuffer != null) { ConstantMatrixBuffer.Dispose(); ConstantMatrixBuffer = null; } // Release the layout. if (Layout != null) { Layout.Dispose(); Layout = null; } // Release the pixel shader. if (PixelShader != null) { PixelShader.Dispose(); PixelShader = null; } // Release the vertex shader. if (VertexShader != null) { VertexShader.Dispose(); VertexShader = null; } }
private void SwapChainPanel_OnLoaded(object sender, RoutedEventArgs e) { using (var defDevice = new D3D.Device(DriverType.Hardware, D3D.DeviceCreationFlags.Debug)) { _device = defDevice.QueryInterface <D3D.Device3>(); } _context = _device.ImmediateContext3; var pixelScale = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f; var swapChainDesc = new DXGI.SwapChainDescription1() { AlphaMode = DXGI.AlphaMode.Premultiplied, BufferCount = 2, Flags = DXGI.SwapChainFlags.None, Format = DXGI.Format.B8G8R8A8_UNorm, Width = (int)(panel.RenderSize.Width * pixelScale), Height = (int)(panel.RenderSize.Height * pixelScale), SampleDescription = new DXGI.SampleDescription(1, 0), Scaling = DXGI.Scaling.Stretch, Stereo = false, SwapEffect = DXGI.SwapEffect.FlipSequential, Usage = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput }; using (var dxgiDevice = _device.QueryInterface <DXGI.Device3>()) { var factory = dxgiDevice.Adapter.GetParent <DXGI.Factory4>(); using (var tmpSwapChain = new DXGI.SwapChain1(factory, _device, ref swapChainDesc)) { _swapChain = tmpSwapChain.QueryInterface <DXGI.SwapChain3>(); } } using (var nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(panel)) { nativeObject.SwapChain = _swapChain; } using (var depthBuffer = new D3D.Texture2D(_device, new D3D.Texture2DDescription() { Format = DXGI.Format.D24_UNorm_S8_UInt, ArraySize = 1, MipLevels = 1, Width = swapChainDesc.Width, Height = swapChainDesc.Height, SampleDescription = new DXGI.SampleDescription(1, 0), BindFlags = D3D.BindFlags.DepthStencil, })) { _depthStencilView = new D3D.DepthStencilView(_device, depthBuffer, new D3D.DepthStencilViewDescription() { Dimension = D3D.DepthStencilViewDimension.Texture2D }); } _backBuffer = D3D.Resource.FromSwapChain <D3D.Texture2D>(_swapChain, 0); _renderView = new D3D.RenderTargetView1(_device, _backBuffer); var viewport = new ViewportF(0, 0, (float)panel.RenderSize.Width, (float)panel.RenderSize.Height, 0.0f, 1.0f); _context.Rasterizer.SetViewport(viewport); ShaderBytecode shaderBytecode; using (shaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "vs", "vs_5_0", ShaderFlags.Debug)) { _vertexShader = new D3D.VertexShader(_device, shaderBytecode); } using (var byteCode = ShaderBytecode.CompileFromFile(@"shaders.hlsl", "ps", "ps_5_0", ShaderFlags.Debug)) { _pixelShader = new D3D.PixelShader(_device, byteCode); } D3D.InputElement[] inputElements = { new D3D.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0, 0), }; _inputLayout = new D3D.InputLayout(_device, shaderBytecode, inputElements); _vertices = new[] { new Vector4(-0.5f, 0.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(0.5f, 0.0f, 0.5f, 1.0f), }; _vertexBuffer = D3D.Buffer.Create(_device, D3D.BindFlags.VertexBuffer, _vertices); _vertexBinding = new D3D.VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Vector4>(), 0); _constantBuffer = new SharpDX.Direct3D11.Buffer( _device, Utilities.SizeOf <SharpDX.Matrix>(), D3D.ResourceUsage.Default, D3D.BindFlags.ConstantBuffer, D3D.CpuAccessFlags.None, D3D.ResourceOptionFlags.None, 0); _timer = new Stopwatch(); _timer.Start(); CompositionTarget.Rendering += CompositionTarget_Rendering; }
internal Engine_Material(string _shaderFileName, string _imageFileName, bool _includeGeometryShader = false) { #region //Get Instances m_d3d = Engine_Renderer.Instance; #endregion #region //Create InputLayout var inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0, 0), new D3D11.InputElement("TEXCOORD", 0, DXGI.Format.R32G32_Float, D3D11.InputElement.AppendAligned, 0), new D3D11.InputElement("NORMAL", 0, DXGI.Format.R32G32B32_Float, D3D11.InputElement.AppendAligned, 0) }; #endregion #region //Create VertexShader CompilationResult vsResult; using (vsResult = ShaderBytecode.CompileFromFile(_shaderFileName, "VS", "vs_4_0", ShaderFlags.None)) { m_vertexShader = new D3D11.VertexShader(m_d3d.m_device, vsResult.Bytecode.Data); m_inputLayout = new D3D11.InputLayout(m_d3d.m_device, vsResult.Bytecode, inputElements); } #endregion #region //Create PixelShader using (var psResult = ShaderBytecode.CompileFromFile(_shaderFileName, "PS", "ps_4_0", ShaderFlags.None)) m_pixelShader = new D3D11.PixelShader(m_d3d.m_device, psResult.Bytecode.Data); #endregion #region //Create GeometryShader if (_includeGeometryShader) { using (var psResult = ShaderBytecode.CompileFromFile(_shaderFileName, "GS", "gs_4_0", ShaderFlags.None)) m_geometryShader = new D3D11.GeometryShader(m_d3d.m_device, psResult.Bytecode.Data); } #endregion #region //Create ConstantBuffers for Model SPerModelConstantBuffer cbModel = new SPerModelConstantBuffer(); D3D11.BufferDescription bufferDescription = new D3D11.BufferDescription { BindFlags = D3D11.BindFlags.ConstantBuffer, CpuAccessFlags = D3D11.CpuAccessFlags.Write, Usage = D3D11.ResourceUsage.Dynamic, }; m_model = D3D11.Buffer.Create(m_d3d.m_device, D3D11.BindFlags.ConstantBuffer, ref cbModel); #endregion #region //Create Texture and Sampler var texture = Engine_ImgLoader.CreateTexture2DFromBitmap(m_d3d.m_device, Engine_ImgLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), _imageFileName)); m_resourceView = new D3D11.ShaderResourceView(m_d3d.m_device, texture); D3D11.SamplerStateDescription samplerStateDescription = new D3D11.SamplerStateDescription { Filter = D3D11.Filter.Anisotropic, AddressU = D3D11.TextureAddressMode.Clamp, AddressV = D3D11.TextureAddressMode.Clamp, AddressW = D3D11.TextureAddressMode.Clamp, ComparisonFunction = D3D11.Comparison.Always, MaximumAnisotropy = 16, MinimumLod = 0, MaximumLod = float.MaxValue, }; m_sampler = new D3D11.SamplerState(m_d3d.m_device, samplerStateDescription); #endregion }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<MatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 0 }; // Create the texture sampler state. SampleState = new SamplerState(device, samplerDesc); return true; } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return false; }; }
/// <summary> /// Creates device-based resources to store a constant buffer, cube /// geometry, and vertex and pixel shaders. In some cases this will also /// store a geometry shader. /// </summary> public async void CreateDeviceDependentResourcesAsync() { ReleaseDeviceDependentResources(); usingVprtShaders = deviceResources.D3DDeviceSupportsVprt; var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature // we can avoid using a pass-through geometry shader to set the render // target array index, thus avoiding any overhead that would be // incurred by setting the geometry shader stage. var vertexShaderFileName = usingVprtShaders ? "Content\\Shaders\\VPRTVertexShader.cso" : "Content\\Shaders\\VertexShader.cso"; // Load the compiled vertex shader. var vertexShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFileName)); // After the vertex shader file is loaded, create the shader and input layout. vertexShader = this.ToDispose(new SharpDX.Direct3D11.VertexShader( deviceResources.D3DDevice, vertexShaderByteCode)); SharpDX.Direct3D11.InputElement[] vertexDesc = { new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), new SharpDX.Direct3D11.InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), }; inputLayout = this.ToDispose(new SharpDX.Direct3D11.InputLayout( deviceResources.D3DDevice, vertexShaderByteCode, vertexDesc)); if (!usingVprtShaders) { // Load the compiled pass-through geometry shader. var geometryShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\GeometryShader.cso")); // After the pass-through geometry shader file is loaded, create the shader. geometryShader = this.ToDispose(new SharpDX.Direct3D11.GeometryShader( deviceResources.D3DDevice, geometryShaderByteCode)); } // Load the compiled pixel shader. var pixelShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\PixelShader.cso")); // After the pixel shader file is loaded, create the shader. pixelShader = this.ToDispose(new SharpDX.Direct3D11.PixelShader( deviceResources.D3DDevice, pixelShaderByteCode)); var texture = TextureLoader.CreateTexture2DFromBitmap(deviceResources.D3DDevice, TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), _file)); _textureView = new ShaderResourceView(deviceResources.D3DDevice, texture); // Load mesh vertices. Each vertex has a position and a color. // Note that the cube size has changed from the default DirectX app // template. Windows Holographic is scaled in meters, so to draw the // cube at a comfortable size we made the cube width 0.2 m (20 cm). TexturedVertex[] vertices = { new TexturedVertex(new Vector3(0.0f, 0.0f, 0.0f), new Vector2(0, 1)), new TexturedVertex(new Vector3(_size, 0.0f, 0.0f), new Vector2(1, 1)), new TexturedVertex(new Vector3(_size, _size, 0.0f), new Vector2(1, 0)), new TexturedVertex(new Vector3(0.0f, _size, 0.0f), new Vector2(0, 0)), }; vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, vertices)); // Load mesh indices. Each trio of indices represents // a triangle to be rendered on the screen. // For example: 0,2,1 means that the vertices with indexes // 0, 2 and 1 from the vertex buffer compose the // first triangle of this mesh. ushort[] cubeIndices = { 2, 1, 0, 0, 3, 2, }; indexCount = cubeIndices.Length; indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, cubeIndices)); // Create a constant buffer to store the model matrix. modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.ConstantBuffer, ref modelConstantBufferData)); // Once the cube is loaded, the object is ready to be rendered. loadingComplete = true; }