private static ShaderMacro[][] GetShaderMacroPermutations(List <MacroGroup> macroGroups) { if (macroGroups.Count == 0) { var emptyPermutations = new ShaderMacro[1][]; emptyPermutations[0] = new ShaderMacro[] { }; return(emptyPermutations); } int permutationCount = macroGroups[0].Names.Length; for (int i = 1; i < macroGroups.Count; ++i) { permutationCount *= macroGroups[i].Names.Length; } var permutations = new ShaderMacro[permutationCount][]; for (int permutationIndex = 0; permutationIndex < permutationCount; ++permutationIndex) { var permutation = permutations[permutationIndex] = new ShaderMacro[macroGroups.Count]; int index = permutationIndex; for (int i = 0; i < macroGroups.Count; ++i) { var defineCount = macroGroups[i].Names.Length; var newIndex = index / defineCount; var nameIndex = index - defineCount * newIndex; permutation[i] = new ShaderMacro { Name = macroGroups[i].Names[nameIndex] }; index = newIndex; } } return(permutations); }
private void HandleConfigDefinesChangeOnStartup(IDiffSpread <string> spread) { if (FConfigShader[0] != "" && !configWritten) { DX11ShaderInclude FIncludeHandler = new DX11ShaderInclude(); List <ShaderMacro> sms = new List <ShaderMacro>(); if (FConfigDefines[0] != "") { string[] defines = FConfigDefines[0].Split(",".ToCharArray()); for (int i = 0; i < defines.Length; i++) { try { string[] s = defines[i].Split("=".ToCharArray()); if (s.Length == 2) { ShaderMacro sm = new ShaderMacro(); sm.Name = s[0]; sm.Value = s[1]; sms.Add(sm); } } catch { } } } FShader = DX11Effect.FromString(FConfigShader[0], FIncludeHandler, sms.ToArray()); this.SetShader(FShader, !ShaderCreatedByConfig); ShaderCreatedByConfig = true; } }
void FindShaderMacros(String content, ShaderLanguage language, out string[] macros) { // Format: // USERMACRO: SAMPLE_COUNT [1,2,4] String pattern = @"// USERMACRO: ([A-Za-z0-9_]+) \[([0-9]+(,[0-9]+)*)\]"; Regex regex = new Regex(pattern); var matches = regex.Matches(content); List <ShaderMacro[]> table = new List <ShaderMacro[]>(); for (int i = 0; i < matches.Count; ++i) { table.Add(null); } for (int i = 0; i < matches.Count; ++i) { String definition = matches[i].Groups[1].Value; String[] values = matches[i].Groups[2].Value.Trim().Split(','); table[i] = new ShaderMacro[values.Length]; for (int j = 0; j < table[i].Length; ++j) { table[i][j] = new ShaderMacro { definition = definition, value = values[j], }; } } IEnumerable <string> results = new List <string> { null }; String format; switch (language) { case ShaderLanguage.HLSL: format = " -D {0}={1} "; break; case ShaderLanguage.VULKAN_GLSL: format = " \"-D {0}={1}\" "; break; default: format = ""; break; } foreach (var list in table) { // cross join the current result with each member of the next list results = results.SelectMany(o => list.Select(s => o + String.Format(format, s.definition, s.value))); } macros = results.ToArray(); if (macros.Length == 1 && macros[0] == null) { macros[0] = ""; } }
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; }
public static SharpDX.Direct3D11.VertexShader VertexShader(SharpDX.Direct3D11.Device device, string hlslFile, string entryPoint, ShaderMacro[] defines = null, string profile = "vs_5_0") { using (var bytecode = CompileFromFile(hlslFile, entryPoint, profile, defines)) { return new SharpDX.Direct3D11.VertexShader(device, bytecode); } }
public static ShaderMacro[] ConcatenateMacros(ShaderMacro[] sm1, ShaderMacro[] sm2) { var smRes = new ShaderMacro[sm1.Length + sm2.Length]; sm1.CopyTo(smRes, 0); sm2.CopyTo(smRes, sm1.Length); return(smRes); }
internal static void Init() { m_vs = MyShaders.CreateVs("decal.hlsl"); var normalMapMacro = new ShaderMacro("USE_NORMALMAP_DECAL", null); var colorMapMacro = new ShaderMacro("USE_COLORMAP_DECAL", null); m_psColorMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { colorMapMacro, new ShaderMacro("USE_DUAL_SOURCE_BLENDING", null) }); m_psNormalMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { normalMapMacro }); m_psNormalColorMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { normalMapMacro, colorMapMacro }); InitIB(); }
internal static void Compile(ShaderBytecodeId bytecode, bool invalidateCache = false) { var info = Shaders[bytecode]; var path = Path.Combine(MyFileSystem.ContentPath, MyShadersDefines.ShadersContentPath, info.File.ToString()); if (!File.Exists(path)) { string message = "ERROR: Shaders Compile - can not find file: " + path; MyRender11.Log.WriteLine(message); throw new MyRenderException(message, MyRenderExceptionEnum.Unassigned); } ShaderMacro[] macros = MyRender11.GlobalShaderMacro; if (info.Macros != null && info.Macros.Length > 0 || MyRender11.DebugMode) { macros = new ShaderMacro[MyRender11.GlobalShaderMacro.Length + (info.Macros != null ? info.Macros.Length : 0)]; MyRender11.GlobalShaderMacro.CopyTo(macros, 0); if (info.Macros != null) { info.Macros.CopyTo(macros, MyRender11.GlobalShaderMacro.Length); } } string shaderSource; using (var reader = new StreamReader(path)) { shaderSource = reader.ReadToEnd(); } var compiled = Compile(shaderSource, macros, info.Profile, info.File.ToString(), false); Bytecodes.Data[bytecode.Index].Bytecode = compiled ?? Bytecodes.Data[bytecode.Index].Bytecode; if (compiled == null) { string message = "Failed to compile " + info.File + " @ profile " + info.Profile + " with defines " + macros.GetString(); MyRender11.Log.WriteLine(message); if (Debugger.IsAttached) { Debugger.Break(); Compile(bytecode, true); } else { throw new MyRenderException(message, MyRenderExceptionEnum.Unassigned); } } }
internal static void Init() { m_vs = MyShaders.CreateVs("decal.hlsl"); var normalMapMacro = new ShaderMacro("USE_NORMALMAP_DECAL", null); var colorMapMacro = new ShaderMacro("USE_COLORMAP_DECAL", null); var transparentMacro = new ShaderMacro("RENDER_TO_TRANSPARENT", null); var extensionsMacro = new ShaderMacro("USE_EXTENSIONS_TEXTURE", null); m_psColorMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { colorMapMacro }); m_psColorMapTransparent = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { colorMapMacro, transparentMacro }); m_psNormalMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { normalMapMacro }); m_psNormalColorMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { colorMapMacro, normalMapMacro }); m_psNormalColorExtMap = MyShaders.CreatePs("decal.hlsl", new ShaderMacro[] { colorMapMacro, normalMapMacro, extensionsMacro }); InitIB(); }
private static int InitShaders(MyBlurDensityFunctionType densityFunctionType, int maxOffset, float depthDiscardThreshold) { bool useDepthDiscard = depthDiscardThreshold > 0; int shaderKey = GetShaderKey(densityFunctionType, maxOffset, useDepthDiscard); if(!m_blurShaders.ContainsKey(shaderKey)) { ShaderMacro depthMacro = new ShaderMacro(useDepthDiscard ? "DEPTH_DISCARD_THRESHOLD" : "", useDepthDiscard ? depthDiscardThreshold : 1); var macrosHorizontal = new[] { new ShaderMacro("HORIZONTAL_PASS", null), new ShaderMacro("MAX_OFFSET", maxOffset), new ShaderMacro("DENSITY_FUNCTION", (int)densityFunctionType), depthMacro }; var macrosVertical = new[] { new ShaderMacro("VERTICAL_PASS", null), new ShaderMacro("MAX_OFFSET", maxOffset), new ShaderMacro("DENSITY_FUNCTION", (int)densityFunctionType), depthMacro }; var shaderPair = MyTuple.Create(MyShaders.CreatePs("Postprocess/Blur.hlsl", macrosHorizontal), MyShaders.CreatePs("Postprocess/Blur.hlsl", macrosVertical)); m_blurShaders.Add(shaderKey, shaderPair); } return shaderKey; }
private static int InitShaders(MyBlurDensityFunctionType densityFunctionType, int maxOffset, float depthDiscardThreshold) { bool useDepthDiscard = depthDiscardThreshold > 0; int shaderKey = GetShaderKey(densityFunctionType, maxOffset, useDepthDiscard); if (!m_blurShaders.ContainsKey(shaderKey)) { ShaderMacro depthMacro = new ShaderMacro(useDepthDiscard ? "DEPTH_DISCARD_THRESHOLD" : "", useDepthDiscard ? depthDiscardThreshold : 1); var macrosHorizontal = new[] { new ShaderMacro("HORIZONTAL_PASS", null), new ShaderMacro("MAX_OFFSET", maxOffset), new ShaderMacro("DENSITY_FUNCTION", (int)densityFunctionType), depthMacro }; var macrosVertical = new[] { new ShaderMacro("VERTICAL_PASS", null), new ShaderMacro("MAX_OFFSET", maxOffset), new ShaderMacro("DENSITY_FUNCTION", (int)densityFunctionType), depthMacro }; var shaderPair = MyTuple.Create(MyShaders.CreatePs("Postprocess/Blur.hlsl", macrosHorizontal), MyShaders.CreatePs("Postprocess/Blur.hlsl", macrosVertical)); m_blurShaders.Add(shaderKey, shaderPair); } return(shaderKey); }
internal static void Init() { m_vs = MyShaders.CreateVs("Decals/Decals.hlsl"); var transparentMacro = new ShaderMacro("RENDER_TO_TRANSPARENT", null); m_psColorMapTransparent = MyShaders.CreatePs("Decals/Decals.hlsl", new ShaderMacro[] { transparentMacro }); m_psColorMap = MyShaders.CreatePs("Decals/Decals.hlsl", MyMeshMaterials1.GetMaterialTextureMacros(MyFileTextureEnum.COLOR_METAL)); m_psNormalMap = MyShaders.CreatePs("Decals/Decals.hlsl", MyMeshMaterials1.GetMaterialTextureMacros(MyFileTextureEnum.NORMALMAP_GLOSS)); m_psNormalColorMap = MyShaders.CreatePs("Decals/Decals.hlsl", MyMeshMaterials1.GetMaterialTextureMacros(MyFileTextureEnum.COLOR_METAL | MyFileTextureEnum.NORMALMAP_GLOSS)); m_psNormalColorExtMap = MyShaders.CreatePs("Decals/Decals.hlsl", MyMeshMaterials1.GetMaterialTextureMacros( MyFileTextureEnum.COLOR_METAL | MyFileTextureEnum.NORMALMAP_GLOSS | MyFileTextureEnum.EXTENSIONS)); InitIB(); }
public object Read(ContentStream stream, object existingObject) { if (existingObject == null) { BinaryReader binaryReader = new BinaryReader(stream); string vertexShaderCode = binaryReader.ReadString(); string pixelShaderCode = binaryReader.ReadString(); int num = binaryReader.ReadInt32(); ShaderMacro[] array = new ShaderMacro[num]; for (int i = 0; i < num; i++) { string name = binaryReader.ReadString(); string value = binaryReader.ReadString(); array[i] = new ShaderMacro(name, value); } return(new Shader(vertexShaderCode, pixelShaderCode, array)); } throw new NotSupportedException(); }
/// <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; }
public static ShaderMacro[] GetComponentMacros(string declaration, string transferCode, MyVertexInputComponent[] components) { ShaderMacro macroDecl = new ShaderMacro("VERTEX_COMPONENTS_DECLARATIONS", declaration); ShaderMacro macroTransfer = new ShaderMacro("TRANSFER_VERTEX_COMPONENTS", transferCode); bool isTexIndices = false; foreach (var comp in components) { if (comp.Type == MyVertexInputComponentType.TEXINDICES) { isTexIndices = true; } } if (isTexIndices) { return new ShaderMacro[] { macroDecl, macroTransfer, new ShaderMacro("USE_TEXTURE_INDICES", null), } } ; else { return new ShaderMacro[] { macroDecl, macroTransfer } }; }
public void Write(string projectDirectory, Stream stream) { string value = Storage.ReadAllText(Storage.CombinePaths(projectDirectory, VertexShader)); string value2 = Storage.ReadAllText(Storage.CombinePaths(projectDirectory, PixelShader)); string[] array = Macros.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); ShaderMacro[] array2 = new ShaderMacro[array.Length]; for (int i = 0; i < array.Length; i++) { string[] array3 = array[i].Split('=', StringSplitOptions.None); if (array3.Length == 1) { array2[i] = new ShaderMacro(array3[0].Trim()); continue; } if (array3.Length == 2) { array2[i] = new ShaderMacro(array3[0].Trim(), array3[1].Trim()); continue; } throw new InvalidOperationException("Error parsing shader macros."); } BinaryWriter binaryWriter = new BinaryWriter(stream); binaryWriter.Write(value); binaryWriter.Write(value2); binaryWriter.Write(array2.Length); for (int j = 0; j < array2.Length; j++) { binaryWriter.Write(array2[j].Name); binaryWriter.Write(array2[j].Value); } }
internal static ShaderMacro[] PrepareMacros(ShaderMacro[] macros) { if (macros == null) { return(null); } if (macros.Length == 0) { return(null); } if (macros[macros.Length - 1].Name == null && macros[macros.Length - 1].Definition == null) { return(macros); } var macroArray = new ShaderMacro[macros.Length + 1]; Array.Copy(macros, macroArray, macros.Length); macroArray[macros.Length] = new ShaderMacro(); return(macroArray); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { m_device.Init(panelOutput.Handle, false, true); } catch (Exception _e) { m_device = null; MessageBox.Show("Failed to initialize DX device!\n\n" + _e.Message, "MSBRDF Test", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { // m_shader_Render = new Shader( m_device, new System.IO.FileInfo( "Shaders/Render.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS" ); // OBSOLETE MSBRDF CODE! For historical purpose only... m_shader_Finalize = new Shader(m_device, new System.IO.FileInfo("Shaders/Finalize.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); #if TEST_COMPLETE_SCENE || TEST_COMPLETE_SCENE_SPHERE_ONLY // Use this for a full render ShaderMacro[] macros = null; #if TEST_COMPLETE_SCENE macros = new ShaderMacro[] { new ShaderMacro("FULL_SCENE", "1") }; #endif m_shader_Accumulate = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderComplete.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS", macros); #elif TEST_SH_ENVIRONMENT // Use this to show a rendering with SH environment m_shader_Accumulate = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderCompareSH.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS", null); checkBoxUseRealTimeApprox.Visible = true; checkBoxUseRealTimeApprox.Checked = true; floatTrackbarControlRoughnessSphere.Value = 1; // Show full roughness floatTrackbarControlReflectanceSphere2.Value = 0; // Disturbing if diffuse is showing! groupBoxPlane.Visible = false; // No plane is available in this configuration #elif TEST_LTC_AREA_LIGHT // Use this to show a rendering with LTC area light m_shader_Accumulate = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderCompareLTC.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); checkBoxUseRealTimeApprox.Visible = true; // checkBoxUseRealTimeApprox.Checked = true; checkBoxUseRealTimeApprox.Checked = false; // floatTrackbarControlRoughnessSphere.Value = 1; // Show full roughness // floatTrackbarControlReflectanceSphere2.Value = 0; // Disturbing if diffuse is showing! checkBoxUseLTC.Visible = true; floatTrackbarControlRoughnessSphere.Value = 0.25f; floatTrackbarControlReflectanceSphere.Value = 0.04f; floatTrackbarControlRoughnessSphere2.Value = 0.80f; floatTrackbarControlReflectanceSphere2.Value = 0.5f; floatTrackbarControlRoughnessGround.Value = 0.85f; floatTrackbarControlReflectanceGround.Value = 0.35f; floatTrackbarControlLightElevation.Value = 0.5f; #elif TEST_DIRECTIONAL_LIGHT // Use this to show a rendering with a directional light m_shader_Accumulate = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderDirectional.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS", null); #else throw new Exception("Invalid scene!"); #endif } catch (Exception _e) { MessageBox.Show("Shader failed to compile!\n\n" + _e.Message, "MSBRDF Test", MessageBoxButtons.OK, MessageBoxIcon.Error); } uint W = (uint)panelOutput.Width; uint H = (uint)panelOutput.Height; m_CB_Global = new ConstantBuffer <CB_Global>(m_device, 0); m_CB_Camera = new ConstantBuffer <CB_Camera>(m_device, 1); m_CB_Render = new ConstantBuffer <CB_Render>(m_device, 2); m_CB_SH = new ConstantBuffer <CB_SH>(m_device, 3); BuildNoiseTextures(); // Shuffle group indices for (uint groupIndex = 0; groupIndex < GROUPS_COUNT; groupIndex++) { m_groupShuffle[groupIndex] = groupIndex; } for (uint shuffleIndex = 100 * GROUPS_COUNT; shuffleIndex > 0; shuffleIndex--) { for (uint groupIndex = 0; groupIndex < GROUPS_COUNT; groupIndex++) { uint i0 = SimpleRNG.GetUint() % GROUPS_COUNT; uint i1 = SimpleRNG.GetUint() % GROUPS_COUNT; uint temp = m_groupShuffle[i0]; m_groupShuffle[i0] = m_groupShuffle[i1]; m_groupShuffle[i1] = temp; } } // Tables are "built" with Mathematica now // BuildMSBRDF( new DirectoryInfo( @".\Tables\" ) ); // LoadMSBRDF( 128, new FileInfo( "./Tables/MSBRDF_GGX_G2_E128x128.float" ), new FileInfo( "./Tables/MSBRDF_GGX_G2_Eavg128.float" ), out m_tex_MSBRDF_GGX_E, out m_tex_MSBRDF_GGX_Eavg ); // LoadMSBRDF( 32, new FileInfo( "./Tables/MSBRDF_OrenNayar_E32x32.float" ), new FileInfo( "./Tables/MSBRDF_OrenNayar_Eavg32.float" ), out m_tex_MSBRDF_OrenNayar_E, out m_tex_MSBRDF_OrenNayar_Eavg ); LoadMSBRDF(new uint[] { 128, 128, 128, 32, 32, 32 }, new FileInfo[] { new FileInfo("./Tables/MSBRDF_GGX_G2_E128x128.float"), new FileInfo("./Tables/MSBRDF_GGX_G2_E128x128.float"), new FileInfo("./Tables/MSBRDF_GGX_G2_E128x128.float"), new FileInfo("./Tables/MSBRDF_OrenNayar_E32x32.float"), new FileInfo("./Tables/MSBRDF_OrenNayar_E32x32.float"), new FileInfo("./Tables/MSBRDF_OrenNayar_E32x32.float"), }, new FileInfo[] { new FileInfo("./Tables/MSBRDF_GGX_G2_Eavg128.float"), new FileInfo("./Tables/MSBRDF_GGX_G2_Eavg128.float"), new FileInfo("./Tables/MSBRDF_GGX_G2_Eavg128.float"), new FileInfo("./Tables/MSBRDF_OrenNayar_Eavg32.float"), new FileInfo("./Tables/MSBRDF_OrenNayar_Eavg32.float"), new FileInfo("./Tables/MSBRDF_OrenNayar_Eavg32.float"), }, out m_tex_MSBRDF_E, out m_tex_MSBRDF_Eavg ); #if TEST_LTC_AREA_LIGHT // Area light m_tex_LTC = LoadLTC(new FileInfo(@".\Tables\LTC.dds")); m_tex_MS_LTC = LoadMSLTC(new FileInfo(@".\Tables\MS_LTC.dds")); #endif // Load cube map using (ImageUtility.ImagesMatrix I = new ImageUtility.ImagesMatrix()) { // I.DDSLoadFile( new FileInfo( "garage4_hd.dds" ) ); I.DDSLoadFile(new FileInfo("beach.dds")); EncodeCubeMapIntoSH(I); m_tex_CubeMap = new Texture2D(m_device, I, ImageUtility.COMPONENT_FORMAT.AUTO); } m_tex_Accumulator = new Texture2D(m_device, m_device.DefaultTarget.Width, m_device.DefaultTarget.Height, 1, 1, ImageUtility.PIXEL_FORMAT.RGBA32F, ImageUtility.COMPONENT_FORMAT.AUTO, false, true, null); // Setup camera m_camera.CreatePerspectiveCamera((float)(60.0 * Math.PI / 180.0), (float)panelOutput.Width / panelOutput.Height, 0.01f, 100.0f); m_manipulator.Attach(panelOutput, m_camera); // m_manipulator.InitializeCamera( new float3( 0, 1.5f, 2.0f ), new float3( -0.4f, 0, 0.4f ), float3.UnitY ); // Garage probe m_manipulator.InitializeCamera(new float3(1.46070266f, 1.10467184f, 1.36212754f), new float3(0, 1, 0), float3.UnitY); // Beach probe m_camera.CameraTransformChanged += Camera_CameraTransformChanged; Camera_CameraTransformChanged(null, EventArgs.Empty); // Start game time m_Ticks2Seconds = 1.0 / System.Diagnostics.Stopwatch.Frequency; m_StopWatch.Start(); m_StartGameTime = GetGameTime(); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); m_Device.Init(viewportPanel.Handle, false, true); m_Device.Clear(m_Device.DefaultTarget, new RendererManaged.float4(Color.SkyBlue, 1)); Reg(m_CB_Camera = new ConstantBuffer <CB_Camera>(m_Device, 0)); Reg(m_CB_Render = new ConstantBuffer <CB_Render>(m_Device, 8)); ////////////////////////////////////////////////////////////////////////// // Photon Shooter #if DEBUG_INFOS ShaderMacro[] Macros = new ShaderMacro[] { new ShaderMacro("DEBUG", "") }; #else ShaderMacro[] Macros = null; #endif Reg(m_CS_PhotonShooter = new ComputeShader(m_Device, new ShaderFile(new System.IO.FileInfo(@"Shaders/LayeredRenderer/PhotonShooter.hlsl")), "CS", Macros)); Reg(m_CB_PhotonShooterInput = new ConstantBuffer <CB_PhotonShooterInput>(m_Device, 8)); BuildPhaseQuantileBuffer(new System.IO.FileInfo(@"Mie65536x2.float")); BuildRandomBuffer(); Reg(m_SB_Photons = new StructuredBuffer <SB_Photon>(m_Device, PHOTONS_COUNT, true)); Reg(m_SB_PhotonLayerIndices = new StructuredBuffer <uint>(m_Device, PHOTONS_COUNT, true)); Reg(m_SB_ProcessedPhotonsCounter = new StructuredBuffer <uint>(m_Device, 1, true)); Build3DDensityField(); ////////////////////////////////////////////////////////////////////////// // Photons Splatter Reg(m_PS_PhotonSplatter = new Shader(m_Device, new ShaderFile(new System.IO.FileInfo(@"Shaders/LayeredRenderer/SplatPhoton.hlsl")), VERTEX_FORMAT.P3, "VS", "GS", "PS", Macros)); Reg(m_CB_SplatPhoton = new ConstantBuffer <CB_SplatPhoton>(m_Device, 8)); Reg(m_Tex_PhotonLayers_Flux = new Texture3D(m_Device, 512, 512, LAYERS_COUNT + 1, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null)); Reg(m_Tex_PhotonLayers_Direction = new Texture3D(m_Device, 512, 512, LAYERS_COUNT + 1, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null)); // Build a single point that will be instanced as many times as there are photons { ByteBuffer Point = new ByteBuffer(3 * System.Runtime.InteropServices.Marshal.SizeOf(typeof(float3))); Reg(m_Prim_Point = new Primitive(m_Device, 1, Point, null, Primitive.TOPOLOGY.POINT_LIST, VERTEX_FORMAT.P3)); } ////////////////////////////////////////////////////////////////////////// // Photons Renderer Reg(m_PS_RenderLayer = new Shader(m_Device, new ShaderFile(new System.IO.FileInfo(@"Shaders/LayeredRenderer/DisplayPhotonLayer.hlsl")), VERTEX_FORMAT.Pt4, "VS", null, "PS", null)); Reg(m_PS_RenderWorldCube = new Shader(m_Device, new ShaderFile(new System.IO.FileInfo(@"Shaders/DisplayWorldCube.hlsl")), VERTEX_FORMAT.P3N3, "VS", null, "PS", null)); BuildQuad(); BuildCube(); // ////////////////////////////////////////////////////////////////////////// // // Photon Vectors Renderer // Reg( m_PS_RenderPhotonVectors = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/DisplayPhotonVector.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null ) ); // Reg( m_CB_RenderPhotonVector = new ConstantBuffer<CB_RenderPhotonVector>( m_Device, 8 ) ); // { // ByteBuffer Line = VertexP3.FromArray( new VertexP3[] { new VertexP3() { P = new float3( 0, 0, 0 ) }, new VertexP3() { P = new float3( 1, 0, 0 ) } } ); // Reg( m_Prim_Line = new Primitive( m_Device, 2, Line, null, Primitive.TOPOLOGY.LINE_LIST, VERTEX_FORMAT.P3 ) ); // } // Create the camera manipulator m_CB_Camera.m.Camera2World = float4x4.Identity; UpdateCameraProjection(60.0f * (float)Math.PI / 180.0f, (float)viewportPanel.Width / viewportPanel.Height, 0.1f, 100.0f); m_Manipulator.Attach(viewportPanel); m_Manipulator.CameraTransformChanged += new CameraManipulator.UpdateCameraTransformEventHandler(Manipulator_CameraTransformChanged); m_Manipulator.InitializeCamera(new float3(0.0f, 0.0f, 4.0f), new float3(0, 0, 0), new float3(0, 1, 0)); integerTrackbarControlLayerDisplayStart.RangeMax = LAYERS_COUNT; integerTrackbarControlLayerDisplayStart.VisibleRangeMax = LAYERS_COUNT; integerTrackbarControlLayerDisplayEnd.RangeMax = LAYERS_COUNT + 1; integerTrackbarControlLayerDisplayEnd.VisibleRangeMax = LAYERS_COUNT + 1; integerTrackbarControlLayerDisplayEnd.Value = LAYERS_COUNT + 1; }
/// <summary> /// Preprocesses the provided shader or effect source. /// </summary> /// <param name = "shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param> /// <param name = "defines">A set of macros to define during preprocessing.</param> /// <param name = "include">An interface for handling include files.</param> /// <returns>The preprocessed shader source.</returns> public static string Preprocess(byte[] shaderSource, ShaderMacro[] defines = null, Include include = null, string sourceFileName = "") { string errors = null; return Preprocess(shaderSource, defines, include, out errors, sourceFileName); }
private ITaskItem CompileShaderFile(string sourceFile, string outputFile, ShaderMacro[] defines) { try { var shaderFlags = GetShaderFlags(); using (var shaderInclude = new ShaderInclude(IncludePath ?? string.Empty)) using (var compilerResult = ShaderBytecode.CompileFromFile(sourceFile, EntryPoint ?? "main", Profile, include: shaderInclude, shaderFlags: shaderFlags, defines: defines)) { if (compilerResult.HasErrors) { int line; int column; string errorMessage; GetCompileResult(compilerResult.Message, out line, out column, out errorMessage); Log.LogError("Shader", compilerResult.ResultCode.ToString(), string.Empty, sourceFile, line, column, 0, 0, errorMessage); } var fileInfo = new FileInfo(outputFile); if (fileInfo.Directory != null) { fileInfo.Directory.Create(); } File.WriteAllBytes(outputFile, compilerResult.Bytecode.Data); return new TaskItem(outputFile); } } catch (CompilationException ex) { int line; int column; string errorMessage; GetCompileResult(ex.Message, out line, out column, out errorMessage); Log.LogError("Shader", ex.ResultCode.ToString(), string.Empty, sourceFile, line, column, 0, 0, errorMessage); return null; } catch (Exception ex) { Log.LogError("Shader", ex.HResult.ToString(CultureInfo.InvariantCulture), string.Empty, sourceFile, 0, 0, 0, 0, string.Format("Critical failure ({0}:) {1}", ex.GetType(), ex.Message)); return null; } }
/// <summary> /// Compiles a shader or effect from a file on disk. /// </summary> /// <param name = "fileName">The name of the source file to compile.</param> /// <param name = "profile">The shader target or set of shader features to compile against.</param> /// <param name = "shaderFlags">Shader compilation options.</param> /// <param name = "effectFlags">Effect compilation options.</param> /// <param name = "defines">A set of macros to define during compilation.</param> /// <param name = "include">An interface for handling include files.</param> /// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if compilation succeeded.</param> /// <returns>The compiled shader bytecode, or <c>null</c> if the method fails.</returns> public static CompilationResult CompileFromFile(string fileName, string profile, ShaderFlags shaderFlags = ShaderFlags.None , EffectFlags effectFlags = EffectFlags.None, ShaderMacro[] defines = null, Include include = null) { return CompileFromFile(fileName, null, profile, shaderFlags, effectFlags, defines, include); }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="sourceFileName">Name of the source file used for reporting errors. Default is "unknown"</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(byte[] shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown") { unsafe { var resultCode = Result.Ok; Blob blobForCode = null; Blob blobForErrors = null; #if !DIRECTX11_1 if ((shaderFlags & Effect10) != 0) { shaderFlags ^= Effect10; fixed (void* pData = &shaderSource[0]) resultCode = D3D.CompileEffect10FromMemory( (IntPtr)pData, shaderSource.Length, sourceFileName, PrepareMacros(defines), IncludeShadow.ToIntPtr(include), shaderFlags, effectFlags, out blobForCode, out blobForErrors); } else #endif { fixed (void* pData = &shaderSource[0]) resultCode = D3D.Compile( (IntPtr)pData, shaderSource.Length, sourceFileName, PrepareMacros(defines), IncludeShadow.ToIntPtr(include), entryPoint, profile, shaderFlags, effectFlags, out blobForCode, out blobForErrors); } if (resultCode.Failure) { if (blobForErrors != null) { if (Configuration.ThrowOnShaderCompileError) throw new CompilationException(resultCode, Utilities.BlobToString(blobForErrors)); } else { throw new SharpDXException(resultCode); } } return new CompilationResult(blobForCode != null ? new ShaderBytecode(blobForCode) : null, resultCode, Utilities.BlobToString(blobForErrors)); } }
public static PixelShaderId CreatePs(string file, ShaderMacro[] macros = null) { var bytecode = CreateBytecode(); var id = new PixelShaderId { Index = PixelShaders.Allocate() }; PixelShaders.Data[id.Index] = new MyShaderInfo { Bytecode = bytecode }; MyArrayHelpers.Reserve(ref PsObjects, id.Index + 1); // compile at once Shaders[bytecode] = new MyShaderCompilationInfo { File = X.TEXT_(file), Profile = MyShadersDefines.Profiles.ps_5_0, Macros = macros }; PsObjects[id.Index] = null; InitPs(id, file); PsIndex.Add(id); return id; }
/// <summary> /// Preprocesses the provided shader or effect source. /// </summary> /// <param name = "shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param> /// <param name = "defines">A set of macros to define during preprocessing.</param> /// <param name = "include">An interface for handling include files.</param> /// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param> /// <returns>The preprocessed shader source.</returns> public static string Preprocess(IntPtr shaderSourcePtr, int shaderSourceLength, ShaderMacro[] defines, Include include, out string compilationErrors, string sourceFileName = "") { unsafe { Blob blobForText = null; Blob blobForErrors = null; compilationErrors = null; try { D3D.Preprocess(shaderSourcePtr, shaderSourceLength, sourceFileName, PrepareMacros(defines), IncludeShadow.ToIntPtr(include), out blobForText, out blobForErrors); } catch (SharpDXException ex) { if (blobForErrors != null) { compilationErrors = Utilities.BlobToString(blobForErrors); throw new CompilationException(ex.ResultCode, compilationErrors); } throw; } return Utilities.BlobToString(blobForText); } }
internal static GeometryShaderId CreateGs(string file, ShaderMacro[] macros = null, MyShaderStreamOutputInfo? streamOut = null) { var bytecode = CreateBytecode(); var id = new GeometryShaderId { Index = GeometryShaders.Allocate() }; GeometryShaders.Data[id.Index] = new MyShaderInfo { Bytecode = bytecode }; MyArrayHelpers.Reserve(ref GsObjects, id.Index + 1); // compile at once Shaders[bytecode] = new MyShaderCompilationInfo { File = X.TEXT_(file), Profile = MyShadersDefines.Profiles.gs_5_0, Macros = macros }; GsObjects[id.Index] = null; if (streamOut.HasValue) { StreamOutputs[id] = streamOut.Value; } InitGs(id, file); GsIndex.Add(id); GsObjects[id.Index].DebugName = file; return id; }
internal static ComputeShaderId CreateCs(string file, ShaderMacro[] macros = null) { var bytecode = CreateBytecode(); var id = new ComputeShaderId { Index = ComputeShaders.Allocate() }; ComputeShaders.Data[id.Index] = new MyShaderInfo { Bytecode = bytecode }; MyArrayHelpers.Reserve(ref CsObjects, id.Index + 1); // compile at once Shaders[bytecode] = new MyShaderCompilationInfo { File = X.TEXT_(file), Profile = MyShadersDefines.Profiles.cs_5_0, Macros = macros, }; CsObjects[id.Index] = null; InitCs(id, file); CsIndex.Add(id); return id; }
/// <summary> /// リストファイルからロードする(ランタイムコンパイル) /// </summary> /// <param name="listFile"></param> static void LoadFromListFile(string listFile) { using (StreamReader sr = new StreamReader(listFile)) { string rootDir = System.IO.Path.GetDirectoryName(listFile); bool end = false; int count = 0; while (!end) { if (sr.EndOfStream) { end = true; continue; } string line = sr.ReadLine().Trim(); if (line.Length == 0 || line[0] == '#') { continue; } // コマンドパース string[] args = line.Split(' '); string name = args[0]; string file = args[1]; string vsEntry = null; string psEntry = null; List <string> defineList = new List <string>(); for (int i = 2; i < args.Length; i++) { switch (args[i]) { case "-vs": vsEntry = args[++i]; break; case "-ps": psEntry = args[++i]; break; case "-D": defineList.Add(args[++i]); break; } } ShaderMacro[] macro = null; if (defineList.Count > 0) { macro = new ShaderMacro[defineList.Count]; int i = 0; foreach (var d in defineList) { macro[i] = new ShaderMacro(d); i++; } } // コンパイル Shader.InitDesc shaderDesc = new Shader.InitDesc { name = name, file_name = rootDir + "/" + file, id = Util.CalcCrc32(name), profile = "5_0", vs_main = vsEntry, ps_main = psEntry, macro = macro, }; if (count < shaderArray_.Count) { // リロード shaderArray_[count].Dispose(); shaderArray_[count].Initialize(shaderDesc); } else { shaderArray_.Add(new Shader(shaderDesc)); } count++; } } }
private static string PreprocessShader(string source, ShaderMacro[] macros) { try { var includes = new MyIncludeProcessor(Path.Combine(MyFileSystem.ContentPath, MyShadersDefines.ShadersContentPath)); return ShaderBytecode.Preprocess(source, macros, includes); } catch (CompilationException e) { return null; } }
internal static byte[] Compile(string source, ShaderMacro[] macros, MyShadersDefines.Profiles profile, string sourceDescriptor, bool optimize, bool invalidateCache, out bool wasCached, out string compileLog) { ProfilerShort.Begin("MyShaders.Compile"); string function = MyShadersDefines.ProfileEntryPoint(profile); string profileName = MyShadersDefines.ProfileToString(profile); wasCached = false; compileLog = null; ProfilerShort.Begin("MyShaders.Preprocess"); string preprocessedSource = PreprocessShader(source, macros); var key = MyShaderCache.CalculateKey(preprocessedSource, function, profileName); if (!invalidateCache) { var cached = MyShaderCache.TryFetch(key); if (cached != null) { wasCached = true; ProfilerShort.End(); ProfilerShort.End(); return cached; } } ProfilerShort.End(); try { string descriptor = sourceDescriptor + " " + profile + " " + macros.GetString(); CompilationResult compilationResult = ShaderBytecode.Compile(preprocessedSource, function, profileName, optimize ? ShaderFlags.OptimizationLevel3 : 0, 0, null, null, descriptor); if (DUMP_CODE) { var disassembly = compilationResult.Bytecode.Disassemble(DisassemblyFlags.EnableColorCode | DisassemblyFlags.EnableInstructionNumbering); string asmPath; if (MyRender11.DebugMode) { asmPath = Path.GetFileName(descriptor + "__DEBUG.html"); } else { asmPath = Path.GetFileName(descriptor + "__O3.html"); } using (var writer = new StreamWriter(Path.Combine(MyFileSystem.ContentPath, "ShaderOutput", asmPath))) { writer.Write(disassembly); } } if (compilationResult.Message != null) { compileLog = ExtendedErrorMessage(source, compilationResult.Message) + DumpShaderSource(key, preprocessedSource); } if (compilationResult.Bytecode != null && compilationResult.Bytecode.Data.Length > 0) MyShaderCache.Store(key.ToString(), compilationResult.Bytecode.Data); return compilationResult.Bytecode != null ? compilationResult.Bytecode.Data : null; } catch (CompilationException e) { Debug.WriteLine(preprocessedSource); compileLog = ExtendedErrorMessage(source, e.Message) + DumpShaderSource(key, preprocessedSource); } finally { ProfilerShort.End(); } return null; }
internal static byte[] Compile(string source, ShaderMacro[] macros, MyShadersDefines.Profiles profile, string sourceDescriptor, bool invalidateCache) { bool wasCached; string compileLog; var result = Compile(source, macros, profile, sourceDescriptor, !MyRender11.DebugMode, invalidateCache, out wasCached, out compileLog); if (!wasCached) { string message = "WARNING: Shader was not precompiled - " + sourceDescriptor + " @ profile " + profile + " with defines " + macros.GetString(); MyRender11.Log.WriteLine(message); } if (!string.IsNullOrEmpty(compileLog)) { string descriptor = sourceDescriptor + " " + MyShadersDefines.ProfileToString(profile) + " " + macros.GetString(); if (result != null) { Debug.WriteLine(String.Format("Compilation of shader {0} notes:\n{1}", descriptor, compileLog)); } else { string message = String.Format("Compilation of shader {0} errors:\n{1}", descriptor, compileLog); MyRender11.Log.WriteLine(message); Debug.WriteLine(message); Debugger.Break(); } } return result; }
/// <summary> /// Preprocesses a shader or effect from a file on disk. /// </summary> /// <param name = "fileName">The name of the source file to compile.</param> /// <param name = "defines">A set of macros to define during preprocessing.</param> /// <param name = "include">An interface for handling include files.</param> /// <returns>The preprocessed shader source.</returns> public static string PreprocessFromFile(string fileName, ShaderMacro[] defines, Include include) { string errors = null; return PreprocessFromFile(fileName, defines, include, out errors); }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="shaderSource">A string containing the source of the shader or effect to compile.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if compilation succeeded.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(string shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown") { if (string.IsNullOrEmpty(shaderSource)) { throw new ArgumentNullException("shaderSource"); } return Compile(Encoding.ASCII.GetBytes(shaderSource), entryPoint, profile, shaderFlags, effectFlags, defines, include, sourceFileName); }
/// <summary> /// Preprocesses a shader or effect from a file on disk. /// </summary> /// <param name = "fileName">The name of the source file to compile.</param> /// <param name = "defines">A set of macros to define during preprocessing.</param> /// <param name = "include">An interface for handling include files.</param> /// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param> /// <returns>The preprocessed shader source.</returns> public static string PreprocessFromFile(string fileName, ShaderMacro[] defines, Include include, out string compilationErrors) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (!File.Exists(fileName)) { throw new FileNotFoundException("Could not open the shader or effect file.", fileName); } return Preprocess(File.ReadAllText(fileName), defines, include, out compilationErrors); }
/// <summary> /// Compiles a shader or effect from a file on disk. /// </summary> /// <param name="fileName">The name of the source file to compile.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult CompileFromFile(string fileName, string entryPoint, string profile, ShaderFlags shaderFlags = ShaderFlags.None, EffectFlags effectFlags = EffectFlags.None, ShaderMacro[] defines = null, Include include = null) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (profile == null) { throw new ArgumentNullException("profile"); } if (!File.Exists(fileName)) { throw new FileNotFoundException("Could not open the shader or effect file.", fileName); } unsafe { var resultCode = Result.Ok; Blob blobForCode = null; Blob blobForErrors = null; #if DIRECTX11_1 resultCode = D3D.CompileFromFile( fileName, PrepareMacros(defines), IncludeShadow.ToIntPtr(include), entryPoint, profile, shaderFlags, effectFlags, out blobForCode, out blobForErrors); if (resultCode.Failure) { if (blobForErrors != null) { if (Configuration.ThrowOnShaderCompileError) throw new CompilationException(resultCode, Utilities.BlobToString(blobForErrors)); } else { throw new SharpDXException(resultCode); } } return new CompilationResult(blobForCode != null ? new ShaderBytecode(blobForCode) : null, resultCode, Utilities.BlobToString(blobForErrors)); #else return Compile(File.ReadAllText(fileName), entryPoint, profile, shaderFlags, effectFlags, PrepareMacros(defines), include, fileName); #endif } }
internal static ShaderMacro[] PrepareMacros(ShaderMacro[] macros) { if (macros == null) return null; if (macros.Length == 0) return null; if (macros[macros.Length - 1].Name == null && macros[macros.Length - 1].Definition == null) return macros; var macroArray = new ShaderMacro[macros.Length + 1]; Array.Copy(macros, macroArray, macros.Length); macroArray[macros.Length] = new ShaderMacro(null, null); return macroArray; }
/// <summary> /// Preprocesses the provided shader or effect source. /// </summary> /// <param name = "shaderSource">A string containing the source of the shader or effect to preprocess.</param> /// <param name = "defines">A set of macros to define during preprocessing.</param> /// <param name = "include">An interface for handling include files.</param> /// <returns>The preprocessed shader source.</returns> public static string Preprocess(string shaderSource, ShaderMacro[] defines = null, Include include = null, string sourceFileName = "") { string errors = null; if (string.IsNullOrEmpty(shaderSource)) { throw new ArgumentNullException("shaderSource"); } var shaderSourcePtr = Marshal.StringToHGlobalAnsi(shaderSource); try { return Preprocess(shaderSourcePtr, shaderSource.Length, defines, include, out errors, sourceFileName); } finally { if (shaderSourcePtr != IntPtr.Zero) Marshal.FreeHGlobal(shaderSourcePtr); } }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <param name="secondaryDataFlags">The secondary data flags.</param> /// <param name="secondaryData">The secondary data.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(byte[] shaderSource, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown", SecondaryDataFlags secondaryDataFlags = SecondaryDataFlags.None, DataStream secondaryData = null) { return Compile(shaderSource, null, profile, shaderFlags, effectFlags, defines, include, sourceFileName, secondaryDataFlags, secondaryData); }
/// <summary> /// Compiles a shader or effect from a file on disk. /// </summary> /// <param name="fileName">The name of the source file to compile.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult CompileFromFile(string fileName, string entryPoint, string profile, ShaderFlags shaderFlags = ShaderFlags.None, EffectFlags effectFlags = EffectFlags.None, ShaderMacro[] defines = null, Include include = null) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (profile == null) { throw new ArgumentNullException("profile"); } if (!File.Exists(fileName)) { throw new FileNotFoundException("Could not open the shader or effect file.", fileName); } return Compile(File.ReadAllText(fileName), entryPoint, profile, shaderFlags, effectFlags, PrepareMacros(defines), include, fileName); }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="shaderSource">A string containing the source of the shader or effect to compile.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <param name="secondaryDataFlags">The secondary data flags.</param> /// <param name="secondaryData">The secondary data.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(string shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown", SecondaryDataFlags secondaryDataFlags = SecondaryDataFlags.None, DataStream secondaryData = null) { if (string.IsNullOrEmpty(shaderSource)) { throw new ArgumentNullException("shaderSource"); } var shaderSourcePtr = Marshal.StringToHGlobalAnsi(shaderSource); try { return Compile(shaderSourcePtr, shaderSource.Length, entryPoint, profile, shaderFlags, effectFlags, defines, include, sourceFileName, secondaryDataFlags, secondaryData); } finally { if (shaderSourcePtr != IntPtr.Zero) Marshal.FreeHGlobal(shaderSourcePtr); } }
public void Evaluate(int SpreadMax) { this.shaderupdated = false; this.spmax = this.CalculateSpreadMax(); if (FShaderCode.IsChanged || FFileName.IsChanged || FInDefines.IsChanged) { List <ShaderMacro> sms = new List <ShaderMacro>(); for (int i = 0; i < this.FInDefines.SliceCount; i++) { try { string[] s = this.FInDefines[i].Split("=".ToCharArray()); if (s.Length == 2) { ShaderMacro sm = new ShaderMacro(); sm.Name = s[0]; sm.Value = s[1]; sms.Add(sm); } } catch { } } DX11ShaderInclude FIncludeHandler = new DX11ShaderInclude(); FIncludeHandler.ParentPath = Path.GetDirectoryName(FFileName[0]); FShader = DX11Effect.FromString(FShaderCode[0], FIncludeHandler, sms.ToArray()); if (init && !ShaderCreatedByConfig) { this.SetShader(FShader, true); init = false; } else { this.SetShader(FShader, false); } // Write Shadercode & Defines into config -> needed to restore dynamic pins if (HasDynamicPins(FShader)) { configWritten = true; if (FConfigShader[0] != FShaderCode[0]) { FConfigShader[0] = FShaderCode[0]; FConfigDefines[0] = ""; for (int i = 0; i < FInDefines.SliceCount; i++) { if (i != 0) { FConfigDefines[0] += ","; } FConfigDefines[0] += this.FInDefines[i]; } } } else { if (FConfigShader[0] != "") { FConfigShader[0] = ""; FConfigDefines[0] = ""; } } } if (FShader.TechniqueNames != null && this.FInTechnique.IsChanged && FInTechnique.SliceCount > 0) { this.techniqueindex = Array.IndexOf(FShader.TechniqueNames, FInTechnique[0].Name); this.techniquechanged = true; } float *src; //Cache world pointer this.FInWorld.GetMatrixPointer(out this.mworldcount, out src); this.mworld = (Matrix *)src; this.FOutLayer.SliceCount = 1; if (this.FOutLayer[0] == null) { this.FOutLayer[0] = new DX11Resource <DX11Layer>(); } if (this.FInvalidate) { if (this.FShader.IsCompiled) { this.FOutCompiled[0] = true; this.FOutTechniqueValid.SliceCount = this.FShader.TechniqueValids.Length; for (int i = 0; i < this.FShader.TechniqueValids.Length; i++) { this.FOutTechniqueValid[i] = this.FShader.TechniqueValids[i]; } } else { this.FOutCompiled[0] = false; this.FOutTechniqueValid.SliceCount = 0; } this.FInvalidate = false; } if (this.FOutQueryable[0] == null) { this.FOutQueryable[0] = this; } }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="sourceFileName">Name of the source file used for reporting errors. Default is "unknown"</param> /// <param name="secondaryDataFlags">The secondary data flags.</param> /// <param name="secondaryData">The secondary data.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(byte[] shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown", SecondaryDataFlags secondaryDataFlags = SecondaryDataFlags.None, DataStream secondaryData = null) { unsafe { fixed (void* pData = &shaderSource[0]) return Compile( (IntPtr)pData, shaderSource.Length, entryPoint, profile, shaderFlags, effectFlags, defines, include, sourceFileName, secondaryDataFlags, secondaryData); } }
private static void CompileShader(ShaderWrapper shader, Device device) { // hack to add includes to list to allow easy reloading after include has changed... m_CurrentlyProcessedShader = shader; bool done = false; while (!done) { try { var defines = new ShaderMacro[shader.m_Defines.Count]; int counter = 0; foreach (var define in shader.m_Defines) { defines[counter++] = new ShaderMacro(define, "1"); } switch (shader.m_ShaderType) { case ShaderType.PixelShader: using (var bytecode = ShaderBytecode.CompileFromFile(shader.m_FilePath, shader.m_ShaderEntry, "ps_5_0", ShaderFlags.WarningsAreErrors, EffectFlags.None, defines, m_Include)) shader.m_PixelShader = new PixelShader(device, bytecode); break; case ShaderType.ComputeShader: using (var bytecode = ShaderBytecode.CompileFromFile(shader.m_FilePath, shader.m_ShaderEntry, "cs_5_0", ShaderFlags.WarningsAreErrors, EffectFlags.None, defines, m_Include)) shader.m_ComputeShader = new ComputeShader(device, bytecode); break; case ShaderType.GeometryShader: using (var bytecode = ShaderBytecode.CompileFromFile(shader.m_FilePath, shader.m_ShaderEntry, "gs_5_0", ShaderFlags.WarningsAreErrors, EffectFlags.None, defines, m_Include)) shader.m_GeometryShader = new GeometryShader(device, bytecode); break; case ShaderType.VertexShader: using (var bytecode = ShaderBytecode.CompileFromFile(shader.m_FilePath, shader.m_ShaderEntry, "vs_5_0", ShaderFlags.WarningsAreErrors, EffectFlags.None, defines, m_Include)) { shader.m_VertexInputSignature = ShaderSignature.GetInputSignature(bytecode); shader.m_VertexShader = new VertexShader(device, bytecode); } break; } done = true; } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message, "Shader compilation error"); } } m_CurrentlyProcessedShader = null; if (m_Shaders.ContainsKey(shader.m_ShaderName)) { m_Shaders[shader.m_ShaderName] = shader; } else { m_Shaders.Add(shader.m_ShaderName, shader); } }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="textSource">The shader data.</param> /// <param name="textSize">Size of the shader.</param> /// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="sourceFileName">Name of the source file used for reporting errors. Default is "unknown"</param> /// <param name="secondaryDataFlags">The secondary data flags.</param> /// <param name="secondaryData">The secondary data.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(IntPtr textSource, int textSize, string entryPoint, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown", SecondaryDataFlags secondaryDataFlags = SecondaryDataFlags.None, DataStream secondaryData = null) { unsafe { var resultCode = Result.Ok; Blob blobForCode = null; Blob blobForErrors = null; try { D3D.Compile2( (IntPtr)textSource, textSize, sourceFileName, PrepareMacros(defines), IncludeShadow.ToIntPtr(include), entryPoint, profile, shaderFlags, effectFlags, secondaryDataFlags, secondaryData != null ? secondaryData.DataPointer : IntPtr.Zero, secondaryData != null ? (int)secondaryData.Length : 0, out blobForCode, out blobForErrors); } catch (SharpDXException ex) { if (blobForErrors != null) { resultCode = ex.ResultCode; if (Configuration.ThrowOnShaderCompileError) throw new CompilationException(ex.ResultCode, Utilities.BlobToString(blobForErrors)); } else { throw; } } return new CompilationResult(blobForCode != null ? new ShaderBytecode(blobForCode) : null, resultCode, Utilities.BlobToString(blobForErrors)); } }
private static void CompileShader(ShaderWrapper shader) { bool done = false; bool acquiredLock = false; while (!done) { try { var defines = new ShaderMacro[shader.m_Defines.Count]; int counter = 0; foreach (var define in shader.m_Defines) { defines[counter++] = new ShaderMacro(define, "1"); } string profile = ""; switch (shader.m_ShaderType) { case ShaderType.PixelShader: profile = "ps_5_0"; break; case ShaderType.ComputeShader: profile = "cs_5_0"; break; case ShaderType.GeometryShader: profile = "gs_5_0"; break; case ShaderType.VertexShader: profile = "vs_5_0"; break; } shader.m_ShaderBytecode = ShaderBytecode.CompileFromFile(shader.m_ShaderFile.m_FilePath, shader.m_ShaderEntry, profile, ShaderFlags.WarningsAreErrors, EffectFlags.None, defines, m_Include); done = true; } catch (Exception e) { // if error - we need to enter synchronized state if (!acquiredLock) { System.Threading.Monitor.TryEnter(m_Lock, ref acquiredLock); } // if we are first to aquire lock - show message box, allowing user to fix shader if (acquiredLock) { System.Windows.Forms.MessageBox.Show(e.Message, "Shader compilation error"); } else { // otherwise just enter without showing mb, will retry compilation after first shader is fixed System.Threading.Monitor.Enter(m_Lock, ref acquiredLock); } } } if (acquiredLock) { System.Threading.Monitor.Exit(m_Lock); } }
/// <summary> /// Compiles the provided shader or effect source. /// </summary> /// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param> /// <param name="profile">The shader target or set of shader features to compile against.</param> /// <param name="shaderFlags">Shader compilation options.</param> /// <param name="effectFlags">Effect compilation options.</param> /// <param name="defines">A set of macros to define during compilation.</param> /// <param name="include">An interface for handling include files.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <returns> /// The compiled shader bytecode, or <c>null</c> if the method fails. /// </returns> public static CompilationResult Compile(byte[] shaderSource, string profile, ShaderFlags shaderFlags, EffectFlags effectFlags, ShaderMacro[] defines, Include include, string sourceFileName = "unknown") { return Compile(shaderSource, null, profile, shaderFlags, effectFlags, defines, include, sourceFileName); }
/// <summary> /// Preprocesses the provided shader or effect source. /// </summary> /// <param name = "shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param> /// <param name = "defines">A set of macros to define during preprocessing.</param> /// <param name = "include">An interface for handling include files.</param> /// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param> /// <returns>The preprocessed shader source.</returns> public static string Preprocess(byte[] shaderSource, ShaderMacro[] defines, Include include, out string compilationErrors, string sourceFileName = "") { unsafe { fixed (void* pData = &shaderSource[0]) return Preprocess((IntPtr)pData, shaderSource.Length, defines, include, out compilationErrors, sourceFileName); } }
internal static void Compile(ShaderBytecodeId bytecode, bool invalidateCache = false) { var info = Shaders[bytecode]; var path = Path.Combine(MyFileSystem.ContentPath, MyShadersDefines.ShadersContentPath, info.File.ToString()); if (!File.Exists(path)) { string message = "ERROR: Shaders Compile - can not find file: " + path; MyRender11.Log.WriteLine(message); throw new MyRenderException(message, MyRenderExceptionEnum.Unassigned); } ShaderMacro[] macros = MyRender11.GlobalShaderMacro; if (info.Macros != null && info.Macros.Length > 0 || MyRender11.DebugMode) { macros = new ShaderMacro[MyRender11.GlobalShaderMacro.Length + (info.Macros != null ? info.Macros.Length : 0)]; MyRender11.GlobalShaderMacro.CopyTo(macros, 0); if (info.Macros != null) info.Macros.CopyTo(macros, MyRender11.GlobalShaderMacro.Length); } string shaderSource; using (var reader = new StreamReader(path)) { shaderSource = reader.ReadToEnd(); } var compiled = Compile(shaderSource, macros, info.Profile, info.File.ToString(), false); Bytecodes.Data[bytecode.Index].Bytecode = compiled ?? Bytecodes.Data[bytecode.Index].Bytecode; if (compiled == null) { string message = "Failed to compile " + info.File + " @ profile " + info.Profile + " with defines " + macros.GetString(); MyRender11.Log.WriteLine(message); if (Debugger.IsAttached) { Compile(bytecode, true); } else throw new MyRenderException(message, MyRenderExceptionEnum.Unassigned); } }