Beispiel #1
0
        private static DX11Effect Compile(string content, bool isfile, Include include, ShaderMacro[] defines)
        {
            DX11Effect shader = new DX11Effect();

            string errors;

            try
            {
                ShaderFlags flags = ShaderFlags.OptimizationLevel1;

                if (isfile)
                {
                    shader.ByteCode = ShaderBytecode.CompileFromFile(content, "fx_5_0", flags, EffectFlags.None, defines, include, out errors);
                }
                else
                {
                    shader.ByteCode = ShaderBytecode.Compile(content, "fx_5_0", flags, EffectFlags.None, defines, include, out errors);
                }

                //Compilation worked, but we can still have warning
                shader.IsCompiled   = true;
                shader.ErrorMessage = errors;

                shader.Preprocess();
            }
            catch (Exception ex)
            {
                shader.IsCompiled    = false;
                shader.ErrorMessage  = ex.Message;
                shader.DefaultEffect = null;
            }
            return(shader);
        }
        public static async Task <ShaderBytecode> CompileFromFileAsync(string hlslFile, string entryPoint, string profile, ShaderMacro[] defines = null)
        {
            if (!Path.IsPathRooted(hlslFile))
            {
                hlslFile = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, hlslFile);
            }

            CompilationResult result = null;

            await Task.Run(() =>
            {
                var shaderSource = SharpDX.IO.NativeFile.ReadAllText(hlslFile);

                // Compile the shader file
                ShaderFlags flags = ShaderFlags.None;
#if DEBUG
                flags |= ShaderFlags.Debug | ShaderFlags.SkipOptimization;
#endif
                var includeHandler = new HLSLFileIncludeHandler(Path.GetDirectoryName(hlslFile));
                result             = ShaderBytecode.Compile(shaderSource, entryPoint, profile, flags, EffectFlags.None, defines, includeHandler, Path.GetFileName(hlslFile));

                if (!String.IsNullOrEmpty(result.Message))
                {
                    throw new CompilationException(result.ResultCode, result.Message);
                }
            });

            return(result);
        }
Beispiel #3
0
        public static Shader <T> CreateFromString(RenderManager manager, string shaderSource)
        {
            var device = manager.Device;

            Shader <T> ret = new Shader <T>();

            ret.buffer = default(T);

            ret.device = device;

            using (var vertexShaderByteCode = ShaderBytecode.Compile(shaderSource, "VS", "vs_4_0"))
            {
                ret.vertexShader = new VertexShader(device, vertexShaderByteCode);
                ret.signature    = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            }
            using (var geometryShaderByteCode = ShaderBytecode.Compile(shaderSource, "GS", "gs_4_0"))
            {
                ret.geometryShader = new GeometryShader(device, geometryShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.Compile(shaderSource, "PS", "ps_4_0"))
            {
                ret.pixelShader = new PixelShader(device, pixelShaderByteCode);
            }

            ret.constantBuffer = new Buffer(device, Utilities.SizeOf <T>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            return(ret);
        }
        private void CreatePixelShader()
        {
            var byteCode = ShaderBytecode.Compile(Encoding.UTF8.GetBytes(DX9Code), "PS",
                                                  "ps_2_0", SlimD3D9.ShaderFlags.None);

            pixelShader = new PixelShader(NativeDevice, byteCode);
        }
Beispiel #5
0
            private byte[] CompileShaderDef(string definition, string source, string fileName = null)
            {
#if DEBUG
                const ShaderFlags shaderFlags = ShaderFlags.Debug;
#else
                const ShaderFlags shaderFlags = ShaderFlags.OptimizationLevel3;
#endif

                var macroArray = Defines.Select(x => new ShaderMacro(x.Text, 1)).ToArray();

                using (var includer = new Includer())
                {
                    var split  = definition.Split(' ');
                    var result = ShaderBytecode.Compile(source, split[0], split[1], shaderFlags, EffectFlags.None,
                                                        macroArray, includer, fileName);

                    /*
                     * foreach (var msg in result.Message.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                     * {
                     *  Renderer.Logger.Info(msg);
                     *  Debug.WriteLine(msg);
                     * }
                     */

                    if (result.Bytecode == null)
                    {
                        throw new Exception($"Could not compile shader \"{Name}\". \n\n{result.Message}");
                    }

                    return(result.Bytecode);
                }
            }
Beispiel #6
0
        /// <summary>
        /// Compile the HLSL file using the provided <paramref name="entryPoint"/>, shader <paramref name="profile"/> and optionally conditional <paramref name="defines"/>
        /// </summary>
        /// <param name="hlslFile">Absolute path to HLSL file, or path relative to application installation location</param>
        /// <param name="entryPoint">Shader function name e.g. VSMain</param>
        /// <param name="profile">Shader profile, e.g. vs_5_0</param>
        /// <param name="defines">An optional list of conditional defines.</param>
        /// <returns>The compiled ShaderBytecode</returns>
        /// <exception cref="CompilationException">Thrown if the compilation failed</exception>
        public static ShaderBytecode CompileFromFile(string hlslFile, string entryPoint, string profile, ShaderMacro[] defines = null)
        {
            if (!Path.IsPathRooted(hlslFile))
            {
                hlslFile = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), hlslFile);
            }
            var shaderSource         = SharpDX.IO.NativeFile.ReadAllText(hlslFile);
            CompilationResult result = null;

            // Compile the shader file
            ShaderFlags flags = ShaderFlags.None;

#if DEBUG
            flags |= ShaderFlags.Debug | ShaderFlags.SkipOptimization;
#endif
            var includeHandler = new HLSLFileIncludeHandler(Path.GetDirectoryName(hlslFile));
            result = ShaderBytecode.Compile(shaderSource, entryPoint, profile, flags, EffectFlags.None, defines, includeHandler, Path.GetFileName(hlslFile));

            if (result.ResultCode.Failure)
            {
                throw new CompilationException(result.ResultCode, result.Message);
            }

            return(result);
        }
Beispiel #7
0
        public static void DumpFloat(int value, StringBuilder sb)
        {
            var floatValue = ToFloat(value);

            if (float.IsNaN(floatValue))
            {
                return;
            }
            string shaderCode = string.Format(@"
				float4 main(): sv_target {{ return asfloat({0}); }}"                ,
                                              value);
            var compiledShader = ShaderBytecode.Compile(shaderCode, "main", "ps_5_0");
            var shaderBytecode = compiledShader.Bytecode;
            var disassembly    = shaderBytecode.Disassemble();
            var bytecode       = BytecodeContainer.Parse(shaderBytecode);
            var number         = bytecode.Shader.InstructionTokens.First().Operands[1].ImmediateValues;

            StringAssert.Contains("Generated by Microsoft (R) HLSL Shader Compiler 10.1", disassembly);
            var expectedFloat = Regex.Match(disassembly, @"l\((.*?),").Groups[1].Value;
            var actualFloat   = FormatFloat(floatValue);
            var fullFloat     = DoubleConverter.ToExactString(floatValue, -1);
            var correct       = expectedFloat == actualFloat;

            if (value != number.Int0)
            {
                return;
            }
            sb.AppendLine(string.Format("{0}\t{1, 50}\t{2, 50}\t{3}\t{4}",
                                        correct, expectedFloat, actualFloat, fullFloat, value));
        }
        //String shader2 = "sampler2D g_samSrcColor;float4 MyShader( float4 Tex : TEXCOORD0 ) : COLOR0{float4 Color;Color = tex2D( g_samSrcColor, Tex.xy);return Color;}";
        private void DrawSprite(SlimDX.Direct3D10.Device device)
        {
            if (_sprite == null)
            {
                _sprite   = new Sprite(device, 1);
                _sTexture = Texture2D.FromFile(
                    device,
                    @"C:\temp\privet.png");

                _srv   = new ShaderResourceView(device, _sTexture);
                _si[0] = new SpriteInstance(_srv, new Vector2(0, 0), new Vector2(1, 1));
                //_sprite.ProjectionTransform = Matrix.OrthoOffCenterLH(0, 800, -600, 0, -10, 10);
                _sprite.ViewTransform = Matrix.Transformation2D(Vector2.Zero, 0.0f, new Vector2(2.0f, 2.0f), Vector2.Zero, 0.0f, Vector2.Zero);


                using (var bytecode = ShaderBytecode.Compile(shader, "PShader", "ps_4_0", ShaderFlags.EnableBackwardsCompatibility, EffectFlags.None))
                    pixelShader = new PixelShader(device, bytecode);
            }
            device.PixelShader.Set(pixelShader);
            //if ((DateTime.Now - _lastSprite).TotalMilliseconds > 0)
            //{
            _sprite.Begin(SpriteFlags.None);
            _sprite.DrawImmediate(_si);
            _sprite.End();
            _lastSprite = DateTime.Now;
            //}
        }
Beispiel #9
0
        public static void TestFloat(int value)
        {
            var floatValue = ToFloat(value);

            if (float.IsNaN(floatValue))
            {
                return;
            }
            string shaderCode = string.Format(@"
				float4 main(): sv_target {{ return asfloat({0}); }}"                ,
                                              value);
            var compiledShader = ShaderBytecode.Compile(shaderCode, "main", "ps_5_0");
            var shaderBytecode = compiledShader.Bytecode;
            var disassembly    = shaderBytecode.Disassemble();
            var bytecode       = BytecodeContainer.Parse(shaderBytecode);
            var number         = bytecode.Shader.InstructionTokens.First().Operands[1].ImmediateValues;

            StringAssert.Contains("Generated by Microsoft (R) HLSL Shader Compiler 10.1", disassembly);
            var expectedFloat = Regex.Match(disassembly, @"l\((.*?),").Groups[1].Value;
            var actualFloat   = FormatFloat(floatValue);

            if (value != number.Int0)
            {
                Directory.CreateDirectory(OutputDir);
                File.WriteAllText($"{OutputDir}/FloatParserDissassembly.asm", disassembly);
                return;
            }
            Assert.AreEqual(value, number.Int0, "Parsed binary represention doesn't match input");
            Assert.AreEqual(expectedFloat, actualFloat, $"String format doesn't match expected for {value} {DoubleConverter.ToExactString(floatValue, -1)}");
        }
Beispiel #10
0
 private string GetBytecodeShader(string shaderSource)
 {
     using (var byteCode = ShaderBytecode.Compile(VS, "main", "vs_4_0", ShaderFlags.OptimizationLevel3))
     {
         return(string.Join(",", byteCode.Bytecode.Data.Select(x => $"{x.ToString("X02")}")));
     }
 }
Beispiel #11
0
        private static DX11Effect Compile(string content, bool isfile, Include include, ShaderMacro[] defines)
        {
            DX11Effect  shader = new DX11Effect();
            ShaderFlags flags  = ShaderFlags.OptimizationLevel1;// | ShaderFlags.PackMatrixRowMajor;

            try
            {
                if (isfile)
                {
                    shader.CompilationResult = ShaderBytecode.CompileFromFile(content, "fx_5_0", flags, EffectFlags.None, defines, include);
                }
                else
                {
                    shader.CompilationResult = ShaderBytecode.Compile(content, "fx_5_0", flags, EffectFlags.None, defines, include);
                }

                if (shader.IsCompiled)
                {
                    shader.DefaultEffect = new Effect(NullDevice.Device, shader.CompilationResult.Bytecode);
                }
            }
            catch (Exception ex)
            {
                shader.CompilationResult = new CompilationResult(null, Result.Fail, ex.Message);
            }
            return(shader);
        }
Beispiel #12
0
        internal void RegisterEffect(string shaderEffectString, string[] techniqueNames, ShaderFlags sFlags = ShaderFlags.None, EffectFlags eFlags = EffectFlags.None)
        {
#if DEBUG
            sFlags |= ShaderFlags.Debug;
            eFlags |= EffectFlags.None;
#endif

            var preprocess = ShaderBytecode.Preprocess(shaderEffectString, null, new IncludeHandler());
            var hashCode   = preprocess.GetHashCode();
            if (!File.Exists(hashCode.ToString()))
            {
                try
                {
                    var shaderBytes = ShaderBytecode.Compile(preprocess, "fx_5_0", sFlags, eFlags);
                    shaderBytes.Bytecode.Save(hashCode.ToString());
                    this.RegisterEffect(shaderBytes.Bytecode, techniqueNames);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(string.Format("Error compiling effect: {0}", ex.Message), "Error");
                }
            }
            else
            {
                var shaderBytes = ShaderBytecode.FromFile(hashCode.ToString());
                this.RegisterEffect(shaderBytes, techniqueNames);
            }
        }
Beispiel #13
0
        protected virtual void InitializeShader()
        {
            try
            {
                string shaderSource = EmbeddedResourceReader.ReadTextResource("MacomberMapClient.Effects.VertexColorShader.fx", Assembly.GetExecutingAssembly());
                // load our default shader

                var vertexShaderByteCode = ShaderBytecode.Compile(shaderSource, "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                _vertexShader = new VertexShader(_surface.Device, vertexShaderByteCode);

                var pixelShaderByteCode = ShaderBytecode.Compile(shaderSource, "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None);
                _pixelShader = new PixelShader(_surface.Device, pixelShaderByteCode);

                // Layout from VertexShader input signature
                _inputLayout = new InputLayout(
                    _surface.Device,
                    ShaderSignature.GetInputSignature(vertexShaderByteCode),
                    new[]
                {
                    new SharpDX.Direct3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new SharpDX.Direct3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                    new SharpDX.Direct3D11.InputElement("NORMAL", 0, Format.R32G32B32_Float, 32, 0),
                });

                // Instantiate Vertex buiffer from vertex data
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #14
0
            /// <summary>
            /// Using Project Resources and gets all byte[] data
            /// </summary>
            public static void CompileShaders()
            {
                // v5
                //string vertexProfile    = "vs_5_0";
                //string pixelProfile     = "ps_5_0";

                // v4
                string vertexProfile = "vs_4_0_level_9_1";
                string pixelProfile  = "ps_4_0_level_9_1";

                string shadersCode = "";

                System.Resources.ResourceSet rsrcSet = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
                foreach (System.Collections.DictionaryEntry entry in rsrcSet)
                {
                    if (entry.Value is byte[])
                    {
                        byte[] byteCode = ShaderBytecode.Compile((byte[])rsrcSet.GetObject(entry.Key.ToString()), "main", entry.Key.ToString() == "VertexShader" ? pixelProfile : vertexProfile, ShaderFlags.Debug);

                        shadersCode += $"{{ \"{entry.Key.ToString()}\", new byte[] {{ {byteCode[0]}";
                        for (int i = 1; i < byteCode.Length; i++)
                        {
                            shadersCode += $",{byteCode[i]}";
                        }
                        shadersCode += $" }}}},\r\n";
                    }
                }

                File.WriteAllText(@"Shaders.cs", shadersCode);
            }
Beispiel #15
0
        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);
        }
Beispiel #16
0
 static public Effect InitEffect(Device device)
 {
     using (ShaderBytecode shaderByteCode = ShaderBytecode.Compile(
                Properties.Resources.myeffect, "fx_5_0", ShaderFlags.None, EffectFlags.None))
     {
         return(new Effect(device, shaderByteCode));
     }
 }
        private void CreateVertexShader()
        {
            byte[] shaderCodeInBytes = Encoding.UTF8.GetBytes(DX9Code);
            var    byteCode          = ShaderBytecode.Compile(shaderCodeInBytes, "VS",
                                                              "vs_2_0", SlimD3D9.ShaderFlags.None);

            vertexShader = new VertexShader(NativeDevice, byteCode);
        }
Beispiel #18
0
        ShaderBytecode LoadShader(string name, ShaderFlags flags)
        {
            Assembly     assembly     = Assembly.GetExecutingAssembly();
            StreamReader reader       = new StreamReader(assembly.GetManifestResourceStream("DemoFramework.SharpDX11." + name));
            string       shaderSource = reader.ReadToEnd();

            return(ShaderBytecode.Compile(shaderSource, "fx_5_0", flags, EffectFlags.None));
        }
        static ShaderBytecode LoadShader(string name, ShaderFlags flags)
        {
            Assembly     assembly     = Assembly.GetExecutingAssembly();
            StreamReader reader       = new StreamReader(assembly.GetManifestResourceStream(string.Format("{0}.{1}", assembly.GetName().Name, name)));
            string       shaderSource = reader.ReadToEnd();

            return(ShaderBytecode.Compile(shaderSource, "fx_4_0", flags, EffectFlags.None));
        }
Beispiel #20
0
        /// <summary>
        /// Register an effect for a set of RenderTechniques.
        /// </summary>
        /// <param name="shaderEffectString">A string representing the shader code.</param>
        /// <param name="techniques">A set of RenderTechnique objects for which to associate the Effect.</param>
        /// <param name="sFlags"></param>
        /// <param name="eFlags"></param>
        public void RegisterEffect(string shaderEffectString, RenderTechnique[] techniques, ShaderFlags sFlags = ShaderFlags.None, EffectFlags eFlags = EffectFlags.None)
        {
#if PRECOMPILED_SHADERS
            try
            {
                var shaderBytes = Techniques.TechniquesSourceDict[techniques[0]];
                this.RegisterEffect(shaderBytes, techniques);
            }
            catch (Exception ex)
            {
                //System.Windows.MessageBox.Show(string.Format("Error registering effect: {0}", ex.Message), "Error");
                Debug.WriteLine(string.Format("Error registering effect: {0}", ex.Message), "Error");
                throw;
            }
#else
#if DEBUG
            sFlags |= ShaderFlags.Debug;
            eFlags |= EffectFlags.None;
#else
            sFlags |= ShaderFlags.OptimizationLevel3;
            eFlags |= EffectFlags.None;
#endif

            var preposessMacros = new List <ShaderMacro>();

#if DEFERRED
#if DEFERRED_MSAA
            preposessMacros.Add(new ShaderMacro("DEFERRED_MSAA", true));
#endif

#if SSAO
            preposessMacros.Add(new ShaderMacro("SSAO", true));
#endif
#endif
            var preprocess = ShaderBytecode.Preprocess(shaderEffectString, preposessMacros.ToArray(), new IncludeHandler());
            var hashCode   = preprocess.GetHashCode();
            if (!File.Exists(hashCode.ToString()))
            {
                try
                {
                    var shaderBytes = ShaderBytecode.Compile(preprocess, "fx_5_0", sFlags, eFlags);
                    shaderBytes.Bytecode.Save(hashCode.ToString());
                    this.RegisterEffect(shaderBytes.Bytecode, techniques);
                }
                catch (Exception ex)
                {
                    //System.Windows.MessageBox.Show(string.Format("Error compiling effect: {0}", ex.Message), "Error");
                    Debug.WriteLine(string.Format("Error compiling effect: {0}", ex.Message), "Error");
                    throw;
                }
            }
            else
            {
                var shaderBytes = ShaderBytecode.FromFile(hashCode.ToString());
                this.RegisterEffect(shaderBytes, techniques);
            }
#endif
        }
Beispiel #21
0
 internal static ShaderBytecode Compile(byte[] data, string name = "")
 {
     try {
         return(ShaderBytecode.Compile(data, "Render", "fx_5_0", ShaderFlags.None, EffectFlags.None));
     } catch (System.Exception e) {
         System.Windows.Forms.MessageBox.Show("Shader " + (name ?? "?") + " compilation failed:\n\n" + e.Message);
         throw;
     }
 }
Beispiel #22
0
        public ProgressVisualizer(RenderForm form, SharpDX.Direct3D11.Device device, SwapChain swapChain)
        {
            _form      = form;
            _device    = device;
            _swapChain = swapChain;

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0);

            _renderView = new RenderTargetView(_device, backBuffer);

            var shaderCode = @"
struct VS_IN
{
	float4 pos : POSITION;
	float4 col : COLOR;
};

struct PS_IN
{
	float4 pos : SV_POSITION;
	float4 col : COLOR;
};

PS_IN VS( VS_IN input )
{
	PS_IN output = (PS_IN)0;
	
	output.pos = input.pos;
	output.col = input.col;
	
	return output;
}

float4 PS( PS_IN input ) : SV_Target
{
	return input.col;
}

technique10 Render
{
	pass P0
	{
		SetGeometryShader( 0 );
		SetVertexShader( CompileShader( vs_4_0, VS() ) );
		SetPixelShader( CompileShader( ps_4_0, PS() ) );
	}
}";

            using (var bytecode = ShaderBytecode.Compile(shaderCode, "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null))
                _effect = new Effect(D3DDevice.Device, bytecode);
            _technique = _effect.GetTechniqueByIndex(0);
            _pass      = _technique.GetPassByIndex(0);
            _layout    = new InputLayout(_device, _pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });
        }
Beispiel #23
0
        public EffectData Rebuild()
        {
            // assemble the source text
            var source = GetSource();

            // compile the library
            var compilationResult = ShaderBytecode.Compile(source, "lib_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None);

            // if compilation failed - try to reset to the initial data and rebuild again
            if (compilationResult.HasErrors)
            {
                if (_isRebuildingAfterReset)
                {
                    // something is messed up, we alraedy tried to rebuild once
                    throw new InvalidOperationException();
                }

                try
                {
                    _isRebuildingAfterReset = true;

                    // reset the data
                    _data.Reset();
                    // rebuild
                    return(Rebuild());
                }
                finally
                {
                    _isRebuildingAfterReset = false;
                }
            }

            var bytecode = compilationResult.Bytecode;

            // create the shader library module
            var shaderLibrary = new Module(bytecode);
            // create the shader library module instance
            var shaderLibraryInstance = new ModuleInstance(shaderLibrary);

            // mark the implicit constant buffer (for single parameter) as bindable
            shaderLibraryInstance.BindConstantBuffer(0, 0, 0);

            // assemble vertex shader
            var vertexShaderBytecode = AssembleVertexShader(shaderLibrary, shaderLibraryInstance);
            // assemble pixel shader
            var pixelShaderBytecode = AssemblePixelShader(shaderLibrary, shaderLibraryInstance);

            try
            {
                // assemble the effect data from the bytecodes
                return(_effectCompiler.Compile(vertexShaderBytecode, pixelShaderBytecode));
            }
            finally
            {
                _data.IsDirty = false;
            }
        }
Beispiel #24
0
 public Shader(Device device, string vsEntry, string psEntry, InputElement[] inputElems)
 {
     inputElements        = inputElems;
     vertexShaderByteCode = ShaderBytecode.Compile(Properties.Resources.Shaders, vsEntry, "vs_5_0", ShaderFlags.Debug | ShaderFlags.OptimizationLevel0);
     pixelShaderByteCode  = ShaderBytecode.Compile(Properties.Resources.Shaders, psEntry, "ps_5_0", ShaderFlags.Debug | ShaderFlags.OptimizationLevel0);
     vertexShader         = new VertexShader(device, vertexShaderByteCode);
     pixelShader          = new PixelShader(device, pixelShaderByteCode);
     inputLayout          = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
 }
Beispiel #25
0
        internal ShaderBytecode GetShaderByteCodeFromResource(string shaderBlob, string entryPoint, string profile)
        {
            ShaderFlags flags = ShaderFlags.None;

#if DEBUG
            flags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
#endif
            return(ShaderBytecode.Compile(shaderBlob, entryPoint, profile, flags));
        }
Beispiel #26
0
        public void RecompileShaders(string relPath)
        {
            string file = $"{ShaderDirectory}/{relPath}";
            // Arrange.
            var relDir = Path.GetDirectoryName(relPath);

            Directory.CreateDirectory($"{OutputDir}/{relDir}");
            var sourceName = GetSourceNameFromObject($"{ShaderDirectory}/{relPath}.o");

            if (ShaderDirectory != OutputDir)
            {
                File.Copy($"{ShaderDirectory}/{relDir}/{sourceName}", $"{OutputDir}/{relDir}/{sourceName}", true);
            }
            if (ShaderDirectory != OutputDir)
            {
                File.Copy($"{ShaderDirectory}/{relPath}.asm", $"{OutputDir}/{relPath}.asm", true);
            }

            var asmFileText = string.Join(Environment.NewLine,
                                          File.ReadAllLines(file + ".asm").Select(x => x.Trim()));

            // Act.
            var    binaryFileBytes = File.ReadAllBytes(file + ".o");
            var    shaderModel     = ShaderReader.ReadShader(binaryFileBytes);
            var    hlslWriter      = new HlslWriter(shaderModel);
            string decompiledHLSL  = "";

            using (var stream = new MemoryStream())
            {
                hlslWriter.Write(stream);
                stream.Position = 0;
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    decompiledHLSL = reader.ReadToEnd();
                }
            }
            File.WriteAllText($"{OutputDir}/{relPath}.d.hlsl", decompiledHLSL);

            using (var shaderBytecode = ShaderBytecode.FromStream(new MemoryStream(binaryFileBytes)))
            {
                var profile = shaderModel.Type == DX9Shader.ShaderType.Pixel ?
                              $"ps_{shaderModel.MajorVersion}_{shaderModel.MinorVersion}" :
                              $"vs_{shaderModel.MajorVersion}_{shaderModel.MinorVersion}";
                var compiledShader = ShaderBytecode.Compile(decompiledHLSL, "main", profile);
                var disassembly    = shaderBytecode.Disassemble();
                var redisassembly  = compiledShader.Bytecode.Disassemble();
                File.WriteAllText($"{OutputDir}/{relPath}.d1.asm", disassembly);
                File.WriteAllText($"{OutputDir}/{relPath}.d2.asm", redisassembly);

                // Assert.
                Warn.If(disassembly, Is.EqualTo(redisassembly));
            }

            // Assert.
            Assert.Pass();
        }
Beispiel #27
0
        CompilationResult Compile(IShaderViewModel shader, out List <ErrorModel> errors)
        {
            CompilationResult result = null;

            errorList = new List <ErrorModel>();
            try
            {
                IncludeHandler includeHandler = new IncludeHandler();
                result = ShaderBytecode.Compile(shader.SourceCode, shader.Name, shader.FeatureLevel.ToString().ToLowerInvariant(),
                                                FromShaderConfiguration(), EffectFlags.None, null, includeHandler);
                includeHandler.Dispose();

                // In case compilation information could be needed - i.e. number of instructions
                //using (ShaderReflection sReflection = new ShaderReflection(result.Bytecode))
                //    Log.Daedalus.Info(sReflection.ToString());

                if (!string.IsNullOrEmpty(result.Message))
                {
                    string[] warnings = result.Message.Split('\n');
                    foreach (string warning in warnings)
                    {
                        if (!string.IsNullOrEmpty(warning))
                        {
                            errorList.Add(new ErrorModel(shader.Name, warning));
                        }
                    }
                    errors = errorList;
                }
                else
                {
                    errors = null;
                }
                return(result);
            }
            catch (InvalidOperationException exIO)
            {
                Log.Daedalus.Error(exIO.ToString());
                errorList.Add(new ErrorModel(shader.Name, exIO.Message, false));
                errors = errorList;
                return(null);
            }
            catch (CompilationException exComp)
            {
                Log.Daedalus.Error(exComp.ToString());
                string[] errorMessages = exComp.Message.Split('\n');
                foreach (string error in errorMessages)
                {
                    if (!string.IsNullOrEmpty(error))
                    {
                        errorList.Add(new ErrorModel(shader.Name, error));
                    }
                }
                errors = errorList;
                return(null);
            }
        }
        public void WillReturnCorrectProfileVersionForVertexShader(string profile)
        {
            const string vertexShaderSourceCode = @"float4 vs() : SV_Position { return float4(0,0,0,0); }";

            var bytecode = ShaderBytecode.Compile(vertexShaderSourceCode, "vs", profile).Bytecode;

            var profileStruct = bytecode.GetVersion();

            Assert.AreEqual(profile, profileStruct.ToString());
        }
        public void WillReturnCorrectProfileVersionForPixelShader(string profile)
        {
            const string pixelShaderSourceCode = @"float4 ps() : SV_Target { return float4(0,0,0,0); }";

            var bytecode = ShaderBytecode.Compile(pixelShaderSourceCode, "ps", profile).Bytecode;

            var profileStruct = bytecode.GetVersion();

            Assert.AreEqual(profile, profileStruct.ToString());
        }
Beispiel #30
0
 public static CompilationResult CompileFromResource(string resourceName, string entryPoint, string profile, EffectFlags effectFlags = EffectFlags.None, string sourceFileName = "unknown")
 {
     using (Stream stream = Application.GetResourceStream(new Uri(resourceName)).Stream)
     {
         using (StreamReader reader = new StreamReader(stream))
         {
             return(ShaderBytecode.Compile(reader.ReadToEnd(), entryPoint, profile, shaderFlags, effectFlags, sourceFileName));
         }
     }
 }