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> /// 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) { // Disassociate any shaders after we've destroyed them. if (Graphics.Shaders.ComputeShader.Current == this) { Graphics.Shaders.ComputeShader.Current = null; } if (D3DShader != null) { D3DShader.Dispose(); } D3DShader = null; } _disposed = true; } base.Dispose(disposing); }
/// <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); } }
/// <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 GorgonComputeShader(GorgonGraphics graphics, string name, bool isDebug, ShaderBytecode byteCode) : base(graphics, name, isDebug, byteCode) { graphics.Log.Print($"Creating {ShaderType} '{name}' ({ID})", LoggingLevel.Verbose); _shader = new D3D11.ComputeShader(graphics.D3DDevice, byteCode) { DebugName = name + "_ID3D11ComputeShader" }; }
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> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { D3D11.ComputeShader shader = Interlocked.Exchange(ref _shader, null); if (shader != null) { Graphics.Log.Print($"Destroying {ShaderType} '{Name}' ({ID})", LoggingLevel.Verbose); shader.Dispose(); } base.Dispose(); }
/// <summary> /// Function to create the shader. /// </summary> /// <param name="byteCode">Byte code for the shader.</param> protected override void CreateShader(Compiler.ShaderBytecode byteCode) { if (D3DShader != null) { D3DShader.Dispose(); } D3DShader = new D3D.ComputeShader(Graphics.D3DDevice, byteCode) { #if DEBUG DebugName = string.Format("Gorgon Compute Shader '{0}'", Name) #endif }; }
public ComputeShader(GraphicsDevice device, string fileName, string kernel) { this.Device = device.Handle as Device; this.Context = this.Device.ImmediateContext; var byteCode = ShaderBytecode.CompileFromFile(fileName, kernel, "cs_5_0"); this.Shader = new SharpDX.Direct3D11.ComputeShader(this.Device, byteCode); this.Resources = new Dictionary <string, ResourceBinding>(); using (var reflector = new ShaderReflection(byteCode)) { this.ReflectInputs(reflector, fileName); } }
public CComputeShader(ICDevice device, CShaderReflection reflection) : base(device, reflection) { Profile = ParseProfile(reflection.Profile); ThreadCountX = reflection.GetThreadCountX(); ThreadCountY = reflection.GetThreadCountY(); ThreadCountZ = reflection.GetThreadCountZ(); var text = GenerateText<CComputeShader>(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 compute shader '{0}'\r\n--- Code ---\r\n{1}\r\n--- Errors ---\r\n{2}", Name, text, e.Message), e); } D3DComputeShader = new ComputeShader(device.D3DDevice, bytecode); }
/// <summary> /// Compiles files into shader byte-code and creates a shader from the shader files that exist /// </summary> /// <param name="folderPath"></param> /// <param name="fileName"></param> public ComputeShader(string folderPath, string fileName) { Init(); ShaderFlags shaderFlags = ShaderFlags.Debug; SharpDX.Direct3D11.ComputeShader computeShader = null; // Handler for #include directive HLSLFileIncludeHandler includeHandler = new HLSLFileIncludeHandler(folderPath); string path = Path.Combine(folderPath, fileName); if (File.Exists(path)) { CompilationResult byteCode = ShaderBytecode.CompileFromFile(path, "main", "cs_5_0", shaderFlags, EffectFlags.None, null, includeHandler); computeShader = new SharpDX.Direct3D11.ComputeShader(d3dDevice, byteCode); } this.computeShader = computeShader; }
internal ComputeShader( GraphicsDevice device, string bytecode ) : base(bytecode) { Shader = new D3D11.ComputeShader( device.Device, Misc.HexStringToByte(bytecode) ); }
public ComputeShader(SharpDX.Direct3D11.ComputeShader computeShader) { Init(); this.computeShader = computeShader; }
internal DeviceChild GetOrCompileShader(EffectShaderType shaderType, int index, int soRasterizedStream, StreamOutputElement[] soElements, out string profileError) { DeviceChild shader = null; profileError = null; lock (sync) { shader = compiledShadersGroup[(int)shaderType][index]; if (shader == null) { if (RegisteredShaders[index].Level > graphicsDevice.Features.Level) { profileError = string.Format("{0}", RegisteredShaders[index].Level); return null; } var bytecodeRaw = RegisteredShaders[index].Bytecode; switch (shaderType) { case EffectShaderType.Vertex: shader = new VertexShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Domain: shader = new DomainShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Hull: shader = new HullShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Geometry: if (soElements != null) { // Calculate the strides var soStrides = new List<int>(); foreach (var streamOutputElement in soElements) { for (int i = soStrides.Count; i < (streamOutputElement.Stream+1); i++) { soStrides.Add(0); } soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float); } shader = new GeometryShader(graphicsDevice, bytecodeRaw, soElements, soStrides.ToArray(), soRasterizedStream); } else { shader = new GeometryShader(graphicsDevice, bytecodeRaw); } break; case EffectShaderType.Pixel: shader = new PixelShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Compute: shader = new ComputeShader(graphicsDevice, bytecodeRaw); break; } compiledShadersGroup[(int)shaderType][index] = ToDispose(shader); } } return shader; }
internal static void CreateShader(Device device, out ShaderBytecode shaderCode, out ComputeShader shader, string shaderPath) { MemoryStream mem = new MemoryStream(GetEmbeddedContent(shaderPath)); shaderCode = new ShaderBytecode(mem); shader = new ComputeShader(device, shaderCode); }
internal static void RunComputeShader(DeviceContext context, ComputeShader shader, ShaderResourceView[] views, UnorderedAccessView[] unordered, SharpDX.Direct3D11.Buffer constParams, int x, int y) { ComputeShaderStage cs = context.ComputeShader; cs.Set(shader); cs.SetShaderResources(0, views); cs.SetUnorderedAccessViews(0, unordered); cs.SetConstantBuffer(0, constParams); context.Dispatch(x, y, 1); }
internal void Set(ComputeShader shader) { if (shader == m_computeShader) return; m_computeShader = shader; m_deviceContext.ComputeShader.Set(shader); m_statistics.SetComputeShaders++; }
internal override void ClearState() { base.ClearState(); m_computeShader = null; }
internal ComputeShader(GraphicsDevice device, string bytecode) : base(bytecode) { Shader = new D3D11.ComputeShader(device.Device, Misc.HexStringToByte(bytecode)); }
public AcceleratedWave(D3D11.Device dev, D3D11.DeviceContext context, D3D11.ComputeShader shader) { __construct(dev, context); ownCompute = false; _compShader = shader; }
internal void SetCS(ComputeShader cs) { Context.ComputeShader.Set(cs); }
/// <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 AcceleratedWave(D3D11.Device dev, D3D11.DeviceContext context, String shaderLocation, String shaderMethodName) { __construct(dev, context); _compShader = BuildCompute(shaderLocation, shaderMethodName); ownCompute = true; }
internal DeviceChild GetOrCompileShader(EffectShaderType shaderType, int index) { DeviceChild shader = null; lock (sync) { shader = compiledShaders[index]; if (shader == null) { var bytecodeRaw = dataGroup.Shaders[index].Bytecode; switch (shaderType) { case EffectShaderType.Vertex: shader = new VertexShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Domain: shader = new DomainShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Hull: shader = new HullShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Geometry: shader = new GeometryShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Pixel: shader = new PixelShader(graphicsDevice, bytecodeRaw); break; case EffectShaderType.Compute: shader = new ComputeShader(graphicsDevice, bytecodeRaw); break; } compiledShaders[index] = shader; } } return shader; }
private void GenerateHeightMaps() { ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initTerrain", "cs_5_0", Shader.ShaderFlags); ComputeShader initTerrain = new ComputeShader(_context.DirectX.Device, shaderByteCode); shaderByteCode.Dispose(); shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initWater", "cs_5_0", Shader.ShaderFlags); ComputeShader initWater = new ComputeShader(_context.DirectX.Device, shaderByteCode); shaderByteCode.Dispose(); shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "applyRandomDisplacement", "cs_5_0", Shader.ShaderFlags); _baseTerrainGeneration = new ComputeShader(_context.DirectX.Device, shaderByteCode); shaderByteCode.Dispose(); shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "flowsCalculation", "cs_5_0", Shader.ShaderFlags); _flowsCalculation = new ComputeShader(_context.DirectX.Device, shaderByteCode); shaderByteCode.Dispose(); shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "updateWaterLevel", "cs_5_0", Shader.ShaderFlags); _updateWaterLevel = new ComputeShader(_context.DirectX.Device, shaderByteCode); shaderByteCode.Dispose(); Texture2DDescription textureDescription = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R32_Float, Height = TextureSize, Width = TextureSize, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; ConstantBuffer<ComputeData> computeBuffer = new ConstantBuffer<ComputeData>(_context); _context.DirectX.DeviceContext.ComputeShader.SetConstantBuffer(1, computeBuffer.Buffer); foreach (Face face in _faces) { Texture2D terrainTexture = new Texture2D(_context.DirectX.Device, textureDescription); face.TerrainSrv = new ShaderResourceView(_context.DirectX.Device, terrainTexture); face.TerrainUav = new UnorderedAccessView(_context.DirectX.Device, terrainTexture); terrainTexture.Dispose(); Texture2D waterTexture = new Texture2D(_context.DirectX.Device, textureDescription); face.WaterSrv = new ShaderResourceView(_context.DirectX.Device, waterTexture); face.WaterUav = new UnorderedAccessView(_context.DirectX.Device, waterTexture); waterTexture.Dispose(); Texture2D flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription); face.FlowsLeftUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture); flowsTexture.Dispose(); flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription); face.FlowsTopUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture); flowsTexture.Dispose(); flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription); face.FlowsRightUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture); flowsTexture.Dispose(); flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription); face.FlowsBottomUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture); flowsTexture.Dispose(); _context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(0, face.TerrainUav); _context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(1, face.WaterUav); _context.DirectX.DeviceContext.ComputeShader.Set(initTerrain); computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.0f)); _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1); _context.DirectX.DeviceContext.ComputeShader.Set(initWater); computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.05f)); _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1); _context.DirectX.DeviceContext.ComputeShader.Set(initTerrain); computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, BatchSize / 2, BatchSize / 2, 0.5f)); _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize - 1, TextureSize / BatchSize - 1, 1); } _planeBuffer = new ConstantBuffer<PlaneData>(_context); initTerrain.Dispose(); computeBuffer.Dispose(); }