/// <summary> /// Compute Shader /// </summary> /// <param name="device">Graphics device</param> /// <param name="filename">Path to uncompiled shaderfile.fx</param> /// <param name="main">Main function in shader</param> /// <param name="shaderversion">Compute shader version</param> /// <param name="compile">Compile the shader, if false, uses previous compiled file</param> public ComputeShaderHelper(Device device, string filename, string shaderversion = "cs_5_0", string main = "CSMain", bool compile = true) { Device = device; // The maximum amount of unordered acces views that can be bound to the shader // More info here: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476331%28v=vs.85%29.aspx if (Device.FeatureLevel == SharpDX.Direct3D.FeatureLevel.Level_11_0) { Data = new ViewBuffer[8]; DataCount = new int[8]; } else { Data = new ViewBuffer[1]; DataCount = new int[1]; } string existing = filename.Substring(0, filename.Length - 3) + ".hlsl"; if (File.Exists(existing) && !compile) { ShaderBytecode code = ShaderBytecode.FromFile(existing); Shader = new ComputeShader(device, code); } else { ShaderBytecode code = ShaderBytecode.CompileFromFile(filename, main, shaderversion, ShaderFlags.None, EffectFlags.None); Shader = new ComputeShader(device, code); //code.Save(existing); } }
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); } }
/// <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 }
public override bool InitializeGraphics(IRenderManager manager, Device device) { // Compile our vertex and pixel shaders. ShaderBytecode vertexByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\XfMesh.vs"); this.VertexShader = new VertexShader(device, vertexByteCode); ShaderBytecode pixelByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\XfMesh.ps"); this.PixelShader = new PixelShader(device, pixelByteCode); // Setup the sampler states for the vertex shader. SamplerStateDescription vertexDesc = new SamplerStateDescription(); vertexDesc.AddressU = TextureAddressMode.Wrap; vertexDesc.AddressV = TextureAddressMode.Wrap; vertexDesc.AddressW = TextureAddressMode.Wrap; vertexDesc.BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f); vertexDesc.MaximumLod = 13; vertexDesc.Filter = Filter.MinMagMipPoint; vertexDesc.MipLodBias = 0; vertexDesc.MaximumAnisotropy = 1; vertexDesc.ComparisonFunction = Comparison.Never; this.VertexSampleStates = new SamplerState[] { new SamplerState(device, vertexDesc) }; SamplerStateDescription pixelDesc = new SamplerStateDescription(); pixelDesc.AddressU = TextureAddressMode.Wrap; pixelDesc.AddressV = TextureAddressMode.Wrap; pixelDesc.AddressW = TextureAddressMode.Wrap; pixelDesc.BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f); pixelDesc.MaximumLod = 0; pixelDesc.Filter = Filter.Anisotropic; pixelDesc.MipLodBias = 0; pixelDesc.MaximumAnisotropy = 3; this.PixelSampleStates = new SamplerState[] { new SamplerState(device, pixelDesc) }; // Setup our vertex declaration and bind it to the inputs for the vertex shader. this.VertexDeclaration = new InputLayout(device, vertexByteCode.Data, new InputElement[] { // Id: 0x0550228e new InputElement("POSITION", 0, Format.R16G16B16A16_SNorm, 0, 0), new InputElement("NORMAL", 0, Format.R16G16B16A16_SNorm, 16, 0), new InputElement("TANGENT", 0, Format.R16G16B16A16_SNorm, 0, 1), new InputElement("TEXCOORD", 0, Format.R16G16_SNorm, 24, 0), new InputElement("TEXCOORD", 1, Format.R16G16_SNorm, 8, 1), new InputElement("BLENDWEIGHT", 0, Format.R8G8B8A8_UNorm, 12, 0), new InputElement("BLENDINDICES", 0, Format.R8G8B8A8_SInt, 8, 0), new InputElement("TEXCOORD", 2, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 3, Format.R32G32B32A32_Float, 0, 0), }); // Successfully initialized. return(true); }
public override bool InitializeGraphics(IRenderManager manager, Device device) { // Compile our vertex and pixel shaders. ShaderBytecode vertexByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\XfMesh.vs"); this.VertexShader = new VertexShader(device, vertexByteCode); ShaderBytecode pixelByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\XfMesh.ps"); this.PixelShader = new PixelShader(device, pixelByteCode); // Setup the sampler states for the vertex shader. SamplerStateDescription samplerDesc = new SamplerStateDescription(); samplerDesc.AddressU = TextureAddressMode.Wrap; samplerDesc.AddressV = TextureAddressMode.Wrap; samplerDesc.AddressW = TextureAddressMode.Wrap; samplerDesc.BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f); samplerDesc.MaximumLod = 0; samplerDesc.Filter = Filter.Anisotropic; samplerDesc.MipLodBias = 0; samplerDesc.MaximumAnisotropy = 3; this.PixelSampleStates = new SamplerState[] { new SamplerState(device, samplerDesc) }; // Setup our vertex declaration and bind it to the inputs for the vertex shader. this.VertexDeclaration = new InputLayout(device, vertexByteCode.Data, new InputElement[] { /* * Id: 0x87a34e22 * Elem 0: Slot=0 Offset=0 Format=R16G16B16A16_SNORM SemanticName=POSITION Index=0 * Elem 1: Slot=0 Offset=8 Format=R8G8B8A8_UINT SemanticName=BLENDINDICES Index=0 * Elem 2: Slot=0 Offset=12 Format=R8G8B8A8_UINT SemanticName=BLENDINDICES Index=1 * Elem 3: Slot=0 Offset=16 Format=R8G8B8A8_UNORM SemanticName=BLENDWEIGHT Index=0 * Elem 4: Slot=0 Offset=20 Format=R8G8B8A8_UNORM SemanticName=BLENDWEIGHT Index=1 * Elem 5: Slot=0 Offset=24 Format=R16G16B16A16_SNORM SemanticName=NORMAL Index=0 * Elem 6: Slot=0 Offset=32 Format=R16G16_SNORM SemanticName=TEXCOORD Index=0 * Elem 7: Slot=1 Offset=0 Format=R16G16B16A16_SNORM SemanticName=TANGENT Index=0 * Elem 8: Slot=1 Offset=8 Format=R16G16_SNORM SemanticName=TEXCOORD Index=1 */ new InputElement("POSITION", 0, Format.R16G16B16A16_SNorm, 0, 0), new InputElement("TEXCOORD", 0, Format.R16G16_SNorm, 24, 0), new InputElement("BLENDWEIGHT", 0, Format.R8G8B8A8_UNorm, 12, 0), new InputElement("BLENDINDICES", 0, Format.R8G8B8A8_SInt, 8, 0), new InputElement("NORMAL", 0, Format.R16G16B16A16_SNorm, 16, 0), new InputElement("TANGENT", 0, Format.R16G16B16A16_SNorm, 0, 0), new InputElement("TEXCOORD", 1, Format.R16G16_SNorm, 8, 0), new InputElement("TEXCOORD", 2, Format.R16G16_SNorm, 0, 0), new InputElement("TEXCOORD", 3, Format.R16G16_SNorm, 0, 0), }); // Successfully initialized. return(true); }
// load and compile the vertex shader private void LoadVertexShader() { try { if (_shaderEntryPoint.VertexShader_EntryPoint != null) { ShaderBytecode byteCode; //Check if existance of precompiled file FileInfo fi = new FileInfo(_filePathName); string precompiledFileName = string.Concat(fi.DirectoryName, @"\", Path.GetFileNameWithoutExtension(fi.Name), "_", _shaderEntryPoint.VertexShader_EntryPoint, ".chlsl"); if (File.Exists(precompiledFileName)) { //Load precompiled Blob byteCode = ShaderBytecode.FromFile(precompiledFileName); } else { //Live compiling CompilationResult result = ShaderBytecode.CompileFromFile(_filePathName, _shaderEntryPoint.VertexShader_EntryPoint, VSProfiles.DirectX10Profile, D3DEngine.ShaderFlags, EffectFlags.None, null, _includeHandler); //Log Compilation Warning if (result.Message != null) { logger.Warn("Vertex Shader [{0}] compilation message returned :\n{1}", _fileName, result.Message); } byteCode = result.Bytecode; } //Get the VS Input signature from the Vertex Shader _signature = ToDispose(ShaderSignature.GetInputSignature(byteCode)); //Create the inputLayout from the signature (Must Match the Vertex Format used with this effect !!!) if (_vertexDeclaration != null) { _inputLayout = ToDispose(new InputLayout(device, _signature, _vertexDeclaration.Elements)); } _vs = ToDispose(new VertexShader(device, byteCode)); #if DEBUG //Set resource Name, will only be done at debug time. _vs.DebugName = "VertexShader from " + _fileName; #endif using (ShaderReflection shaderMetaData = new ShaderReflection(byteCode)) { ShaderReflection(Shaders.VS, ShaderIDs.VS, shaderMetaData); } byteCode.Dispose(); } } catch (Exception e) { throw new Exception("Shader compilation error : " + e.Message); } }
public static void Main(string[] args) { Device device; Effect effect; device = new Device(DriverType.Hardware, DeviceCreationFlags.None); if (args.Length < 1) { Console.WriteLine("Usage: dumptech.exe <effect file>"); return; } string effect_file = args[0]; if (!File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return; } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return; } //Console.WriteLine("technique count {0}", effect.Description.TechniqueCount); for (int i = 0; i < effect.Description.TechniqueCount; i++) { var technique = effect.GetTechniqueByIndex(i); Console.WriteLine("{0}\t{1}", i, technique.Description.Name); } if (effect != null) { effect.Dispose(); } if (device != null) { device.Dispose(); } }
// load and compile the pixel shader private void LoadPixelShader() { try { if (_shaderEntryPoint.PixelShader_EntryPoint != null) { ShaderBytecode byteCode; //Check if existance of precompiled file FileInfo fi = new FileInfo(_filePathName); string precompiledFileName = string.Concat(fi.DirectoryName, @"\", Path.GetFileNameWithoutExtension(fi.Name), "_", _shaderEntryPoint.PixelShader_EntryPoint, ".chlsl"); if (File.Exists(precompiledFileName)) { //Load precompiled Blob byteCode = ShaderBytecode.FromFile(precompiledFileName); } else { //Live compiling CompilationResult result = ShaderBytecode.CompileFromFile(_filePathName, _shaderEntryPoint.PixelShader_EntryPoint, PSProfiles.DirectX10Profile, D3DEngine.ShaderFlags, EffectFlags.None, null, _includeHandler); //Log Compilation Warning if (result.Message != null) { logger.Warn("Pixel Shader [{0}] compilation message returned :\n{1}", _fileName, result.Message); } byteCode = result.Bytecode; } _ps = ToDispose(new PixelShader(device, byteCode)); #if DEBUG //Set resource Name, will only be done at debug time. _ps.DebugName = "PixelShader from " + _fileName; #endif using (ShaderReflection shaderMetaData = new ShaderReflection(byteCode)) { ShaderReflection(Shaders.PS, ShaderIDs.PS, shaderMetaData); } byteCode.Dispose(); } } catch (Exception e) { throw new Exception("Shader compilation error : " + e.Message); } }
public override bool InitializeGraphics(IRenderManager manager, SharpDX.Direct3D11.Device device) { // Compile our vertex and pixel shaders. ShaderBytecode vertexByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\Wireframe.vs"); this.VertexShader = new VertexShader(device, vertexByteCode); ShaderBytecode pixelByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\Wireframe.ps"); this.PixelShader = new PixelShader(device, pixelByteCode); // Setup our vertex declaration and bind it to the inputs for the vertex shader. this.VertexDeclaration = new InputLayout(device, vertexByteCode.Data, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0), }); // Successfully initialized. return(true); }
public Shader(string file, D3D11.Device device, D3D11.DeviceContext context, params D3D11.InputElement[] inputElements) { if (File.Exists(file + "_vs.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_vs.cso")) { Signature = ShaderSignature.GetInputSignature(byteCode); VertexShader = new D3D11.VertexShader(device, byteCode); InputLayout = new D3D11.InputLayout(device, Signature, inputElements); } } if (File.Exists(file + "_ps.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_ps.cso")) PixelShader = new D3D11.PixelShader(device, byteCode); } if (File.Exists(file + "_gs.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_gs.cso")) GeometryShader = new D3D11.GeometryShader(device, byteCode); } }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="ocu_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, OcuConfig ocu_config) { this.ocu_config = ocu_config; oculus = new OculusWrap.Wrap(); // Initialize the Oculus runtime. bool success = oculus.Initialize(); if (!success) { MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) { hmd = oculus.Hmd_Create(0); } else { hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); } if (hmd == null) { MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (hmd.ProductName == string.Empty) { MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None); // Create DirectX drawing device. device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (!File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return(false); } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return(false); } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return(false); } techmap.Load(techmap_file); control.MouseDown += new MouseEventHandler(form_OnMouseDown); // Define the properties of the swap chain. SwapChainDescription swapChainDescription = DefineSwapChainDescription(control); // Create DirectX Graphics Interface factory, used to create the swap chain. dxgi_factory = new SharpDX.DXGI.Factory(); // Create the swap chain. swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. buf0 = swap_chain.GetBackBuffer <Texture2D>(0); buf0_view = new RenderTargetView(device, buf0); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control); // Create the depth buffer. ztex = new Texture2D(device, depthBufferDescription); ztex_view = new DepthStencilView(device, ztex); ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view); viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); ctx.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } layers = new OculusWrap.Layers(); layer_eye_fov = layers.AddLayerEyeFov(); CreateEyeTextures(); CreateMirrorTexture(control); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); //figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); main_camera = new Camera() { Position = ocu_config.Position, Rotation = Quaternion.Identity, }; directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); keyboardState = keyboard.GetCurrentState(); return(true); }
public static PixelShader LoadPixelShader(string filename) { return(new PixelShader(ApplicationDX11.Instance.Device, ShaderBytecode.FromFile(RealPath(filename)))); }
/// <summary> /// Récupère le PixelShader précompilé /// </summary> private void LoadPixelShaderFromFile(string file) { InitializePixelShader(ShaderBytecode.FromFile(RealPath(file))); }
/// <summary> /// Récupère et Initialise le Geometry Shader précompilé /// </summary> private void LoadGeometryShaderFromFile(string file) { InitializeGeometryShader(ShaderBytecode.FromFile(RealPath(file))); }
public void SetPixelShader(string pixelname) { SetPixelShader(new PixelShader(ApplicationDX11.Instance.Device, ShaderBytecode.FromFile(RealPath(pixelname)))); }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="tso_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, TSOConfig tso_config) { this.tso_config = tso_config; SetControl(control); control.MouseDown += new MouseEventHandler(form_OnMouseDown); control.MouseMove += new MouseEventHandler(form_OnMouseMove); var desc = new SharpDX.DXGI.SwapChainDescription() { BufferCount = 1, Usage = SharpDX.DXGI.Usage.RenderTargetOutput, OutputHandle = control.Handle, IsWindowed = true, ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.B8G8R8A8_UNorm), SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0), Flags = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch, SwapEffect = SharpDX.DXGI.SwapEffect.Discard }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swap_chain); //DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (!File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return(false); } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return(false); } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return(false); } techmap.Load(techmap_file); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for normal in view */ View_variable = effect.GetVariableBySemantic("View").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; camera.Update(); DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); return(true); }
public static bool ValidateShaderOfType(string Type, string HlslType, string OriginalFile, string SourcePath) { var metadata = new ShaderMetadata(OriginalFile.Replace(".bin", ".txt")); // Grab the technique along with each #define used var techniqueId = metadata.GetTechnique(); var macros = GetCompilationMacros(Type, HlslType, metadata.GetDefines().ToList()); // Read from disk, compile, then disassemble to text ShaderBytecode originalBytecode = null; ShaderBytecode newBytecode = null; try { originalBytecode = ShaderBytecode.FromFile(OriginalFile).Strip(m_StripFlags); newBytecode = CompileShaderOfType(SourcePath, HlslType, macros).Strip(m_StripFlags); } catch (InvalidProgramException e) { Program.Log($"{OriginalFile}\n{e.Message}"); return(false); } string[] originalDisasm = originalBytecode.Disassemble(DisassemblyFlags.None).Split('\n'); string[] newDisasm = newBytecode.Disassemble(DisassemblyFlags.None).Split('\n'); // Sometimes the newly generated output will be shorter than the original code. Add some padding // to prevent out-of-bounds array access. if (originalDisasm.Length > newDisasm.Length) { string[] newArray = new string[originalDisasm.Length]; for (int i = 0; i < newArray.Length; i++) { newArray[i] = "\n"; } newDisasm.CopyTo(newArray, 0); newDisasm = newArray; } try { ValidateShaderHeader(originalDisasm, newDisasm); ValidateShaderCode(originalDisasm, newDisasm); } catch (Exception) { // Dump raw disassembly to file File.WriteAllLines($"{Program.ShaderDiffDirectory}\\{Type}-{techniqueId:X}-{HlslType}-old.txt", originalDisasm); File.WriteAllLines($"{Program.ShaderDiffDirectory}\\{Type}-{techniqueId:X}-{HlslType}-new.txt", newDisasm); // // Generate the "symbolic" diff by: // // - Replacing all temporary registers with rX.xxxx // - Sorting all lines // - Eliminating all empty lines // var tempRegisterExpr = new Regex(@"r\d\.[xXyYzZwW]{1,4}", RegexOptions.Compiled); for (int i = 0; i < originalDisasm.Length; i++) { originalDisasm[i] = tempRegisterExpr.Replace(originalDisasm[i], "rX.xxxx"); newDisasm[i] = tempRegisterExpr.Replace(newDisasm[i], "rX.xxxx"); } File.WriteAllLines($"{Program.ShaderDiffDirectory}\\{Type}-{techniqueId:X}-{HlslType}-symbolic-old.txt", originalDisasm.Where(x => !string.IsNullOrWhiteSpace(x)).OrderBy(x => x)); File.WriteAllLines($"{Program.ShaderDiffDirectory}\\{Type}-{techniqueId:X}-{HlslType}-symbolic-new.txt", newDisasm.Where(x => !string.IsNullOrWhiteSpace(x)).OrderBy(x => x)); return(false); } return(true); }