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 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 SibenikMaterial(Device device, TweakBar bar, String name) : base(device, bar, name) { bar.AddColor(Prefix + "diffuse", "Diffuse", name, new Color3(1, 1, 1)); bar.AddColor(Prefix + "specular", "Specular", name, new Color3(1, 1, 1)); bar.AddFloat(Prefix + "shininess", "Shininess", name, 1, 256, 64, 0.1, 2); bar.AddFloat(Prefix + "brightness", "Brightness", name, 0, 15000, 5, 50, 2); pixelShader = Material.CompileShader(device, "sibenik"); constantBuffer = Material.AllocateMaterialBuffer(device, BufferSize); sampler = new SamplerState(device, new SamplerStateDescription() { ComparisonFunction = Comparison.Always, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic, BorderColor = Color4.Black, MaximumAnisotropy = 16, MaximumLod = 15, MinimumLod = 0, MipLodBias = 0, }); }
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"); } }
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); }
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); }
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); }
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); }
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; } } }
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; }
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 PassThroughFilter(Device device) { this.pixelShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/PassThrough.hlsl", "pixel", "ps_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null); this.pixelShader = new PixelShader(device, this.pixelShaderByteCode, null); this.sampler = new SamplerState(device, new SamplerStateDescription { MaximumAnisotropy = 16, Filter = SharpDX.Direct3D11.Filter.Anisotropic, AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, MinimumLod = 0f, MaximumLod = 100f }); }
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); }
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 CPixelShader(ICDevice device, CShaderReflection reflection) : base(device, reflection) { Profile = ParseProfile(Reflection.Profile); var text = GenerateText<CPixelShader>(WriteIOAndCode); CompilationResult bytecode; 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 pixel shader '{0}'\r\n--- Code ---\r\n{1}\r\n--- Errors ---\r\n{2}", Name, text, e.Message), e); } D3DPixelShader = new PixelShader(device.D3DDevice, bytecode); }
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; }
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; }
/// <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; } }
public GroundMaterial(Device device, TweakBar bar, String name) : base(device, bar, name) { bar.AddFloat(Prefix + "albedo", "Albedo", name, 0, 100, 30, 0.1, 2); pixelShader = Material.CompileShader(device, "ground"); constantBuffer = Material.AllocateMaterialBuffer(device, BufferSize); sampler = new SamplerState(device, new SamplerStateDescription() { ComparisonFunction = Comparison.Always, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic, BorderColor = Color4.Black, MaximumAnisotropy = 16, MaximumLod = 15, MinimumLod = 0, MipLodBias = 0, }); }
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> /// 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; } }
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; }; }
// 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; }; }
private void InitializeGraphics() { //generate data/////////////////////////////////////////////////////////////////////////////////////////////// uint[] indices = new uint[] { 0,1, 1,2, 2,3, 3,4, 4,5, 5,0, }; //create directx objects/////////////////////////////////////////////////////////////////////////////////// SwapChainDescription scd = new SwapChainDescription() { BufferCount = 4, IsWindowed = true, Flags = SwapChainFlags.None, ModeDescription = new ModeDescription(ClientSize.Width, ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), OutputHandle = Handle, SampleDescription = new SampleDescription(8, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; try { Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None, scd, out d, out sc); } catch (Exception EX) { MessageBox.Show("Could not create Device and/or swap chain :" + EX.Message + "\r\n\r\n" + EX.StackTrace); return; } target = Texture2D.FromSwapChain<Texture2D>(sc, 0); targetView = new RenderTargetView(d, target); ib = Buffer.Create(d, BindFlags.IndexBuffer, indices); vs = new VertexShader(d, File.ReadAllBytes("Shaders\\VertexShader.cso")); ps = new PixelShader(d, File.ReadAllBytes("Shaders\\PixelShader.cso")); //set the objects on the device////////////////////////////////////////////////////////////////////////////////////// d.ImmediateContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList; d.ImmediateContext.InputAssembler.SetIndexBuffer(ib, Format.R32_UInt, 0); d.ImmediateContext.VertexShader.Set(vs); d.ImmediateContext.PixelShader.Set(ps); d.ImmediateContext.Rasterizer.SetViewport(0, 0, ClientSize.Width, ClientSize.Height); d.ImmediateContext.Rasterizer.State = new RasterizerState(d, new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid }); d.ImmediateContext.OutputMerger.SetRenderTargets(targetView); clearColor = new Color(System.Drawing.Color.CornflowerBlue.R/255f, System.Drawing.Color.CornflowerBlue.G / 255f, System.Drawing.Color.CornflowerBlue.B / 255f, System.Drawing.Color.CornflowerBlue.A / 255f); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription= new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events Factory factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION",0,Format.R32G32B32A32_Float,0,0), new InputElement("COLOR",0,Format.R32G32B32A32_Float,16,0) }); // Write vertex data to a datastream var stream = new DataStream(32*3, true, true); stream.WriteRange(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) }); stream.Position = 0; // Instantiate Vertex buiffer from vertex data var vertices = new Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 32*3, Usage = ResourceUsage.Default, StructureByteStride = 0 }); stream.Release(); // Prepare All the stages context.InputAssembler.SetInputLayout(layout); context.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f)); context.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Release(); vertexShader.Release(); pixelShaderByteCode.Release(); pixelShader.Release(); vertices.Release(); layout.Release(); renderView.Release(); backBuffer.Release(); context.ClearState(); context.Flush(); device.Release(); context.Release(); swapChain.Release(); factory.Release(); }