public void DeviceCreated(GraphicsDevice device) { _device = device; _resources = _device.ResourceFactory; var vertexShaderDescription = new ShaderDescription(ShaderStages.Vertex, Encoding.ASCII.GetBytes(_vertexShaderSource), "main"); var fragmentShaderDescription = new ShaderDescription(ShaderStages.Fragment, Encoding.ASCII.GetBytes(_fragmentShaderSource), "main"); var shaders = _resources.CreateFromSpirv(vertexShaderDescription, fragmentShaderDescription); var shaderSetDescription = new ShaderSetDescription(new VertexLayoutDescription[0], shaders); _resourceLayout = _resources.CreateResourceLayout(new ResourceLayoutDescription(new ResourceLayoutElementDescription("Uniforms", ResourceKind.UniformBuffer, ShaderStages.Fragment))); var sizeOf = (uint)Marshal.SizeOf <ShaderToyUniforms.Uniforms>(); sizeOf = ((sizeOf + 15) / 16) * 16; _uniforms = _resources.CreateBuffer(new BufferDescription( sizeOf, BufferUsage.Dynamic | BufferUsage.UniformBuffer)); _resourceSet = _resources.CreateResourceSet(new ResourceSetDescription(_resourceLayout, _uniforms)); _pipeline = _resources.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.Disabled, RasterizerStateDescription.CullNone, PrimitiveTopology.TriangleStrip, shaderSetDescription, new ResourceLayout[] { _resourceLayout, }, _device.MainSwapchain.Framebuffer.OutputDescription )); _cl = _resources.CreateCommandList(); }
public CacheEntry(string vertexPath, string fragmentPath, ShaderDescription vertexShader, ShaderDescription fragmentShader) { VertexPath = vertexPath; FragmentPath = fragmentPath; VertexShader = vertexShader; FragmentShader = fragmentShader; }
private static Shader[] LoadShader(ResourceFactory resourceFactory, string fragmentShaderSourceCode) { const string vertexCode = @"#version 330 out vec2 uv; const vec2 vertices[4] = vec2[4]( vec2( -1.0, 1.0), vec2( 1.0, 1.0), vec2(-1.0, -1.0), vec2( 1.0, -1.0)); void main() { vec2 pos = vertices[gl_VertexID]; gl_Position = vec4(pos, 0, 1); uv = 0.5 + 0.5 * pos; }" ; var vertexShaderDesc = new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexCode), "main"); var fragmentShaderDesc = new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragmentShaderSourceCode), "main"); //return resourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc); var vertexShader = resourceFactory.CreateShader(vertexShaderDesc); var fragmentShader = resourceFactory.CreateShader(fragmentShaderDesc); return(new Shader[] { vertexShader, fragmentShader }); }
private Shader[] createShaders() { var vertexShaderDesc = new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(File.ReadAllText("./Shaders/RayMarchingDemo/VertexShader.hlsl")), "main"); var fragmentShaderDesc = new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(File.ReadAllText("./Shaders/RayMarchingDemo/FragmentShader.hlsl")), "main"); return(GraphicsDevice.ResourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc)); }
/// <summary> /// Creates a vertex and fragment shader pair from the given <see cref="ShaderDescription"/> pair containing SPIR-V /// bytecode or GLSL source code. /// </summary> /// <param name="factory">The <see cref="ResourceFactory"/> used to compile the translated shader code.</param> /// <param name="vertexShaderDescription">The vertex shader's description. <see cref="ShaderDescription.ShaderBytes"/> /// should contain SPIR-V bytecode or Vulkan-style GLSL source code which can be compiled to SPIR-V.</param> /// <param name="fragmentShaderDescription">The fragment shader's description. /// <see cref="ShaderDescription.ShaderBytes"/> should contain SPIR-V bytecode or Vulkan-style GLSL source code which /// can be compiled to SPIR-V.</param> /// <returns>A two-element array, containing the vertex shader (element 0) and the fragment shader (element 1).</returns> public static Shader[] CreateFromSpirv( this ResourceFactory factory, ShaderDescription vertexShaderDescription, ShaderDescription fragmentShaderDescription) { return(CreateFromSpirv(factory, vertexShaderDescription, fragmentShaderDescription, new CrossCompileOptions())); }
protected override Shader CreateShaderCore(ref ShaderDescription description) { Shader shader = Factory.CreateShader(ref description); DisposeCollector.Add(shader); return(shader); }
public virtual bool Load(GraphicsDevice graphicsDevice, string vertexShaderFileName, string fragmentShaderFileName) { _vertexLayout = new VertexLayoutDescription( new VertexElementDescription(nameof(Vertex.Position), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription(nameof(Vertex.Normal), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription(nameof(Vertex.TextureCoordinate), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)); try { byte[] vertexShaderBytes = File.ReadAllBytes(vertexShaderFileName); ShaderDescription vertexShaderDesc = new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes, "main"); byte[] fragmentShaderBytes = File.ReadAllBytes(fragmentShaderFileName); ShaderDescription fragmentShaderDesc = new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes, "main"); _shaders = graphicsDevice.ResourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc); ShaderSet = new ShaderSetDescription(new[] { _vertexLayout }, _shaders); } catch (Exception e) { Console.WriteLine(e); Dispose(); return(false); } return(true); }
internal MTLComputePipelineState GetUnalignedBufferCopyPipeline() { lock (_unalignedBufferCopyPipelineLock) { if (_unalignedBufferCopyPipeline.IsNull) { MTLComputePipelineDescriptor descriptor = MTLUtil.AllocInit <MTLComputePipelineDescriptor>( nameof(MTLComputePipelineDescriptor)); MTLPipelineBufferDescriptor buffer0 = descriptor.buffers[0]; buffer0.mutability = MTLMutability.Mutable; MTLPipelineBufferDescriptor buffer1 = descriptor.buffers[1]; buffer0.mutability = MTLMutability.Mutable; Debug.Assert(_unalignedBufferCopyShader == null); string name = MetalFeatures.IsMacOS ? UnalignedBufferCopyPipelineMacOSName : UnalignedBufferCopyPipelineiOSName; using (Stream resourceStream = typeof(MTLGraphicsDevice).Assembly.GetManifestResourceStream(name)) { byte[] data = new byte[resourceStream.Length]; using (MemoryStream ms = new MemoryStream(data)) { resourceStream.CopyTo(ms); ShaderDescription shaderDesc = new ShaderDescription(ShaderStages.Compute, data, "copy_bytes"); _unalignedBufferCopyShader = new MTLShader(ref shaderDesc, this); } } descriptor.computeFunction = _unalignedBufferCopyShader.Function; _unalignedBufferCopyPipeline = _device.newComputePipelineStateWithDescriptor(descriptor); ObjectiveCRuntime.release(descriptor.NativePtr); } return(_unalignedBufferCopyPipeline); } }
public unsafe MTLShader(ref ShaderDescription description, MTLGraphicsDevice gd) : base(description.Stage) { _device = gd; DispatchQueue queue = Dispatch.dispatch_get_global_queue(QualityOfServiceLevel.QOS_CLASS_USER_INTERACTIVE, 0); fixed(byte *shaderBytesPtr = description.ShaderBytes) { DispatchData dispatchData = Dispatch.dispatch_data_create( shaderBytesPtr, (UIntPtr)description.ShaderBytes.Length, queue, IntPtr.Zero); Library = gd.Device.newLibraryWithData(dispatchData); try { Function = Library.newFunctionWithName(description.EntryPoint); if (Function.NativePtr == IntPtr.Zero) { throw new VeldridException( $"Failed to create Metal {description.Stage} Shader. The given entry point \"{description.EntryPoint}\" was not found."); } } finally { Dispatch.dispatch_release(dispatchData.NativePtr); } } }
public Shader CreateShaderCompileFromSpirv(ShaderDescription shaderDescription) { var stage = shaderDescription.Stage; if (stage == ShaderStages.Geometry || stage == ShaderStages.None || stage == ShaderStages.TessellationControl || stage == ShaderStages.TessellationEvaluation) { throw new Yak2DException("Unable to compile SPIRV shader - unsupported shader stage", new ArgumentException()); } if (stage == ShaderStages.Compute) { return(RawFactory?.CreateFromSpirv(shaderDescription)); } var otherStage = stage == ShaderStages.Vertex ? ShaderStages.Fragment : ShaderStages.Vertex; var otherShaderDescription = new ShaderDescription { Debug = false, EntryPoint = "main", Stage = otherStage, ShaderBytes = GenerateValidUnusedShaderBytes(otherStage) }; var shaders = RawFactory?.CreateFromSpirv(stage == ShaderStages.Vertex ? shaderDescription : otherShaderDescription, stage == ShaderStages.Vertex ? otherShaderDescription : shaderDescription); return(shaders[stage == ShaderStages.Vertex ? 0 : 1]); }
public static ShaderDescription CreateZeroFillShader(GraphicsDevice gd) { byte[] zeroFillShaderBytes = Encoding.UTF8.GetBytes(comp_zerofill); ShaderDescription shaderDesc = new ShaderDescription(ShaderStages.Compute, zeroFillShaderBytes, "main"); return(shaderDesc); }
public D3D11Shader(Device device, ShaderDescription description) { switch (description.Stage) { case ShaderStages.Vertex: DeviceShader = new VertexShader(device, description.ShaderBytes); break; case ShaderStages.Geometry: DeviceShader = new GeometryShader(device, description.ShaderBytes); break; case ShaderStages.TessellationControl: DeviceShader = new HullShader(device, description.ShaderBytes); break; case ShaderStages.TessellationEvaluation: DeviceShader = new DomainShader(device, description.ShaderBytes); break; case ShaderStages.Fragment: DeviceShader = new PixelShader(device, description.ShaderBytes); break; default: throw Illegal.Value <ShaderStages>(); } Bytecode = description.ShaderBytes; }
public static string ShaderFileToSourceCode(string fileName, ResourceFactory resourceFactory) { var dir = Path.GetDirectoryName(fileName); var shaderCode = File.ReadAllText(fileName); string GetIncludeCode(string includeName) { var includeFileName = Path.Combine(dir, includeName); var includeCode = File.ReadAllText(includeFileName); try { var conformalIncludeCode = GlslTools.MakeConformal(includeCode); var fragmentShaderDesc = new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(conformalIncludeCode), "main"); using (resourceFactory.CreateShader(fragmentShaderDesc)) { return(includeCode); } } catch (VeldridException vex) { throw new ShaderIncludeException($"Error compiling include file '{includeName}'", vex); } } var expandedShaderCode = Transformation.ExpandIncludes(shaderCode, GetIncludeCode); return(GlslTools.MakeConformal(expandedShaderCode)); }
/// <summary> /// Creates a compute shader from the given <see cref="ShaderDescription"/> containing SPIR-V bytecode or GLSL source /// code. /// </summary> /// <param name="factory">The <see cref="ResourceFactory"/> used to compile the translated shader code.</param> /// <param name="computeShaderDescription">The compute shader's description. /// <see cref="ShaderDescription.ShaderBytes"/> should contain SPIR-V bytecode or Vulkan-style GLSL source code which /// can be compiled to SPIR-V.</param> /// <param name="options">The <see cref="CrossCompileOptions"/> which will control the parameters used to translate the /// shaders from SPIR-V to the target language.</param> /// <returns>The compiled compute <see cref="Shader"/>.</returns> public static Shader CreateFromSpirv( this ResourceFactory factory, ShaderDescription computeShaderDescription, CrossCompileOptions options) { GraphicsBackend backend = factory.BackendType; if (backend == GraphicsBackend.Vulkan) { computeShaderDescription.ShaderBytes = EnsureSpirv(computeShaderDescription); return(factory.CreateShader(ref computeShaderDescription)); } CrossCompileTarget target = GetCompilationTarget(factory.BackendType); ComputeCompilationResult compilationResult = SpirvCompilation.CompileCompute( computeShaderDescription.ShaderBytes, target, options); string computeEntryPoint = (backend == GraphicsBackend.Metal && computeShaderDescription.EntryPoint == "main") ? "main0" : computeShaderDescription.EntryPoint; byte[] computeBytes = GetBytes(backend, compilationResult.ComputeShader); return(factory.CreateShader(new ShaderDescription( computeShaderDescription.Stage, computeBytes, computeEntryPoint))); }
protected override Shader CreateShaderCore(ref ShaderDescription description) { StagingBlock stagingBlock = _pool.Stage(description.ShaderBytes); OpenGLShader shader = new OpenGLShader(_gd, description.Stage, stagingBlock, description.EntryPoint); _gd.EnsureResourceInitialized(shader); return(shader); }
private Texture2DShader() { var vsBytes = ShaderTools.LoadBytecode(GraphicsBackend.Vulkan, "BasicTextureShader", ShaderStages.Vertex); var fsBytes = ShaderTools.LoadBytecode(GraphicsBackend.Vulkan, "BasicTextureShader", ShaderStages.Fragment); VertexShaderDescription = new ShaderDescription(ShaderStages.Vertex, vsBytes, "main", true); FragmentShaderDescription = new ShaderDescription(ShaderStages.Fragment, fsBytes, "main", true); }
private Vertex2Color4Shader() { var vsBytes = ShaderTools.LoadBytecode(GraphicsBackend.Vulkan, "Vertex2Color4", ShaderStages.Vertex); var fsBytes = ShaderTools.LoadBytecode(GraphicsBackend.Vulkan, "Vertex2Color4", ShaderStages.Fragment); VertexShaderDescription = new ShaderDescription(ShaderStages.Vertex, vsBytes, "main", true); FragmentShaderDescription = new ShaderDescription(ShaderStages.Fragment, fsBytes, "main", true); }
public (Shader vertex, Shader fragment) CreateShaders(ResourceFactory factory) { var vertexDesc = new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexShader), "main"); var fragmentDesc = new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragmentShader), "main"); var shaders = factory.CreateFromSpirv(vertexDesc, fragmentDesc); return(shaders[0], shaders[1]); }
public MIDIPatternIO(GraphicsDevice gd, ImGuiView view, Func <Vector2> computeSize, MIDIPatternConnect pattern) : base(gd, view, computeSize) { Buffers = new BufferList <VertexPositionColor> [257]; // first buffer for general purpose, others for keys for (int i = 0; i < 257; i++) { Buffers[i] = dispose.Add(new BufferList <VertexPositionColor>(gd, 6 * 2048 * 16, new[] { 0, 3, 2, 0, 2, 1 })); } PatternHandler = pattern; CurrentInteraction = new MIDIPatternInteractionIdle(PatternHandler); ProjMatrix = Factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); dispose.Add(ProjMatrix); VertexLayoutDescription vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4)); Layout = Factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("ProjectionMatrixBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex))); dispose.Add(Layout); ShaderDescription vertexShaderDesc = new ShaderDescription( ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"); ShaderDescription fragmentShaderDesc = new ShaderDescription( ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main"); Shaders = dispose.AddArray(Factory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc)); var pipelineDescription = new GraphicsPipelineDescription(); pipelineDescription.BlendState = BlendStateDescription.SingleAlphaBlend; pipelineDescription.DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual); pipelineDescription.RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Front, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false); pipelineDescription.PrimitiveTopology = PrimitiveTopology.TriangleList; pipelineDescription.ResourceLayouts = new ResourceLayout[] { Layout }; pipelineDescription.ShaderSet = new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { vertexLayout }, shaders: Shaders); pipelineDescription.Outputs = Canvas.FrameBuffer.OutputDescription; Pipeline = Factory.CreateGraphicsPipeline(pipelineDescription); MainResourceSet = Factory.CreateResourceSet(new ResourceSetDescription(Layout, ProjMatrix)); }
public unsafe MTLShader(ref ShaderDescription description, MTLGraphicsDevice gd) : base(description.Stage) { _device = gd; if (description.ShaderBytes.Length > 4 && description.ShaderBytes[0] == 0x4d && description.ShaderBytes[1] == 0x54 && description.ShaderBytes[2] == 0x4c && description.ShaderBytes[3] == 0x42) { DispatchQueue queue = Dispatch.dispatch_get_global_queue(QualityOfServiceLevel.QOS_CLASS_USER_INTERACTIVE, 0); fixed(byte *shaderBytesPtr = description.ShaderBytes) { DispatchData dispatchData = Dispatch.dispatch_data_create( shaderBytesPtr, (UIntPtr)description.ShaderBytes.Length, queue, IntPtr.Zero); try { Library = gd.Device.newLibraryWithData(dispatchData); } finally { Dispatch.dispatch_release(dispatchData.NativePtr); } } } else { string source = Encoding.UTF8.GetString(description.ShaderBytes); MTLCompileOptions compileOptions = MTLCompileOptions.New(); Library = gd.Device.newLibraryWithSource(source, compileOptions); ObjectiveCRuntime.release(compileOptions); } Function = Library.newFunctionWithName(description.EntryPoint); if (Function.NativePtr == IntPtr.Zero) { throw new VeldridException( $"Failed to create Metal {description.Stage} Shader. The given entry point \"{description.EntryPoint}\" was not found."); } if (Function.functionConstantsDictionary.count != UIntPtr.Zero) { // Need to create specialized MTLFunction. ObjectiveCRuntime.release(Function.NativePtr); MTLFunctionConstantValues constantValues = MTLFunctionConstantValues.New(); Function = Library.newFunctionWithNameConstantValues(description.EntryPoint, constantValues); ObjectiveCRuntime.release(constantValues.NativePtr); Debug.Assert(Function.NativePtr != IntPtr.Zero, "Failed to create specialized MTLFunction"); } }
private Shader[] CreateShaders(string vertexCode, string fragmentCode) { ShaderDescription vertexShaderDesc = CreateShaderDescription(vertexCode, ShaderStages.Vertex); ShaderDescription fragmentShaderDesc = CreateShaderDescription(fragmentCode, ShaderStages.Fragment); return(new Shader[] { factory.CreateShader(ref vertexShaderDesc), factory.CreateShader(ref fragmentShaderDesc) }); }
/// <summary> /// Registers the shader. /// </summary> /// <param name="description">The description.</param> /// <returns></returns> public ShaderBase RegisterShader(ShaderDescription description) { if (description == null) { return(null); } return(shaderPools[description.ShaderType.ToIndex()].TryCreateOrGet(description.ByteCode, description, out var shader) ? shader : null); }
public static Shader LoadShader(string name, ShaderStages stage, params string[] include) { string extension = GraphicsExtension(); string entryPoint = ""; switch (stage) { case ShaderStages.Vertex: entryPoint = "VS"; break; case ShaderStages.Fragment: entryPoint = "FS"; break; case ShaderStages.Compute: entryPoint = "main"; break; } string path = Path.Combine(AppContext.BaseDirectory, "Shaders", $"{name}.{extension}"); //Debug.WriteLine("Loading shader: " + path); List <byte> shaderBytes = new List <byte>(); foreach (string inc in include) { string incpath = Path.Combine(AppContext.BaseDirectory, "Shaders", $"{name}.{extension}"); shaderBytes.AddRange(File.ReadAllBytes(incpath)); } shaderBytes.AddRange(File.ReadAllBytes(path)); var desc = new ShaderDescription(stage, shaderBytes.ToArray(), entryPoint, DebugMode); return(factory.CreateShader(desc)); string GraphicsExtension() { switch (device.BackendType) { case GraphicsBackend.Direct3D11: return("hlsl"); case GraphicsBackend.Vulkan: return("spv"); case GraphicsBackend.OpenGL: return("glsl"); case GraphicsBackend.Metal: return("metallib"); default: throw new InvalidOperationException(); } } }
private Vertex2Color4Shader() { var vertexShaderBytes = ShaderTools.LoadShaderBytes(DisplaySettings.Instance.GraphicsBackend, typeof(Vertex2Color4Shader).Assembly, "Vertex2Color4ShaderSource", ShaderStages.Vertex); var fragmentShaderBytes = ShaderTools.LoadShaderBytes(DisplaySettings.Instance.GraphicsBackend, typeof(Vertex2Color4Shader).Assembly, "Vertex2Color4ShaderSource", ShaderStages.Fragment); VertexShaderDescription = new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes, "VS"); FragmentShaderDescription = new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes, "FS"); }
private Texture2DShader() { var vertexShaderBytes = ShaderTools.LoadShaderBytes(DisplaySettings.Instance.GraphicsBackend, typeof(TextNode).Assembly, "BasicTextureShader", ShaderStages.Vertex); var fragmentShaderBytes = ShaderTools.LoadShaderBytes(DisplaySettings.Instance.GraphicsBackend, typeof(TextNode).Assembly, "BasicTextureShader", ShaderStages.Fragment); VertexShaderDescription = new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes, "VS"); FragmentShaderDescription = new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes, "FS"); }
public ParsedShader(ShaderStages stage, byte[] shaderBytes) { #if DEBUG const bool debug = true; #else const bool debug = false; #endif Description = new ShaderDescription(stage, shaderBytes, "main", debug); var shaderText = Encoding.UTF8.GetString(shaderBytes); Attributes = ParseAttributes(shaderText); Resources = ParseShaderResources(stage, shaderText); }
public static Shader[] LoadSet(GraphicsDevice gd, ResourceFactory factory, string name) { ShaderDescription vsDesc = new ShaderDescription( ShaderStages.Vertex, LoadBytes(name, ShaderStages.Vertex), "main"); ShaderDescription fsDesc = new ShaderDescription( ShaderStages.Fragment, LoadBytes(name, ShaderStages.Fragment), "main"); CrossCompileOptions options = GetCompileOptions(gd); return(factory.CreateFromSpirv(vsDesc, fsDesc, options)); }
/// <summary> /// Creates a vertex and fragment shader pair from the given <see cref="ShaderDescription"/> pair containing SPIR-V /// bytecode or GLSL source code. /// </summary> /// <param name="factory">The <see cref="ResourceFactory"/> used to compile the translated shader code.</param> /// <param name="vertexShaderDescription">The vertex shader's description. <see cref="ShaderDescription.ShaderBytes"/> /// should contain SPIR-V bytecode or Vulkan-style GLSL source code which can be compiled to SPIR-V.</param> /// <param name="fragmentShaderDescription">The fragment shader's description. /// <see cref="ShaderDescription.ShaderBytes"/> should contain SPIR-V bytecode or Vulkan-style GLSL source code which /// can be compiled to SPIR-V.</param> /// <param name="options">The <see cref="CrossCompileOptions"/> which will control the parameters used to translate the /// shaders from SPIR-V to the target language.</param> /// <returns>A two-element array, containing the vertex shader (element 0) and the fragment shader (element 1).</returns> public static Shader[] CreateFromSpirv( this ResourceFactory factory, ShaderDescription vertexShaderDescription, ShaderDescription fragmentShaderDescription, CrossCompileOptions options) { GraphicsBackend backend = factory.BackendType; if (backend == GraphicsBackend.Vulkan) { vertexShaderDescription.ShaderBytes = EnsureSpirv(vertexShaderDescription); fragmentShaderDescription.ShaderBytes = EnsureSpirv(fragmentShaderDescription); return(new Shader[] { factory.CreateShader(ref vertexShaderDescription), factory.CreateShader(ref fragmentShaderDescription) }); } CrossCompileTarget target = GetCompilationTarget(factory.BackendType); VertexFragmentCompilationResult compilationResult = SpirvCompilation.CompileVertexFragment( vertexShaderDescription.ShaderBytes, fragmentShaderDescription.ShaderBytes, target, options); string vertexEntryPoint = (backend == GraphicsBackend.Metal && vertexShaderDescription.EntryPoint == "main") ? "main0" : vertexShaderDescription.EntryPoint; byte[] vertexBytes = GetBytes(backend, compilationResult.VertexShader); Shader vertexShader = factory.CreateShader(new ShaderDescription( vertexShaderDescription.Stage, vertexBytes, vertexEntryPoint)); string fragmentEntryPoint = (backend == GraphicsBackend.Metal && fragmentShaderDescription.EntryPoint == "main") ? "main0" : fragmentShaderDescription.EntryPoint; byte[] fragmentBytes = GetBytes(backend, compilationResult.FragmentShader); Shader fragmentShader = factory.CreateShader(new ShaderDescription( fragmentShaderDescription.Stage, fragmentBytes, fragmentEntryPoint)); return(new Shader[] { vertexShader, fragmentShader }); }
public VkShader(VkGraphicsDevice gd, ref ShaderDescription description) { _gd = gd; VkShaderModuleCreateInfo shaderModuleCI = VkShaderModuleCreateInfo.New(); fixed(byte *codePtr = description.ShaderBytes) { shaderModuleCI.codeSize = (UIntPtr)description.ShaderBytes.Length; shaderModuleCI.pCode = (uint *)codePtr; VkResult result = vkCreateShaderModule(gd.Device, ref shaderModuleCI, null, out _shaderModule); CheckResult(result); } }
private byte[] CompileCode(ShaderDescription description) { string profile; switch (description.Stage) { case ShaderStages.Vertex: profile = "vs_5_0"; break; case ShaderStages.Geometry: profile = "gs_5_0"; break; case ShaderStages.TessellationControl: profile = "hs_5_0"; break; case ShaderStages.TessellationEvaluation: profile = "ds_5_0"; break; case ShaderStages.Fragment: profile = "ps_5_0"; break; case ShaderStages.Compute: profile = "cs_5_0"; break; default: throw Illegal.Value <ShaderStages>(); } ShaderFlags flags = description.Debug ? ShaderFlags.Debug : ShaderFlags.OptimizationLevel3; CompilationResult result = ShaderBytecode.Compile( description.ShaderBytes, description.EntryPoint, profile, flags); if (result.ResultCode.Failure || !string.IsNullOrEmpty(result.Message)) { throw new VeldridException($"Failed to compile HLSL code: {result.Message}"); } return(result.Bytecode.Data); }