diff options
| author | Jean-Philippe Bruyère <jp_bruyere@hotmail.com> | 2019-08-30 06:53:00 +0200 |
|---|---|---|
| committer | Jean-Philippe Bruyère <jp_bruyere@hotmail.com> | 2019-08-30 06:53:00 +0200 |
| commit | 9d390ab1738507ee166ac519f3d7def15e698493 (patch) | |
| tree | f7061585bb49690746889ddbf51bbff6bda56cf4 | |
| parent | 7251cffba37990ad8f9f4f68c1e300e1d80acfa3 (diff) | |
distance field fonts, separate vkvg addon, debug
54 files changed, 1067 insertions, 1878 deletions
diff --git a/CVKL.Addons/Directory.Build.props b/CVKL.Addons/Directory.Build.props index 786764d..57d68f7 100644 --- a/CVKL.Addons/Directory.Build.props +++ b/CVKL.Addons/Directory.Build.props @@ -10,7 +10,6 @@ <Authors>Jean-Philippe Bruyère</Authors> <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IncludeDefaultNoneItems>false</IncludeDefaultNoneItems> @@ -35,7 +34,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="SpirVTasks" Version="0.1.8-beta" /> + <PackageReference Include="SpirVTasks" Version="0.1.9-beta" /> <PackageReference Include="Vulkan" Version="0.1.4" /> </ItemGroup> diff --git a/CVKL.Addons/DistanceFieldFont/BMChar.cs b/CVKL.Addons/DistanceFieldFont/BMChar.cs new file mode 100644 index 0000000..0667fc3 --- /dev/null +++ b/CVKL.Addons/DistanceFieldFont/BMChar.cs @@ -0,0 +1,49 @@ +// Copyright (c) 2019 Jean-Philippe Bruyère <jp_bruyere@hotmail.com> +// +// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) +using System; +namespace CVKL.DistanceFieldFont { + public struct BMChar { + public enum Channel { + Blue = 0x01, + Green = 0x02, + Red = 0x04, + Alpha = 0x08, + All = 0x0f + } + public uint id; + /// <summary> + /// The left position of the character image in the texture. + /// </summary> + public uint x; + public uint y; + /// <summary> + /// The width of the character image in the texture. + /// </summary> + public uint width; + /// <summary> + /// The height of the character image in the texture. + /// </summary> + public uint height; + /// <summary> + /// How much the current position should be offset when copying the image from the texture to the screen. + /// </summary> + public int xoffset; + /// <summary> + /// How much the current position should be offset when copying the image from the texture to the screen. + /// </summary> + public int yoffset; + /// <summary> + /// How much the current position should be advanced after drawing the character. + /// </summary> + public int xadvance; + /// <summary> + /// The texture page where the character image is found. + /// </summary> + public uint page; + /// <summary> + /// The texture channel where the character image is found (1 = blue, 2 = green, 4 = red, 8 = alpha, 15 = all channels). + /// </summary> + public Channel channel; + } +} diff --git a/CVKL.Addons/DistanceFieldFont/BMFont.cs b/CVKL.Addons/DistanceFieldFont/BMFont.cs new file mode 100644 index 0000000..e277517 --- /dev/null +++ b/CVKL.Addons/DistanceFieldFont/BMFont.cs @@ -0,0 +1,207 @@ +// Copyright (c) 2019 Jean-Philippe Bruyère <jp_bruyere@hotmail.com> +// +// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using VK; + +namespace CVKL.DistanceFieldFont { + /// <summary> + /// BMF font. (http://www.angelcode.com/products/bmfont/doc/file_format.html) + /// </summary> + public class BMFont { + /// <summary> + /// distance in pixels between each line of text. + /// </summary> + public readonly ushort lineHeight; + /// <summary> + /// The number of pixels from the absolute top of the line to the base of the characters. + /// </summary> + public readonly ushort @base; + public readonly ushort width, height; + + public readonly Dictionary<int, BMChar> CharMap = new Dictionary<int, BMChar> (); + public readonly Dictionary<int, string> PageImagePathes = new Dictionary<int, string> (); + + readonly string fntFilePath; + + public BMFont (string path) { + fntFilePath = path; + object thisFont = this; + + + using (BMFontStreamReader bmf = new BMFontStreamReader (path)) { + while (!bmf.EndOfStream) { + + string w = bmf.ReadWord (); + if (string.IsNullOrEmpty (w)) + continue; + + if (string.Equals (w, "info", StringComparison.OrdinalIgnoreCase) || + string.Equals (w, "common", StringComparison.OrdinalIgnoreCase)) + bmf.ReadDatas (ref thisFont); + else if (string.Equals (w, "page", StringComparison.OrdinalIgnoreCase)) { + int p = bmf.ReadPageDatas (out string pageImg); + PageImagePathes.Add (p, pageImg); + } else if (string.Equals (w, "chars", StringComparison.OrdinalIgnoreCase)) + bmf.ReadLine ();//skip char count + else if (string.Equals (w, "char", StringComparison.OrdinalIgnoreCase)) { + BMChar c = bmf.NextBMChar; + CharMap.Add ((int)c.id, c); + } else if (string.Equals (w, "kernings", StringComparison.OrdinalIgnoreCase)) + bmf.ReadLine ();//skip + else if (string.Equals (w, "kerning", StringComparison.OrdinalIgnoreCase)) + bmf.ReadLine ();//skip + } + } + } + + public Image GetPageTexture (int page, Queue staggingQ, CommandPool cmdPool, + VkMemoryPropertyFlags imgProp = VkMemoryPropertyFlags.DeviceLocal, bool genMipMaps = true, VkImageTiling tiling = VkImageTiling.Optimal) { + + string path = Path.Combine (Path.GetDirectoryName (fntFilePath), PageImagePathes[page]); + + if (path.EndsWith ("ktx", StringComparison.OrdinalIgnoreCase)) + return KTX.KTX.Load (staggingQ, cmdPool, path, + VkImageUsageFlags.Sampled, imgProp, genMipMaps, tiling); + return Image.Load (staggingQ.Dev, staggingQ, cmdPool, path, VkFormat.R8g8b8a8Unorm, imgProp, tiling, genMipMaps); + } + + } + + + + internal class BMFontStreamReader : StreamReader { + public BMFontStreamReader (string bmPath) : base (bmPath) { } + + public char PeekedChar => (char)Peek (); + public char ReadedChar => (char)Read (); + public bool EndOfLine => PeekedChar == '\n'; + + public string ReadWord () { + string word = ""; + SkipWhiteSpacesAndLineBreak (); + while (!EndOfStream) { + if (!Char.IsLetterOrDigit (PeekedChar)) + break; + word += ReadedChar; + } + return word; + } + public void SkipWhiteSpaces () { + while (!EndOfStream) { + if (!char.IsWhiteSpace (PeekedChar) || PeekedChar == '\n') + break; + Read (); + } + } + public void SkipWhiteSpacesAndLineBreak () { + while (!EndOfStream) { + if (!char.IsWhiteSpace (PeekedChar)) + break; + Read (); + } + } + + public string NextValue { + get { + SkipWhiteSpaces (); + if (ReadedChar != '=') + throw new Exception ("expecting '='"); + SkipWhiteSpaces (); + if (PeekedChar == '"') { + Read (); + return ReadUntil ('"'); + } + return ReadUntilSpace (); + } + } + public string ReadUntil (char limit) { + string word = ""; + while (!EndOfStream) { + char c = ReadedChar; + if (c == limit) + break; + word += c; + } + return word; + } + public string ReadUntilSpace () { + string word = ""; + while (!EndOfStream) { + if (char.IsWhiteSpace (PeekedChar)) + break; + word += ReadedChar; + } + return word; + } + + public void ReadField (ref object obj, string fieldName) { + FieldInfo fi = obj.GetType ().GetField (fieldName); + if (fi == null) { + System.Diagnostics.Debug.WriteLine ($"BMFont property not handled: {fieldName}"); + string tmp = NextValue; + return; + } + if (fi.FieldType == typeof (ushort)) { + fi.SetValue (obj, ushort.Parse (NextValue)); + return; + } + if (fi.FieldType == typeof (short)) { + fi.SetValue (obj, short.Parse (NextValue)); + return; + } + if (fi.FieldType == typeof (int)) { + fi.SetValue (obj, int.Parse (NextValue)); + return; + } + if (fi.FieldType == typeof (uint)) { + fi.SetValue (obj, uint.Parse (NextValue)); + return; + } + if (fi.FieldType == typeof (string)) { + fi.SetValue (obj, NextValue); + return; + } + } + public void ReadDatas (ref object obj) { + while (!EndOfLine && !EndOfStream) { + string field = ReadWord (); + ReadField (ref obj, field); + } + + } + public int ReadPageDatas (out string pageImgPath) { + int idx = 0; + pageImgPath = ""; + + while (!EndOfLine && !EndOfStream) { + string field = ReadWord (); + if (string.Equals (field, "id", StringComparison.OrdinalIgnoreCase)) + idx = int.Parse (NextValue); + else if (string.Equals (field, "file", StringComparison.OrdinalIgnoreCase)) + pageImgPath = NextValue; + else + Console.WriteLine ($"BMFont page property not handled: {field} = {NextValue}"); + } + return idx; + } + public BMChar NextBMChar { + get { + object c = default (BMChar); + + while (!EndOfLine && !EndOfStream) { + string field = ReadWord (); + ReadField (ref c, field); + SkipWhiteSpaces ();//trailing spaces + } + + return (BMChar)c; + } + + } + } + +} diff --git a/CVKL.Addons/DistanceFieldFont/DistanceFieldFont.csproj b/CVKL.Addons/DistanceFieldFont/DistanceFieldFont.csproj new file mode 100644 index 0000000..a131f27 --- /dev/null +++ b/CVKL.Addons/DistanceFieldFont/DistanceFieldFont.csproj @@ -0,0 +1,20 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <Import Project="$(RootDirectory)netfx.props" /> + <PropertyGroup> + <AssemblyName>CVKL.DistanceFieldFont</AssemblyName> + <PackageId>CVKL.DistanceFieldFont</PackageId> + <AssemblyVersion>0.1.0</AssemblyVersion> + <Description>CVKL signed distance field font addons, BMFont file format</Description> + <PackageTags>C# vulkan CVKL gltf</PackageTags> + <PackageVersion>$(AssemblyVersion)-beta</PackageVersion> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <PackageRequireLicenseAcceptance>False</PackageRequireLicenseAcceptance> + <PackageProjectUrl>https://github.com/jpbruyere/vk.net/blob/master/README.md</PackageProjectUrl> + <License>MIT</License> + <PackageReleaseNotes></PackageReleaseNotes> + <SynchReleaseVersion>false</SynchReleaseVersion> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + +</Project> diff --git a/CVKL.Addons/VkvgPipeline/VkvgPipeline.cs b/CVKL.Addons/VkvgPipeline/VkvgPipeline.cs new file mode 100644 index 0000000..037254b --- /dev/null +++ b/CVKL.Addons/VkvgPipeline/VkvgPipeline.cs @@ -0,0 +1,135 @@ +// Copyright (c) 2019 Jean-Philippe Bruyère <jp_bruyere@hotmail.com> +// +// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) +using System; +using System.Numerics; +using CVKL; +using VK; + +namespace VkvgPipeline { + + public class VkvgPipeline : GraphicPipeline { + vkvg.Device vkvgDev; + vkvg.Surface vkvgSurf; + Image uiImage; + + public vkvg.Context CreateContext () => new vkvg.Context (vkvgSurf); + + public VkvgPipeline (Instance instance, Device dev, Queue queue, GraphicPipeline pipeline, PipelineCache pipelineCache = null) + : base (pipeline.RenderPass, pipelineCache, "vkvg pipeline") { + + GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault (VkPrimitiveTopology.TriangleList, this.RenderPass.Samples, false); + cfg.RenderPass = RenderPass; + cfg.Layout = pipeline.Layout; + cfg.AddShader (VkShaderStageFlags.Vertex, "#CVKL.FullScreenQuad.vert.spv"); + cfg.AddShader (VkShaderStageFlags.Fragment, "#CVKL.simpletexture.frag.spv"); + cfg.multisampleState.rasterizationSamples = Samples; + + cfg.blendAttachments[0] = new VkPipelineColorBlendAttachmentState (true); + + layout = cfg.Layout; + + init (cfg); + + vkvgDev = new vkvg.Device (instance.Handle, dev.phy.Handle, dev.VkDev.Handle, queue.qFamIndex, + vkvg.SampleCount.Sample_4, queue.index); + } + + void initUISurface (int width, int height) { + uiImage?.Dispose (); + vkvgSurf?.Dispose (); + vkvgSurf = new vkvg.Surface (vkvgDev, width, height); + uiImage = new Image (Dev, new VkImage ((ulong)vkvgSurf.VkImage.ToInt64 ()), VkFormat.B8g8r8a8Unorm, + VkImageUsageFlags.ColorAttachment, (uint)vkvgSurf.Width, (uint)vkvgSurf.Height); + uiImage.CreateView (VkImageViewType.ImageView2D, VkImageAspectFlags.Color); + uiImage.CreateSampler (VkFilter.Nearest, VkFilter.Nearest, VkSamplerMipmapMode.Nearest, VkSamplerAddressMode.ClampToBorder); + uiImage.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; + } + + + public void Resize (int width, int height, DescriptorSetWrites dsUpdate) { + initUISurface (width, height); + dsUpdate.Write (Dev, uiImage.Descriptor); + } + public void RecordDraw (CommandBuffer cmd) { + Bind (cmd); + + uiImage.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.ColorAttachmentOptimal, VkImageLayout.ShaderReadOnlyOptimal, + VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.FragmentShader); + + cmd.Draw (3, 1, 0, 0); + + uiImage.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.ShaderReadOnlyOptimal, VkImageLayout.ColorAttachmentOptimal, + VkPipelineStageFlags.FragmentShader, VkPipelineStageFlags.BottomOfPipe); + } + public void DrawResources (vkvg.Context ctx, int width, int height) { + ResourceManager rm = Dev.resourceManager; + + int margin = 5, memPoolHeight = 15; + int drawingWidth = width - 4 * margin; + int drawingHeight = (memPoolHeight + margin) * (rm.memoryPools.Length) + margin; + int y = height - drawingHeight - margin; + int x = 2 * margin; + ctx.LineWidth = 1; + ctx.SetSource (0.1, 0.1, 0.1, 0.8); + ctx.Rectangle (0.5 + margin, 0.5 + y, width - 2 * margin, drawingHeight); + ctx.FillPreserve (); + ctx.Flush (); + ctx.SetSource (0.8, 0.8, 0.8); + ctx.Stroke (); + + foreach (MemoryPool mp in rm.memoryPools) { + float byteWidth = (float)drawingWidth / mp.Size; + + y += margin; + ctx.Rectangle (x, y, drawingWidth, memPoolHeight); + ctx.SetSource (0.3, 0.3, 0.3, 0.4); + ctx.Fill (); + + if (mp.Last == null) + return; + + Resource r = mp.Last; + do { + float w = Math.Max (1f, byteWidth * r.AllocatedDeviceMemorySize); + + Vector3 c = new Vector3 (0); + Image img = r as Image; + if (img != null) { + c.Z = 1f; + if (img.CreateInfo.usage.HasFlag (VkImageUsageFlags.InputAttachment)) + c.Y += 0.3f; + if (img.CreateInfo.usage.HasFlag (VkImageUsageFlags.ColorAttachment)) + c.Y += 0.1f; + if (img.CreateInfo.usage.HasFlag (VkImageUsageFlags.Sampled)) + c.X += 0.3f; + } else { + CVKL.Buffer buff = r as CVKL.Buffer; + c.X = 1f; + if (buff.Infos.usage.HasFlag (VkBufferUsageFlags.IndexBuffer)) + c.Y += 0.2f; + if (buff.Infos.usage.HasFlag (VkBufferUsageFlags.VertexBuffer)) + c.Y += 0.4f; + if (buff.Infos.usage.HasFlag (VkBufferUsageFlags.UniformBuffer)) + c.Z += 0.3f; + } + ctx.SetSource (c.X, c.Y, c.Z, 0.5); + ctx.Rectangle (0.5f + x + byteWidth * r.poolOffset, 0.5f + y, w, memPoolHeight); + ctx.FillPreserve (); + ctx.SetSource (0.01f, 0.01f, 0.01f); + ctx.Stroke (); + r = r.next; + } while (r != mp.Last && r != null); + y += memPoolHeight; + } + } + protected override void Dispose (bool disposing) { + uiImage?.Dispose (); + vkvgSurf?.Dispose (); + vkvgDev.Dispose (); + + base.Dispose (disposing); + } + } + +} diff --git a/CVKL.Addons/VkvgPipeline/VkvgPipeline.csproj b/CVKL.Addons/VkvgPipeline/VkvgPipeline.csproj new file mode 100644 index 0000000..3d07598 --- /dev/null +++ b/CVKL.Addons/VkvgPipeline/VkvgPipeline.csproj @@ -0,0 +1,23 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <Import Project="$(RootDirectory)netfx.props" /> + <PropertyGroup> + <AssemblyName>CVKL.vkvgPipeline</AssemblyName> + <PackageId>CVKL.vkvgPipeline</PackageId> + <AssemblyVersion>0.1.0</AssemblyVersion> + <Description>CVKL vkvg addons, vectorial drawing with cairo like api.</Description> + <PackageTags>C# vulkan CVKL gltf</PackageTags> + <PackageVersion>$(AssemblyVersion)-beta</PackageVersion> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <PackageRequireLicenseAcceptance>False</PackageRequireLicenseAcceptance> + <PackageProjectUrl>https://github.com/jpbruyere/vk.net/blob/master/README.md</PackageProjectUrl> + <License>MIT</License> + <PackageReleaseNotes></PackageReleaseNotes> + <SynchReleaseVersion>false</SynchReleaseVersion> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="vkvg.net" Version="0.2.2-beta" /> + </ItemGroup> +</Project> diff --git a/CVKL.Addons/gltfLoader/Program.cs b/CVKL.Addons/gltfLoader/Program.cs deleted file mode 100644 index 6a0cfcd..0000000 --- a/CVKL.Addons/gltfLoader/Program.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace gltfLoader { - class Program { - static void Main (string[] args) { - Console.WriteLine ("Hello World!"); - } - } -} diff --git a/SpirVTasks/CompileGLSLTask.cs b/SpirVTasks/CompileGLSLTask.cs index c2d1a7e..cac29fc 100644 --- a/SpirVTasks/CompileGLSLTask.cs +++ b/SpirVTasks/CompileGLSLTask.cs @@ -156,7 +156,7 @@ namespace SpirVTasks { glslc.BeginErrorReadLine (); glslc.BeginOutputReadLine (); - Log.LogMessage (MessageImportance.High, $"{SourceFile.ItemSpec} -> {DestinationFile.ItemSpec}"); + DestinationFile.SetMetadata ("LogicalName", $"FromCS.{SourceFile.ItemSpec.Replace (Path.DirectorySeparatorChar, '.')}"); glslc.WaitForExit (); @@ -175,8 +175,8 @@ namespace SpirVTasks { Log.LogMessage (MessageImportance.High, $"glslc: {e.Data}"); if (tmp.Length == 5) { - string srcFile = BuildEngine.ProjectFileOfTaskNode; - int line = int.Parse (tmp[1]); + string srcFile = SourceFile.ItemSpec; + int line = Math.Max (0, int.Parse (tmp[1]) - 1); BuildErrorEventArgs err = new BuildErrorEventArgs ("compile", tmp[2], srcFile, line, 0, 0, 0, $"{tmp[3]} {tmp[4]}", "no help", "SpirVTasks"); BuildEngine.LogErrorEvent (err); diff --git a/SpirVTasks/README.md b/SpirVTasks/README.md index e1278a3..7b2fdb4 100644 --- a/SpirVTasks/README.md +++ b/SpirVTasks/README.md @@ -12,7 +12,7 @@ </h1> **SpirVTasks** package add **SpirV** compilation support to msbuild project. Error and warning -are transmited to the **IDE**. Resulting `.spv` files will be embedded with the resource ID = ProjectName.file.ext.spv. +are transmited to the **IDE**. Add glsl files to your project with the **`<GLSLShader>`** tag. @@ -22,7 +22,17 @@ Add glsl files to your project with the **`<GLSLShader>`** tag. </ItemGroup> ``` -The add-on will search for **glslc** executable with the **VULKAN_SDK** or **PATH** environments variables. +Resulting `.spv` files will be embedded with the resource ID = ProjectName.file.ext.spv. +You can override the resource name by adding a **`<LogicalName>`** element. + +```xml +<ItemGroup> + <GLSLShader Include="shaders\skybox.vert"> + <LogicalName>NewName.vert.spv</LogicalName> + </GLSLShader> +</ItemGroup> +``` +**glslc** executable is searched with the help of the **VULKAN_SDK** or **PATH** environments variables. You may also point to glslc with the **`<SpirVglslcPath>`** property (>= 0.1.7), but if the property is set. ```xml diff --git a/SpirVTasks/SpirVTasks.csproj b/SpirVTasks/SpirVTasks.csproj index f9fa944..314ddc7 100644 --- a/SpirVTasks/SpirVTasks.csproj +++ b/SpirVTasks/SpirVTasks.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net471;netstandard2.0</TargetFrameworks> - <AssemblyVersion>0.1.8</AssemblyVersion> + <AssemblyVersion>0.1.9</AssemblyVersion> <Description>MSBuild addon to compile and embed spirV shaders</Description> <PackageId>SpirVTasks</PackageId> diff --git a/SpirVTasks/SpirVTasks.targets b/SpirVTasks/SpirVTasks.targets index a6e2a06..6825c47 100644 --- a/SpirVTasks/SpirVTasks.targets +++ b/SpirVTasks/SpirVTasks.targets @@ -11,19 +11,20 @@ AdditionalIncludeDirectories="$(SpirVAdditionalIncludeDirectories)" TempDirectory="$(IntermediateOutputPath)" DestinationFile="$(IntermediateOutputPath)%(RelativeDir)%(Filename)%(Extension).spv" /> - <CreateItem - Include="$(IntermediateOutputPath)%(GLSLShader.RelativeDir)%(Filename)%(Extension).spv"> + <CreateItem Condition=" '%(GLSLShader.LogicalName)'!='' " + Include="$(IntermediateOutputPath)%(RelativeDir)%(Filename)%(Extension).spv" + AdditionalMetadata="LogicalName=%(GLSLShader.LogicalName)"> <Output - TaskParameter="Include" - ItemName="EmbeddedResource"/> + TaskParameter="Include" + ItemName="EmbeddedResource"/> + </CreateItem> + <CreateItem Condition=" '%(GLSLShader.LogicalName)'=='' " + Include="$(IntermediateOutputPath)%(RelativeDir)%(Filename)%(Extension).spv" + AdditionalMetadata="LogicalName=$(AssemblyName).%(GLSLShader.Filename)%(Extension).spv"> + <Output + TaskParameter="Include" + ItemName="EmbeddedResource"/> </CreateItem> - <Message Importance="High" Text="Embedding $(IntermediateOutputPath)%(GLSLShader.RelativeDir)%(Filename)%(Extension).spv" /> - </Target> - <Target Name="ModifyEmbeddedResourceNames" AfterTargets="CompileShaders"> - <ItemGroup> - <EmbeddedResource> - <LogicalName>$(AssemblyName).%(EmbeddedResource.Filename)%(Extension)</LogicalName> - </EmbeddedResource> - </ItemGroup> + <Message Importance="High" Text="%(GLSLShader.Identity) -> $(AssemblyName).%(Filename)%(Extension).spv (Embedded Resource)" /> </Target> </Project> diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props index 6a8fdd3..dc4c42e 100644 --- a/samples/Directory.Build.props +++ b/samples/Directory.Build.props @@ -33,7 +33,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="SpirVTasks" Version="0.1.8-beta" /> + <PackageReference Include="SpirVTasks" Version="0.1.9-beta" /> <PackageReference Include="Vulkan" Version="0.1.4" /> </ItemGroup> diff --git a/samples/hdr/hdr.csproj b/samples/DistanceFieldFontTest/DistanceFieldFontTest.csproj index f4c1c6b..e16b3e1 100644 --- a/samples/hdr/hdr.csproj +++ b/samples/DistanceFieldFontTest/DistanceFieldFontTest.csproj @@ -1,6 +1,9 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> <ItemGroup> + <ProjectReference Include="..\..\CVKL.Addons\DistanceFieldFont\DistanceFieldFont.csproj" /> + </ItemGroup> + <ItemGroup> <Folder Include="shaders\" /> </ItemGroup> </Project> diff --git a/samples/DistanceFieldFontTest/Program.cs b/samples/DistanceFieldFontTest/Program.cs new file mode 100644 index 0000000..7d9ce45 --- /dev/null +++ b/samples/DistanceFieldFontTest/Program.cs @@ -0,0 +1,300 @@ +using System.Collections.Generic; +using System.Numerics; +using System.Runtime.InteropServices; +using Glfw; + +using VK; +using CVKL; +using CVKL.DistanceFieldFont; + +namespace DistanceFieldFontTest { + + + + class Program : VkWindow { + static void Main (string[] args) { +#if DEBUG + Instance.VALIDATION = true; + Instance.DEBUG_UTILS = true; + Instance.RENDER_DOC_CAPTURE = false; +#endif + using (Program vke = new Program ()) { + vke.Run (); + } + } + + float rotSpeed = 0.01f, zoomSpeed = 0.01f; + float rotX, rotY, rotZ = 0f, zoom = 1f; + + struct Matrices { + public Matrix4x4 projection; + public Matrix4x4 view; + public Matrix4x4 model; + } + + Matrices matrices; + + HostBuffer uboMats; + GPUBuffer<float> vbo; + GPUBuffer<ushort> ibo; + + DescriptorPool descriptorPool; + DescriptorSetLayout dsLayout; + DescriptorSet descriptorSet; + + GraphicPipeline pipeline; + Framebuffer[] frameBuffers; + + Image fontTexture; + + struct Vertex { + public Vector3 pos; + public Vector2 uv; + public Vertex (float x, float y, float z, float u, float v) { + pos.X = x; pos.Y = y; pos.Z = z; + uv.X = u; uv.Y = v; + } + } + + BMFont font; + Vector4 textColor = new Vector4 (1.0f, 1.0f, 0.0f, 1.0f);//alpha => 0:disabled 1:enabled + Vector4 outlineColor = new Vector4 (1.0f, 0.0f, 0.0f, 0.6f);//alpha => 0:disabled 1:enabled + + Program () : base () { + + font = new BMFont ("../data/font.fnt"); + + vbo = new GPUBuffer<float> (dev, VkBufferUsageFlags.VertexBuffer, 1024); + ibo = new GPUBuffer<ushort> (dev, VkBufferUsageFlags.IndexBuffer, 2048); + + descriptorPool = new DescriptorPool (dev, 1, + new VkDescriptorPoolSize (VkDescriptorType.UniformBuffer), + new VkDescriptorPoolSize (VkDescriptorType.CombinedImageSampler) + ); + + dsLayout = new DescriptorSetLayout (dev, 0, + new VkDescriptorSetLayoutBinding (0, VkShaderStageFlags.Vertex, VkDescriptorType.UniformBuffer), + new VkDescriptorSetLayoutBinding (1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler)); + + GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault (VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount4, false); + + cfg.Layout = new PipelineLayout (dev, dsLayout); + cfg.Layout.AddPushConstants (new VkPushConstantRange (VkShaderStageFlags.Fragment, (uint)Marshal.SizeOf<Vector4> () * 2)); + + cfg.RenderPass = new RenderPass (dev, swapChain.ColorFormat, cfg.Samples); + + cfg.blendAttachments[0] = new VkPipelineColorBlendAttachmentState ( + true, VkBlendFactor.One, VkBlendFactor.OneMinusSrcAlpha, VkBlendOp.Add, VkBlendFactor.One, VkBlendFactor.Zero); + + cfg.AddVertexBinding (0, 5 * sizeof (float)); + cfg.AddVertexAttributes (0, VkFormat.R32g32b32Sfloat, VkFormat.R32g32Sfloat); + + cfg.AddShader (VkShaderStageFlags.Vertex, "#DistanceFieldFontTest.main.vert.spv"); + cfg.AddShader (VkShaderStageFlags.Fragment, "#DistanceFieldFontTest.main.frag.spv"); + + pipeline = new GraphicPipeline (cfg); + + uboMats = new HostBuffer (dev, VkBufferUsageFlags.UniformBuffer, matrices); + uboMats.Map ();//permanent map + + descriptorSet = descriptorPool.Allocate (dsLayout); + + fontTexture = font.GetPageTexture (0, presentQueue, cmdPool); + fontTexture.CreateView (); + fontTexture.CreateSampler (); + fontTexture.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; + + DescriptorSetWrites dsUpdate = new DescriptorSetWrites (descriptorSet, dsLayout); + dsUpdate.Write (dev, uboMats.Descriptor, fontTexture.Descriptor); + + generateText ("Vulkan", out HostBuffer<Vertex> staggingVbo, out HostBuffer<ushort> staggingIbo); + + CommandBuffer cmd = cmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); + + staggingVbo.CopyTo (cmd, vbo); + staggingIbo.CopyTo (cmd, ibo); + + presentQueue.EndSubmitAndWait (cmd); + + staggingVbo.Dispose (); + staggingIbo.Dispose (); + } + + + // Creates a vertex buffer containing quads for the passed text + void generateText (string text, out HostBuffer<Vertex> svbo, out HostBuffer<ushort> sibo) { + List<Vertex> vertices = new List<Vertex> (); + List<ushort> indices = new List<ushort> (); + ushort indexOffset = 0; + + float w = fontTexture.Width; + + float posx = 0.0f; + float posy = 0.0f; + + for (int i = 0; i < text.Length; i++) { + BMChar charInfo = font.CharMap[text[i]]; + + + if (charInfo.width == 0) + charInfo.width = 36; + + float charw = ((float)(charInfo.width) / 36.0f); + float dimx = 1.0f * charw; + float charh = ((float)(charInfo.height) / 36.0f); + float dimy = 1.0f * charh; + posy = 1.0f - charh; + + float us = charInfo.x / w; + float ue = (charInfo.x + charInfo.width) / w; + float ts = charInfo.y / w; + float te = (charInfo.y + charInfo.height) / w; + + float xo = charInfo.xoffset / 36.0f; + float yo = charInfo.yoffset / 36.0f; + + vertices.Add (new Vertex (posx + dimx + xo, posy + dimy, 0.0f, ue, te)); + vertices.Add (new Vertex (posx + xo, posy + dimy, 0.0f, us, te)); + vertices.Add (new Vertex (posx + xo, posy, 0.0f, us, ts)); + vertices.Add (new Vertex (posx + dimx + xo, posy, 0.0f, ue, ts)); + + indices.AddRange (new ushort[] { indexOffset, (ushort)(indexOffset + 1), (ushort)(indexOffset + 2), (ushort)(indexOffset + 2), (ushort)(indexOffset + 3), indexOffset }); + indexOffset += 4; + + float advance = charInfo.xadvance / 36.0f; + posx += advance; + } + + Vertex[] vx = vertices.ToArray (); + + // Center + for (int i = 0; i < vx.Length; i++) { + vx[i].pos.X -= posx / 2.0f; + vx[i].pos.Y -= 0.5f; + } + + svbo = new HostBuffer<Vertex> (dev, VkBufferUsageFlags.TransferSrc, vx); + sibo = new HostBuffer<ushort> (dev, VkBufferUsageFlags.TransferSrc, indices.ToArray()); + } + + bool rebuildBuffers; + + public override void Update () { + if (rebuildBuffers) { + buildCommandBuffers (); + rebuildBuffers = false; + } + } + + void buildCommandBuffers () { + for (int i = 0; i < swapChain.ImageCount; ++i) { + cmds[i]?.Free (); + cmds[i] = cmdPool.AllocateAndStart (); + + recordDraw (cmds[i], frameBuffers[i]); + + cmds[i].End (); + } + } + + void recordDraw (CommandBuffer cmd, Framebuffer fb) { + pipeline.RenderPass.Begin (cmd, fb); + + cmd.SetViewport (fb.Width, fb.Height); + cmd.SetScissor (fb.Width, fb.Height); + + cmd.BindPipeline (pipeline, descriptorSet); + + cmd.PushConstant (pipeline, textColor); + cmd.PushConstant (pipeline, outlineColor, 0, 16); + + cmd.BindVertexBuffer (vbo, 0); + cmd.BindIndexBuffer (ibo, VkIndexType.Uint16); + cmd.DrawIndexed ((uint)ibo.ElementCount,1,0,0,0); + + pipeline.RenderPass.End (cmd); + } + + + public override void UpdateView () { + matrices.projection = Matrix4x4.CreatePerspectiveFieldOfView (Utils.DegreesToRadians (60f), (float)swapChain.Width / (float)swapChain.Height, 0.1f, 256.0f); + matrices.view = Matrix4x4.CreateTranslation (0, 0, -2.5f * zoom); + matrices.model = + Matrix4x4.CreateFromAxisAngle (Vector3.UnitZ, rotZ) * + Matrix4x4.CreateFromAxisAngle (Vector3.UnitY, rotY) * + Matrix4x4.CreateFromAxisAngle (Vector3.UnitX, rotX); + + uboMats.Update (matrices, (uint)Marshal.SizeOf<Matrices> ()); + + updateViewRequested = false; + } + + protected override void onMouseMove (double xPos, double yPos) { + double diffX = lastMouseX - xPos; + double diffY = lastMouseY - yPos; + if (MouseButton[0]) { + rotY -= rotSpeed * (float)diffX; + rotX += rotSpeed * (float)diffY; + } else if (MouseButton[1]) { + zoom += zoomSpeed * (float)diffY; + } + + updateViewRequested = true; + } + + protected override void onKeyDown (Key key, int scanCode, Modifier modifiers) { + switch (key) { + case Key.F2: + if (modifiers.HasFlag (Modifier.Shift)) + outlineColor.W -= 0.01f; + else + outlineColor.W += 0.01f; + rebuildBuffers = true; + break; + default: + base.onKeyDown (key, scanCode, modifiers); + break; + } + } + protected override void OnResize () { + + updateViewRequested = true; + + if (frameBuffers != null) + for (int i = 0; i < swapChain.ImageCount; ++i) + frameBuffers[i]?.Dispose (); + + frameBuffers = new Framebuffer[swapChain.ImageCount]; + + for (int i = 0; i < swapChain.ImageCount; ++i) { + frameBuffers[i] = new Framebuffer (pipeline.RenderPass, swapChain.Width, swapChain.Height, + (pipeline.Samples == VkSampleCountFlags.SampleCount1) ? new Image[] { + swapChain.images[i], + } : new Image[] { + null, + swapChain.images[i] + }); + } + + buildCommandBuffers (); + } + + protected override void Dispose (bool disposing) { + if (disposing) { + if (!isDisposed) { + dev.WaitIdle (); + pipeline.Dispose (); + dsLayout.Dispose (); + for (int i = 0; i < swapChain.ImageCount; i++) + frameBuffers[i].Dispose (); + descriptorPool.Dispose (); + fontTexture?.Dispose (); + vbo.Dispose (); + ibo.Dispose (); + uboMats.Dispose (); + } + } + base.Dispose (disposing); + } + } +} diff --git a/samples/DistanceFieldFontTest/shaders/main.frag b/samples/DistanceFieldFontTest/shaders/main.frag new file mode 100644 index 0000000..fa1f6c6 --- /dev/null +++ b/samples/DistanceFieldFontTest/shaders/main.frag @@ -0,0 +1,32 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; + +layout (push_constant) uniform PushConsts { + vec4 color; + vec4 outlineColor; +}; + +layout (location = 0) in vec2 inUV; +layout (location = 0) out vec4 outFragColor; + +void main() +{ + float distance = texture(samplerColor, inUV).a; + float smoothWidth = fwidth(distance); + float alpha = smoothstep(0.5 - smoothWidth, 0.5 + smoothWidth, distance); + vec3 rgb = color.rgb * vec3(alpha); + + if (outlineColor.a > 0.0) + { + float w = 1.0 - outlineColor.a; + alpha = smoothstep(w - smoothWidth, w + smoothWidth, distance); + rgb += mix(vec3(alpha), outlineColor.rgb, alpha); + } + + outFragColor = vec4(rgb, alpha * color.a); + +}
\ No newline at end of file diff --git a/samples/hdr/shaders/main.vert b/samples/DistanceFieldFontTest/shaders/main.vert index 3b395bf..3b395bf 100644 --- a/samples/hdr/shaders/main.vert +++ b/samples/DistanceFieldFontTest/shaders/main.vert diff --git a/samples/Textured/main.cs b/samples/Textured/main.cs index b11cef9..4705a54 100644 --- a/samples/Textured/main.cs +++ b/samples/Textured/main.cs @@ -11,8 +11,12 @@ namespace Textured { #if DEBUG Instance.VALIDATION = true; Instance.DEBUG_UTILS = true; - Instance.RENDER_DOC_CAPTURE = false; + Instance.RENDER_DOC_CAPTURE = true; #endif + + foreach (string s in System.Reflection.Assembly.GetEntryAssembly ().GetManifestResourceNames ()) + Console.WriteLine (s); + using (Program vke = new Program ()) { vke.Run (); } @@ -59,7 +63,7 @@ namespace Textured { string[] imgPathes = { "/mnt/devel/vulkan/VulkanExamples/data/models/voyager/voyager_rgba_unorm.ktx", "/mnt/devel/vulkan/vulkanExUpstream/data/models/voyager/voyager_astc_8x8_unorm.ktx", - "../data/textures/rgba-reference.ktx", + "../data/font.ktx", "/mnt/devel/vulkan/vulkanExUpstream/data/textures/trail_astc_8x8_unorm.ktx", "../data/textures/texturearray_rocks_bc3_unorm.ktx", "../data/textures/texture.jpg", @@ -108,8 +112,8 @@ namespace Textured { } void buildCommandBuffers () { - for (int i = 0; i < swapChain.ImageCount; ++i) { - cmds[i]?.Free (); + for (int i = 0; i < swapChain.ImageCount; ++i) { + cmds[i]?.Free (); cmds[i] = cmdPool.AllocateAndStart (); recordDraw (cmds[i], frameBuffers[i]); diff --git a/samples/TexturedCube/TexturedCube.csproj b/samples/TexturedCube/TexturedCube.csproj index 5608d58..990df32 100644 --- a/samples/TexturedCube/TexturedCube.csproj +++ b/samples/TexturedCube/TexturedCube.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> - <Import Project="$(RootDirectory)netfx.props" /> + <Import Project="$(RootDirectory)netfx.props" /> <ItemGroup> - <PackageReference Include="vkvg.net" Version="0.2.2-beta" /> - </ItemGroup> + <ProjectReference Include="..\..\CVKL.Addons\VkvgPipeline\VkvgPipeline.csproj" /> + </ItemGroup> </Project> diff --git a/samples/TexturedCube/main.cs b/samples/TexturedCube/main.cs index 295334d..f05c72f 100644 --- a/samples/TexturedCube/main.cs +++ b/samples/TexturedCube/main.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) 2019 Jean-Philippe Bruyère <jp_bruyere@hotmail.com> +// +// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) +using System; using System.Numerics; using System.Runtime.InteropServices; using Glfw; @@ -33,7 +36,7 @@ namespace TextureCube { GPUBuffer<float> vbo; DescriptorPool descriptorPool; DescriptorSetLayout dsLayout; - DescriptorSet descriptorSet; + DescriptorSet descriptorSet, dsVkvg; GraphicPipeline pipeline; Framebuffer[] frameBuffers; @@ -94,121 +97,41 @@ namespace TextureCube { VkSampleCountFlags samples = VkSampleCountFlags.SampleCount1; - vkvg.Device vkvgDev; - vkvg.Surface vkvgSurf; - Image uiImage; - GraphicPipeline uiPipeline; - DescriptorSet dsVKVG; - - void initUISurface () { - uiImage?.Dispose (); - vkvgSurf?.Dispose (); - vkvgSurf = new vkvg.Surface (vkvgDev, (int)swapChain.Width, (int)swapChain.Height); - uiImage = new Image (dev, new VkImage ((ulong)vkvgSurf.VkImage.ToInt64 ()), VkFormat.B8g8r8a8Unorm, - VkImageUsageFlags.ColorAttachment, (uint)vkvgSurf.Width, (uint)vkvgSurf.Height); - uiImage.CreateView (VkImageViewType.ImageView2D, VkImageAspectFlags.Color); - uiImage.CreateSampler (VkFilter.Nearest, VkFilter.Nearest, VkSamplerMipmapMode.Nearest, VkSamplerAddressMode.ClampToBorder); - uiImage.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; - - DescriptorSetWrites uboUpdate = new DescriptorSetWrites (dsVKVG, dsLayout.Bindings[1]); - uboUpdate.Write (dev, uiImage.Descriptor); - } +#if WITH_VKVG + VkvgPipeline.VkvgPipeline vkvgPipeline; void vkvgDraw () { - using (vkvg.Context ctx = new vkvg.Context (vkvgSurf)) { + using (vkvg.Context ctx = vkvgPipeline.CreateContext()) { ctx.Operator = vkvg.Operator.Clear; ctx.Paint (); ctx.Operator = vkvg.Operator.Over; - - drawResources (ctx); + vkvgPipeline.DrawResources (ctx, (int)swapChain.Width, (int)swapChain.Height); } } - void drawResources (vkvg.Context ctx) { - ResourceManager rm = dev.resourceManager; - - int margin = 5, memPoolHeight=15; - int drawingWidth = (int)swapChain.Width - 4 * margin; - int drawingHeight = (memPoolHeight + margin) * (rm.memoryPools.Length) + margin; - int y = (int)swapChain.Height - drawingHeight - margin; - int x = 2 * margin; - ctx.LineWidth = 1; - ctx.SetSource (0.1, 0.1, 0.1, 0.8); - ctx.Rectangle (0.5+margin, 0.5+y, swapChain.Width - 2*margin, drawingHeight); - ctx.FillPreserve (); - ctx.Flush (); - ctx.SetSource (0.8, 0.8, 0.8); - ctx.Stroke (); - - - - foreach (MemoryPool mp in rm.memoryPools) { - float byteWidth = (float)drawingWidth / mp.Size; - y += margin; - ctx.Rectangle (x, y, drawingWidth, memPoolHeight); - ctx.SetSource (0.3, 0.3, 0.3, 0.4); - ctx.Fill (); - - if (mp.Last == null) - return; +#endif - Resource r = mp.Last; - do { - float width = Math.Max (1f, byteWidth * r.AllocatedDeviceMemorySize); - Vector3 c = new Vector3 (0); - Image img = r as Image; - if (img != null) { - c.Z = 1f; - if (img.CreateInfo.usage.HasFlag (VkImageUsageFlags.InputAttachment)) - c.Y += 0.3f; - if (img.CreateInfo.usage.HasFlag (VkImageUsageFlags.ColorAttachment)) - c.Y += 0.1f; - if (img.CreateInfo.usage.HasFlag (VkImageUsageFlags.Sampled)) - c.X += 0.3f; - } else { - CVKL.Buffer buff = r as CVKL.Buffer; - c.X = 1f; - if (buff.Infos.usage.HasFlag (VkBufferUsageFlags.IndexBuffer)) - c.Y += 0.2f; - if (buff.Infos.usage.HasFlag (VkBufferUsageFlags.VertexBuffer)) - c.Y += 0.4f; - if (buff.Infos.usage.HasFlag (VkBufferUsageFlags.UniformBuffer)) - c.Z += 0.3f; - } - ctx.SetSource (c.X, c.Y, c.Z, 0.5); - ctx.Rectangle (0.5f + x + byteWidth * r.poolOffset, 0.5f + y, width, memPoolHeight); - ctx.FillPreserve (); - ctx.SetSource (0.01f, 0.01f, 0.01f); - ctx.Stroke (); - r = r.next; - } while (r != mp.Last && r != null); - y += memPoolHeight; - } - } Program () : base () { - vkvgDev = new vkvg.Device (instance.Handle, phy.Handle, dev.VkDev.Handle, presentQueue.qFamIndex, - vkvg.SampleCount.Sample_4, presentQueue.index); - vbo = new GPUBuffer<float> (presentQueue, cmdPool, VkBufferUsageFlags.VertexBuffer, g_vertex_buffer_data); descriptorPool = new DescriptorPool (dev, 2, - new VkDescriptorPoolSize (VkDescriptorType.UniformBuffer,2), - new VkDescriptorPoolSize (VkDescriptorType.CombinedImageSampler,2) + new VkDescriptorPoolSize (VkDescriptorType.UniformBuffer, 2), + new VkDescriptorPoolSize (VkDescriptorType.CombinedImageSampler, 2) ); dsLayout = new DescriptorSetLayout (dev, 0, new VkDescriptorSetLayoutBinding (0, VkShaderStageFlags.Vertex, VkDescriptorType.UniformBuffer), new VkDescriptorSetLayoutBinding (1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler)); - + GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault (VkPrimitiveTopology.TriangleList, samples); cfg.Layout = new PipelineLayout (dev, dsLayout); cfg.RenderPass = new RenderPass (dev, swapChain.ColorFormat, dev.GetSuitableDepthFormat (), cfg.Samples); - cfg.AddVertexBinding (0, 5 * sizeof(float)); + cfg.AddVertexBinding (0, 5 * sizeof (float)); cfg.AddVertexAttributes (0, VkFormat.R32g32b32Sfloat, VkFormat.R32g32Sfloat); cfg.AddShader (VkShaderStageFlags.Vertex, "#TexturedCube.skybox.vert.spv"); @@ -216,33 +139,28 @@ namespace TextureCube { pipeline = new GraphicPipeline (cfg); - cfg.ResetShadersAndVerticesInfos (); - cfg.AddShader (VkShaderStageFlags.Vertex, "#TexturedCube.FullScreenQuad.vert.spv"); - cfg.AddShader (VkShaderStageFlags.Fragment, "#TexturedCube.simpletexture.frag.spv"); - - cfg.blendAttachments[0] = new VkPipelineColorBlendAttachmentState (true); - - uiPipeline = new GraphicPipeline (cfg); - - uboMats = new HostBuffer (dev, VkBufferUsageFlags.UniformBuffer, matrices); uboMats.Map ();//permanent map descriptorSet = descriptorPool.Allocate (dsLayout); - dsVKVG = descriptorPool.Allocate (dsLayout); - - DescriptorSetWrites uboUpdate = new DescriptorSetWrites (descriptorSet, dsLayout.Bindings[0]); + DescriptorSetWrites uboUpdate = new DescriptorSetWrites (descriptorSet, dsLayout.Bindings[0]); uboUpdate.Write (dev, uboMats.Descriptor); loadTexture (imgPathes[currentImgIndex]); if (nextTexture != null) updateTextureSet (); - initUISurface (); + +#if WITH_VKVG + dsVkvg = descriptorPool.Allocate (pipeline.Layout.DescriptorSetLayouts[0]); + vkvgPipeline = new VkvgPipeline.VkvgPipeline (instance, dev, presentQueue, pipeline); } + public override void Update () { vkvgDraw (); +#endif } + void buildCommandBuffers () { for (int i = 0; i < swapChain.ImageCount; ++i) { cmds[i]?.Free (); @@ -266,16 +184,10 @@ namespace TextureCube { cmd.BindVertexBuffer (vbo, 0); cmd.Draw (36); - uiPipeline.Bind (cmd); - cmd.BindDescriptorSet (pipeline.Layout, dsVKVG); - - uiImage.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.ColorAttachmentOptimal, VkImageLayout.ShaderReadOnlyOptimal, - VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.FragmentShader); - - cmd.Draw (3, 1, 0, 0); - - uiImage.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.ShaderReadOnlyOptimal, VkImageLayout.ColorAttachmentOptimal, - VkPipelineStageFlags.FragmentShader, VkPipelineStageFlags.BottomOfPipe); +#if WITH_VKVG + cmd.BindDescriptorSet (pipeline.Layout, dsVkvg); + vkvgPipeline.RecordDraw (cmd); +#endif pipeline.RenderPass.End (cmd); } @@ -365,7 +277,9 @@ namespace TextureCube { protected override void OnResize () { dev.WaitIdle (); - initUISurface (); +#if WITH_VKVG + vkvgPipeline.Resize ((int)swapChain.Width, (int)swapChain.Height, new DescriptorSetWrites (dsVkvg, dsLayout.Bindings[1])); +#endif updateMatrices (); @@ -397,19 +311,16 @@ namespace TextureCube { if (!isDisposed) { dev.WaitIdle (); pipeline.Dispose (); - uiPipeline.Dispose (); - dsLayout.Dispose (); for (int i = 0; i < swapChain.ImageCount; i++) frameBuffers[i].Dispose (); descriptorPool.Dispose (); texture.Dispose (); uboMats.Dispose (); - vbo.Dispose (); - uiImage?.Dispose (); - vkvgSurf?.Dispose (); - vkvgDev.Dispose (); +#if WITH_VKVG + vkvgPipeline.Dispose (); +#endif } } diff --git a/samples/Triangle/main.cs b/samples/Triangle/main.cs index 893a296..75c20ed 100644 --- a/samples/Triangle/main.cs +++ b/samples/Triangle/main.cs @@ -169,7 +169,6 @@ namespace Triangle { if (disposing) { if (!isDisposed) { pipeline.Dispose (); - dsLayout.Dispose (); for (int i = 0; i < swapChain.ImageCount; i++) frameBuffers[i].Dispose (); descriptorPool.Dispose (); diff --git a/samples/deferred/deferred.csproj b/samples/deferred/deferred.csproj index 58c2b9d..5a92526 100644 --- a/samples/deferred/deferred.csproj +++ b/samples/deferred/deferred.csproj @@ -2,7 +2,7 @@ <Import Project="$(RootDirectory)netfx.props" /> <PropertyGroup> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> - <EnableDefaultNoneItems>false</EnableDefaultNoneItems> +<!-- <EnableDefaultNoneItems>false</EnableDefaultNoneItems> --> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> diff --git a/samples/deferred/main-crow.cs b/samples/deferred/main-crow.cs index dd70624..5c0e872 100644 --- a/samples/deferred/main-crow.cs +++ b/samples/deferred/main-crow.cs @@ -129,6 +129,7 @@ namespace deferred { int curModelIndex = 0; bool reloadModel; + bool rebuildBuffers; Queue transferQ; DeferredPbrRenderer renderer; diff --git a/samples/deferred/main.cs b/samples/deferred/main.cs index 5ea0a37..2e24b37 100644 --- a/samples/deferred/main.cs +++ b/samples/deferred/main.cs @@ -64,6 +64,7 @@ namespace deferred { int curModelIndex = 0; bool reloadModel; + bool rebuildBuffers; Queue transferQ, computeQ; DeferredPbrRenderer renderer; diff --git a/samples/hdr/Program.cs b/samples/hdr/Program.cs deleted file mode 100644 index 3d3c216..0000000 --- a/samples/hdr/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using CVKL; -using VK; -using static VK.Vk; - -namespace tests { - class Program : VkWindow { - static void Main (string[] args) { -#if DEBUG - Instance.VALIDATION = true; - Instance.DEBUG_UTILS = true; - Instance.RENDER_DOC_CAPTURE = false; -#endif - using (Program vke = new Program ()) { - vke.Run (); - } - } - - - Program () : base () { - - - } - - - protected override void Dispose (bool disposing) { - if (disposing) { - if (!isDisposed) { - } - } - base.Dispose (); - } - } -} diff --git a/samples/pbr/main.cs b/samples/pbr/main.cs index 5bbdfca..b890489 100644 --- a/samples/pbr/main.cs +++ b/samples/pbr/main.cs @@ -55,14 +55,9 @@ namespace pbrSample { TimestampQueryPool timestampQPool; ulong[] results; #endif - - bool queryUpdatePrefilCube, showDebugImg, showUI; - - Image uiImage; - -#region ui + #region ui //DescriptorSet dsDebugImg; //void initDebugImg () { // dsDebugImg = descriptorPool.Allocate (descLayoutMain); @@ -70,10 +65,11 @@ namespace pbrSample { // DescriptorSetWrites uboUpdate = new DescriptorSetWrites (dsDebugImg, descLayoutMain); // uboUpdate.Write (dev, pbrPipeline.envCube.debugImg.Descriptor); //} - vkvg.Device vkvgDev; vkvg.Surface vkvgSurf; - + + Image uiImage; + Pipeline uiPipeline; void initUIPipeline () { @@ -228,6 +224,8 @@ namespace pbrSample { #endif } + bool rebuildBuffers; + void buildCommandBuffers () { for (int i = 0; i < swapChain.ImageCount; ++i) { cmds[i]?.Free (); @@ -7,37 +7,41 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CVKL", "vke\CVKL.csproj", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpirVTasks", "SpirVTasks\SpirVTasks.csproj", "{F72F73E4-86CC-4F56-B004-BCC4BF0AF30B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triangle", "samples\Triangle\Triangle.csproj", "{3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vk.generator", "vk.generator\vk.generator.csproj", "{B105512C-9461-4802-B299-A6E7A29CDAEE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "deferred", "samples\deferred\deferred.csproj", "{BA44E304-0A97-4949-B672-0CD70AD21178}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vk.rewrite", "vk.rewrite\vk.rewrite.csproj", "{5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "pbr", "samples\pbr\pbr.csproj", "{BA549E32-CC14-47B4-9E3E-6C86F9474A15}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vulkan", "VK\vulkan.csproj", "{37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Textured", "samples\Textured\Textured.csproj", "{41484D20-BBC6-484D-BD2D-BDE384304347}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CVKL.Addons", "CVKL.Addons", "{95E6BE33-0082-4E01-B064-864B411FD6B8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TexturedCube", "samples\TexturedCube\TexturedCube.csproj", "{C7188E6F-DB14-4F01-81F4-52E3159D33CF}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gltfLoader", "CVKL.Addons\gltfLoader\gltfLoader.csproj", "{39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "samples\Model\Model.csproj", "{019EDFD7-7700-4513-A1DF-74F882463E2A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DistanceFieldFontTest", "samples\DistanceFieldFontTest\DistanceFieldFontTest.csproj", "{76A29B9E-D119-4592-BB01-DBC3C17F6068}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "compute", "samples\compute\compute.csproj", "{CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "deferred", "samples\deferred\deferred.csproj", "{2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vk.generator", "vk.generator\vk.generator.csproj", "{B105512C-9461-4802-B299-A6E7A29CDAEE}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DistanceFieldFont", "CVKL.Addons\DistanceFieldFont\DistanceFieldFont.csproj", "{85BDCBF2-4918-4F74-9FF1-DFEA8514A573}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vk.rewrite", "vk.rewrite\vk.rewrite.csproj", "{5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triangle", "samples\Triangle\Triangle.csproj", "{72CA1818-AF80-497D-AD9B-C67C1A0CA913}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vulkan", "VK\vulkan.csproj", "{37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "pbr", "samples\pbr\pbr.csproj", "{08BDBB06-4B30-4B4D-A6AD-170563328F72}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CVKL.Addons", "CVKL.Addons", "{95E6BE33-0082-4E01-B064-864B411FD6B8}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TexturedCube", "samples\TexturedCube\TexturedCube.csproj", "{A5F8810A-622A-4137-B779-8A34E4C7BDDC}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gltfLoader", "CVKL.Addons\gltfLoader\gltfLoader.csproj", "{39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "samples\Model\Model.csproj", "{2B8B9356-982A-4CAC-9AE3-69DD49890FEF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VkvgPipeline", "CVKL.Addons\VkvgPipeline\VkvgPipeline.csproj", "{58A3D415-B90A-4C54-B28F-F66E2F5E77E3}" +EndProject +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "compute", "samples\compute\compute.csproj", "{807FEF05-1368-4917-90E4-260DEBF5AA51}" EndProject -Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "hdr", "samples\hdr\hdr.csproj", "{F954B758-2031-42EA-93CE-7283B6BF45A5}" +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "tests", "samples\tests\tests.csproj", "{F7848BAF-E3A8-47FD-959E-226D6E612718}" EndProject -Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "tests", "samples\tests\tests.csproj", "{58224D63-D87A-4D91-9753-CDDF418203D6}" +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "vkvg_tests", "samples\vkvg_tests\vkvg_tests.csproj", "{6FFDEEB2-90B2-4081-A9AF-DCEFB48F18DB}" EndProject -Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "vkvg_tests", "samples\vkvg_tests\vkvg_tests.csproj", "{B666FE3E-50EF-4A5F-ADC1-A178C326321F}" +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "datas", "samples\datas\datas.csproj", "{39D038E6-35F7-4926-86D9-16D279A79767}" EndProject -Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "datas", "samples\datas\datas.csproj", "{F9CD3147-68C8-4F0A-BDCD-B7E288B79DE9}" +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "Textured", "samples\Textured\Textured.csproj", "{D0E725A8-116C-4DED-A656-1C254AAFA953}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -60,109 +64,123 @@ Global {F72F73E4-86CC-4F56-B004-BCC4BF0AF30B}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU {F72F73E4-86CC-4F56-B004-BCC4BF0AF30B}.BuildPackages|Any CPU.ActiveCfg = Release|Any CPU {F72F73E4-86CC-4F56-B004-BCC4BF0AF30B}.BuildPackages|Any CPU.Build.0 = Release|Any CPU - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}.Release|Any CPU.Build.0 = Release|Any CPU - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.Release|Any CPU.Build.0 = Release|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.DebugCrow|Any CPU.ActiveCfg = DebugCrow|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.DebugCrow|Any CPU.Build.0 = DebugCrow|Any CPU - {BA44E304-0A97-4949-B672-0CD70AD21178}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {BA549E32-CC14-47B4-9E3E-6C86F9474A15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BA549E32-CC14-47B4-9E3E-6C86F9474A15}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BA549E32-CC14-47B4-9E3E-6C86F9474A15}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BA549E32-CC14-47B4-9E3E-6C86F9474A15}.Release|Any CPU.Build.0 = Release|Any CPU - {BA549E32-CC14-47B4-9E3E-6C86F9474A15}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {BA549E32-CC14-47B4-9E3E-6C86F9474A15}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {41484D20-BBC6-484D-BD2D-BDE384304347}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {41484D20-BBC6-484D-BD2D-BDE384304347}.Debug|Any CPU.Build.0 = Debug|Any CPU - {41484D20-BBC6-484D-BD2D-BDE384304347}.Release|Any CPU.ActiveCfg = Release|Any CPU - {41484D20-BBC6-484D-BD2D-BDE384304347}.Release|Any CPU.Build.0 = Release|Any CPU - {41484D20-BBC6-484D-BD2D-BDE384304347}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {41484D20-BBC6-484D-BD2D-BDE384304347}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {C7188E6F-DB14-4F01-81F4-52E3159D33CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C7188E6F-DB14-4F01-81F4-52E3159D33CF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C7188E6F-DB14-4F01-81F4-52E3159D33CF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C7188E6F-DB14-4F01-81F4-52E3159D33CF}.Release|Any CPU.Build.0 = Release|Any CPU - {C7188E6F-DB14-4F01-81F4-52E3159D33CF}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {C7188E6F-DB14-4F01-81F4-52E3159D33CF}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {019EDFD7-7700-4513-A1DF-74F882463E2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {019EDFD7-7700-4513-A1DF-74F882463E2A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {019EDFD7-7700-4513-A1DF-74F882463E2A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {019EDFD7-7700-4513-A1DF-74F882463E2A}.Release|Any CPU.Build.0 = Release|Any CPU - {019EDFD7-7700-4513-A1DF-74F882463E2A}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {019EDFD7-7700-4513-A1DF-74F882463E2A}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}.Release|Any CPU.Build.0 = Release|Any CPU - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU {B105512C-9461-4802-B299-A6E7A29CDAEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B105512C-9461-4802-B299-A6E7A29CDAEE}.Debug|Any CPU.Build.0 = Debug|Any CPU {B105512C-9461-4802-B299-A6E7A29CDAEE}.Release|Any CPU.ActiveCfg = Release|Any CPU {B105512C-9461-4802-B299-A6E7A29CDAEE}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU {B105512C-9461-4802-B299-A6E7A29CDAEE}.BuildPackages|Any CPU.ActiveCfg = Release|Any CPU - {B105512C-9461-4802-B299-A6E7A29CDAEE}.BuildPackages|Any CPU.Build.0 = Release|Any CPU {5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}.Debug|Any CPU.Build.0 = Debug|Any CPU {5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}.Release|Any CPU.ActiveCfg = Release|Any CPU {5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU {5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}.BuildPackages|Any CPU.ActiveCfg = Release|Any CPU - {5EC0F6C6-74C9-4509-8AC8-FAE3574AF5C7}.BuildPackages|Any CPU.Build.0 = Release|Any CPU {37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}.Debug|Any CPU.Build.0 = Debug|Any CPU {37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}.Release|Any CPU.ActiveCfg = Release|Any CPU {37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU {37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}.BuildPackages|Any CPU.ActiveCfg = Release|Any CPU - {37D01BE5-5FE2-4742-BD5B-5D2C25FCF146}.BuildPackages|Any CPU.Build.0 = Release|Any CPU {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.Release|Any CPU.ActiveCfg = Release|Any CPU {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.Release|Any CPU.Build.0 = Release|Any CPU {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.DebugCrow|Any CPU.Build.0 = Debug|Any CPU - {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.BuildPackages|Any CPU.Build.0 = Debug|Any CPU - {F954B758-2031-42EA-93CE-7283B6BF45A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F954B758-2031-42EA-93CE-7283B6BF45A5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F954B758-2031-42EA-93CE-7283B6BF45A5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F954B758-2031-42EA-93CE-7283B6BF45A5}.Release|Any CPU.Build.0 = Release|Any CPU - {F954B758-2031-42EA-93CE-7283B6BF45A5}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {F954B758-2031-42EA-93CE-7283B6BF45A5}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {58224D63-D87A-4D91-9753-CDDF418203D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {58224D63-D87A-4D91-9753-CDDF418203D6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {58224D63-D87A-4D91-9753-CDDF418203D6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {58224D63-D87A-4D91-9753-CDDF418203D6}.Release|Any CPU.Build.0 = Release|Any CPU - {58224D63-D87A-4D91-9753-CDDF418203D6}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {58224D63-D87A-4D91-9753-CDDF418203D6}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {B666FE3E-50EF-4A5F-ADC1-A178C326321F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B666FE3E-50EF-4A5F-ADC1-A178C326321F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B666FE3E-50EF-4A5F-ADC1-A178C326321F}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU - {B666FE3E-50EF-4A5F-ADC1-A178C326321F}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU - {F9CD3147-68C8-4F0A-BDCD-B7E288B79DE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F9CD3147-68C8-4F0A-BDCD-B7E288B79DE9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F9CD3147-68C8-4F0A-BDCD-B7E288B79DE9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F9CD3147-68C8-4F0A-BDCD-B7E288B79DE9}.Release|Any CPU.Build.0 = Release|Any CPU + {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2}.BuildPackages|Any CPU.ActiveCfg = Release|Any CPU + {76A29B9E-D119-4592-BB01-DBC3C17F6068}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {76A29B9E-D119-4592-BB01-DBC3C17F6068}.Debug|Any CPU.Build.0 = Debug|Any CPU + {76A29B9E-D119-4592-BB01-DBC3C17F6068}.Release|Any CPU.ActiveCfg = Release|Any CPU + {76A29B9E-D119-4592-BB01-DBC3C17F6068}.Release|Any CPU.Build.0 = Release|Any CPU + {76A29B9E-D119-4592-BB01-DBC3C17F6068}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {76A29B9E-D119-4592-BB01-DBC3C17F6068}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.Release|Any CPU.Build.0 = Release|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.DebugCrow|Any CPU.ActiveCfg = DebugCrow|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.DebugCrow|Any CPU.Build.0 = DebugCrow|Any CPU + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.Release|Any CPU.Build.0 = Release|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.DebugCrow|Any CPU.Build.0 = Debug|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573}.BuildPackages|Any CPU.Build.0 = Debug|Any CPU + {72CA1818-AF80-497D-AD9B-C67C1A0CA913}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {72CA1818-AF80-497D-AD9B-C67C1A0CA913}.Debug|Any CPU.Build.0 = Debug|Any CPU + {72CA1818-AF80-497D-AD9B-C67C1A0CA913}.Release|Any CPU.ActiveCfg = Release|Any CPU + {72CA1818-AF80-497D-AD9B-C67C1A0CA913}.Release|Any CPU.Build.0 = Release|Any CPU + {72CA1818-AF80-497D-AD9B-C67C1A0CA913}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {72CA1818-AF80-497D-AD9B-C67C1A0CA913}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {08BDBB06-4B30-4B4D-A6AD-170563328F72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {08BDBB06-4B30-4B4D-A6AD-170563328F72}.Debug|Any CPU.Build.0 = Debug|Any CPU + {08BDBB06-4B30-4B4D-A6AD-170563328F72}.Release|Any CPU.ActiveCfg = Release|Any CPU + {08BDBB06-4B30-4B4D-A6AD-170563328F72}.Release|Any CPU.Build.0 = Release|Any CPU + {08BDBB06-4B30-4B4D-A6AD-170563328F72}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {08BDBB06-4B30-4B4D-A6AD-170563328F72}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {A5F8810A-622A-4137-B779-8A34E4C7BDDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5F8810A-622A-4137-B779-8A34E4C7BDDC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5F8810A-622A-4137-B779-8A34E4C7BDDC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A5F8810A-622A-4137-B779-8A34E4C7BDDC}.Release|Any CPU.Build.0 = Release|Any CPU + {A5F8810A-622A-4137-B779-8A34E4C7BDDC}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {A5F8810A-622A-4137-B779-8A34E4C7BDDC}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF}.Release|Any CPU.Build.0 = Release|Any CPU + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.Release|Any CPU.Build.0 = Release|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.DebugCrow|Any CPU.Build.0 = Debug|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3}.BuildPackages|Any CPU.Build.0 = Debug|Any CPU + {807FEF05-1368-4917-90E4-260DEBF5AA51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {807FEF05-1368-4917-90E4-260DEBF5AA51}.Debug|Any CPU.Build.0 = Debug|Any CPU + {807FEF05-1368-4917-90E4-260DEBF5AA51}.Release|Any CPU.ActiveCfg = Release|Any CPU + {807FEF05-1368-4917-90E4-260DEBF5AA51}.Release|Any CPU.Build.0 = Release|Any CPU + {807FEF05-1368-4917-90E4-260DEBF5AA51}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {807FEF05-1368-4917-90E4-260DEBF5AA51}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {F7848BAF-E3A8-47FD-959E-226D6E612718}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F7848BAF-E3A8-47FD-959E-226D6E612718}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F7848BAF-E3A8-47FD-959E-226D6E612718}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F7848BAF-E3A8-47FD-959E-226D6E612718}.Release|Any CPU.Build.0 = Release|Any CPU + {F7848BAF-E3A8-47FD-959E-226D6E612718}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {F7848BAF-E3A8-47FD-959E-226D6E612718}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {6FFDEEB2-90B2-4081-A9AF-DCEFB48F18DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6FFDEEB2-90B2-4081-A9AF-DCEFB48F18DB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6FFDEEB2-90B2-4081-A9AF-DCEFB48F18DB}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {6FFDEEB2-90B2-4081-A9AF-DCEFB48F18DB}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU + {39D038E6-35F7-4926-86D9-16D279A79767}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {39D038E6-35F7-4926-86D9-16D279A79767}.Debug|Any CPU.Build.0 = Debug|Any CPU + {39D038E6-35F7-4926-86D9-16D279A79767}.Release|Any CPU.ActiveCfg = Release|Any CPU + {39D038E6-35F7-4926-86D9-16D279A79767}.Release|Any CPU.Build.0 = Release|Any CPU + {D0E725A8-116C-4DED-A656-1C254AAFA953}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0E725A8-116C-4DED-A656-1C254AAFA953}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0E725A8-116C-4DED-A656-1C254AAFA953}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0E725A8-116C-4DED-A656-1C254AAFA953}.Release|Any CPU.Build.0 = Release|Any CPU + {D0E725A8-116C-4DED-A656-1C254AAFA953}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {D0E725A8-116C-4DED-A656-1C254AAFA953}.BuildPackages|Any CPU.ActiveCfg = Debug|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution - {3CFF99D3-8C0E-4B37-9146-9A7ED9D28CAA} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {BA44E304-0A97-4949-B672-0CD70AD21178} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {BA549E32-CC14-47B4-9E3E-6C86F9474A15} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {41484D20-BBC6-484D-BD2D-BDE384304347} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {C7188E6F-DB14-4F01-81F4-52E3159D33CF} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {019EDFD7-7700-4513-A1DF-74F882463E2A} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {CB21E2C4-C56E-49AE-9423-FCE2E75DEA0A} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} {39E7BD7A-0489-4681-ACBD-6CEE13C6C9C2} = {95E6BE33-0082-4E01-B064-864B411FD6B8} - {F954B758-2031-42EA-93CE-7283B6BF45A5} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {58224D63-D87A-4D91-9753-CDDF418203D6} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {B666FE3E-50EF-4A5F-ADC1-A178C326321F} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} - {F9CD3147-68C8-4F0A-BDCD-B7E288B79DE9} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {76A29B9E-D119-4592-BB01-DBC3C17F6068} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {2DBE8CDD-E1E7-4930-B925-6C60E6C5C84D} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {85BDCBF2-4918-4F74-9FF1-DFEA8514A573} = {95E6BE33-0082-4E01-B064-864B411FD6B8} + {72CA1818-AF80-497D-AD9B-C67C1A0CA913} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {08BDBB06-4B30-4B4D-A6AD-170563328F72} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {A5F8810A-622A-4137-B779-8A34E4C7BDDC} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {2B8B9356-982A-4CAC-9AE3-69DD49890FEF} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {58A3D415-B90A-4C54-B28F-F66E2F5E77E3} = {95E6BE33-0082-4E01-B064-864B411FD6B8} + {807FEF05-1368-4917-90E4-260DEBF5AA51} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {F7848BAF-E3A8-47FD-959E-226D6E612718} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {6FFDEEB2-90B2-4081-A9AF-DCEFB48F18DB} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {39D038E6-35F7-4926-86D9-16D279A79767} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {D0E725A8-116C-4DED-A656-1C254AAFA953} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution Policies = $0 diff --git a/vke/CVKL.csproj b/vke/CVKL.csproj index 465fd48..443ed77 100644 --- a/vke/CVKL.csproj +++ b/vke/CVKL.csproj @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> - <Import Project="$(RootDirectory)netfx.props" /> +<!-- <Import Project="$(RootDirectory)netfx.props" />--> <PropertyGroup> <AssemblyName>CVKL</AssemblyName> <Product>CVKL</Product> @@ -19,6 +19,8 @@ <SynchReleaseVersion>false</SynchReleaseVersion> <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + + <EnableDefaultNoneItems>false</EnableDefaultNoneItems> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> @@ -39,9 +41,13 @@ </ItemGroup> <ItemGroup> + <PackageReference Include="SpirVTasks" Version="0.1.9-beta" /> <PackageReference Include="Vulkan" Version="0.1.4" /> </ItemGroup> <ItemGroup> + <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert;shaders\**\*.comp;shaders\**\*.geom"> + <ResourceId>testRsID</ResourceId> + </GLSLShader> <Compile Remove="Properties\AssemblyInfo.cs;src\Renderer.cs;src\QueueFamily.cs" /> </ItemGroup> -</Project>
\ No newline at end of file +</Project> diff --git a/vke/shaders/debug.frag b/vke/shaders/debug.frag deleted file mode 100644 index fd419ff..0000000 --- a/vke/shaders/debug.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 450 - -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (location = 0) in vec3 inColor; -layout (location = 0) out vec4 outFragColor; - -void main() -{ - outFragColor = vec4(inColor, 1.0); -}
\ No newline at end of file diff --git a/vke/shaders/debug.vert b/vke/shaders/debug.vert deleted file mode 100644 index 180e58e..0000000 --- a/vke/shaders/debug.vert +++ /dev/null @@ -1,34 +0,0 @@ -#version 450 - -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (location = 0) in vec3 inPos; -layout (location = 1) in vec3 inColor; - -layout (location = 0) out vec3 outColor; - -layout (binding = 0) uniform UBO -{ - mat4 projectionMatrix; - mat4 viewMatrix; - mat4 modelMatrix; - float gamma; - float exposure; -} ubo; - -layout(push_constant) uniform PushConsts { - mat4 projectionMatrix; -} pc; - -out gl_PerVertex -{ - vec4 gl_Position; -}; - -void main() -{ - outColor = inColor; - - gl_Position = pc.projectionMatrix * vec4 ((ubo.viewMatrix * vec4(inPos.xyz, 0.0)).xyz, 1); -} diff --git a/vke/shaders/deffered/GBuffPbr.frag b/vke/shaders/deffered/GBuffPbr.frag deleted file mode 100644 index ca398e6..0000000 --- a/vke/shaders/deffered/GBuffPbr.frag +++ /dev/null @@ -1,212 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -#define MANUAL_SRGB 0 -#define DEBUG 0 - -layout (constant_id = 0) const float NEAR_PLANE = 0.1f; -layout (constant_id = 1) const float FAR_PLANE = 256.0f; -layout (constant_id = 2) const int MAT_COUNT = 1; - -struct Material { - vec4 baseColorFactor; - vec4 emissiveFactor; - vec4 diffuseFactor; - vec4 specularFactor; - float workflow; - uint tex0; - uint tex1; - float metallicFactor; - float roughnessFactor; - float alphaMask; - float alphaMaskCutoff; - int pad0; -}; -const float M_PI = 3.141592653589793; -const float c_MinRoughness = 0.04; - -const float PBR_WORKFLOW_METALLIC_ROUGHNESS = 1.0; -const float PBR_WORKFLOW_SPECULAR_GLOSINESS = 2.0f; - -const uint MAP_COLOR = 0x1; -const uint MAP_NORMAL = 0x2; -const uint MAP_AO = 0x4; -const uint MAP_METAL = 0x8; -const uint MAP_ROUGHNESS = 0x10; -const uint MAP_METALROUGHNESS = 0x20; -const uint MAP_EMISSIVE = 0x40; - -layout (location = 0) in vec3 inWorldPos; -layout (location = 1) in vec3 inNormal; -layout (location = 2) in vec2 inUV0; -layout (location = 3) in vec2 inUV1; - - -layout (set = 0, binding = 5) uniform UBOMaterials { - Material materials[MAT_COUNT]; -}; - -// Material bindings -layout (set = 2, binding = 0) uniform sampler2D colorMap; -layout (set = 2, binding = 1) uniform sampler2D physicalDescriptorMap; -layout (set = 2, binding = 2) uniform sampler2D normalMap; -layout (set = 2, binding = 3) uniform sampler2D aoMap; -layout (set = 2, binding = 4) uniform sampler2D emissiveMap; - - -layout (push_constant) uniform PushCsts { - layout(offset = 64) - int materialIdx; -}; - - -layout (location = 0) out vec4 outColorRough; -layout (location = 1) out vec4 outEmitMetal; -layout (location = 2) out vec4 outN_AO; -layout (location = 3) out vec4 outPos; - -vec4 SRGBtoLINEAR(vec4 srgbIn) -{ - #ifdef MANUAL_SRGB - #ifdef SRGB_FAST_APPROXIMATION - vec3 linOut = pow(srgbIn.xyz,vec3(2.2)); - #else //SRGB_FAST_APPROXIMATION - vec3 bLess = step(vec3(0.04045),srgbIn.xyz); - vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess ); - #endif //SRGB_FAST_APPROXIMATION - return vec4(linOut,srgbIn.w);; - #else //MANUAL_SRGB - return srgbIn; - #endif //MANUAL_SRGB -} - -// Find the normal for this fragment, pulling either from a predefined normal map -// or from the interpolated mesh normal and tangent attributes. -vec3 getNormal() -{ - vec3 tangentNormal; - // Perturb normal, see http://www.thetenthplanet.de/archives/1180 - if ((materials[materialIdx].tex0 & MAP_NORMAL) == MAP_NORMAL) - tangentNormal = texture(normalMap, inUV0).xyz * 2.0 - 1.0; - else if ((materials[materialIdx].tex1 & MAP_NORMAL) == MAP_NORMAL) - tangentNormal = texture(normalMap, inUV1).xyz * 2.0 - 1.0; - else - return normalize(inNormal); - - vec3 q1 = dFdx(inWorldPos); - vec3 q2 = dFdy(inWorldPos); - vec2 st1 = dFdx(inUV0); - vec2 st2 = dFdy(inUV0); - - vec3 N = normalize(inNormal); - vec3 T = normalize(q1 * st2.t - q2 * st1.t); - vec3 B = -normalize(cross(N, T)); - mat3 TBN = mat3(T, B, N); - - return normalize(TBN * tangentNormal); -} - -// Gets metallic factor from specular glossiness workflow inputs -float convertMetallic(vec3 diffuse, vec3 specular, float maxSpecular) { - float perceivedDiffuse = sqrt(0.299 * diffuse.r * diffuse.r + 0.587 * diffuse.g * diffuse.g + 0.114 * diffuse.b * diffuse.b); - float perceivedSpecular = sqrt(0.299 * specular.r * specular.r + 0.587 * specular.g * specular.g + 0.114 * specular.b * specular.b); - if (perceivedSpecular < c_MinRoughness) { - return 0.0; - } - float a = c_MinRoughness; - float b = perceivedDiffuse * (1.0 - maxSpecular) / (1.0 - c_MinRoughness) + perceivedSpecular - 2.0 * c_MinRoughness; - float c = c_MinRoughness - perceivedSpecular; - float D = max(b * b - 4.0 * a * c, 0.0); - return clamp((-b + sqrt(D)) / (2.0 * a), 0.0, 1.0); -} - -float linearDepth(float depth) -{ - float z = depth * 2.0f - 1.0f; - return (2.0f * NEAR_PLANE * FAR_PLANE) / (FAR_PLANE + NEAR_PLANE - z * (FAR_PLANE - NEAR_PLANE)); -} - -void main() -{ - float perceptualRoughness; - float metallic; - vec4 baseColor; - vec3 emissive = vec3(0); - - baseColor = materials[materialIdx].baseColorFactor; - - if (materials[materialIdx].workflow == PBR_WORKFLOW_METALLIC_ROUGHNESS) { - perceptualRoughness = materials[materialIdx].roughnessFactor; - metallic = materials[materialIdx].metallicFactor; - // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel. - // This layout intentionally reserves the 'r' channel for (optional) occlusion map data - if ((materials[materialIdx].tex0 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS){ - perceptualRoughness *= texture(physicalDescriptorMap, inUV0).g; - metallic *= texture(physicalDescriptorMap, inUV0).b; - }else if ((materials[materialIdx].tex1 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS){ - perceptualRoughness *= texture(physicalDescriptorMap, inUV1).g; - metallic *= texture(physicalDescriptorMap, inUV1).b; - } - perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0); - metallic = clamp(metallic, 0.0, 1.0); - - // The albedo may be defined from a base texture or a flat color - if ((materials[materialIdx].tex0 & MAP_COLOR) == MAP_COLOR) - baseColor *= SRGBtoLINEAR(texture(colorMap, inUV0)); - else if ((materials[materialIdx].tex1 & MAP_COLOR) == MAP_COLOR) - baseColor *= SRGBtoLINEAR(texture(colorMap, inUV1)); - } - - if (materials[materialIdx].alphaMask == 1.0f) { - if (baseColor.a < materials[materialIdx].alphaMaskCutoff) - discard; - } - - if (materials[materialIdx].workflow == PBR_WORKFLOW_SPECULAR_GLOSINESS) { - // Values from specular glossiness workflow are converted to metallic roughness - if ((materials[materialIdx].tex0 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS) - perceptualRoughness = 1.0 - texture(physicalDescriptorMap, inUV0).a; - else if ((materials[materialIdx].tex1 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS) - perceptualRoughness = 1.0 - texture(physicalDescriptorMap, inUV1).a; - else - perceptualRoughness = 0.0; - - const float epsilon = 1e-6; - - vec4 diffuse = SRGBtoLINEAR(texture(colorMap, inUV0)); - vec3 specular = SRGBtoLINEAR(texture(physicalDescriptorMap, inUV0)).rgb; - - float maxSpecular = max(max(specular.r, specular.g), specular.b); - - // Convert metallic value from specular glossiness inputs - metallic = convertMetallic(diffuse.rgb, specular, maxSpecular); - - vec3 baseColorDiffusePart = diffuse.rgb * ((1.0 - maxSpecular) / (1 - c_MinRoughness) / max(1 - metallic, epsilon)) * materials[materialIdx].diffuseFactor.rgb; - vec3 baseColorSpecularPart = specular - (vec3(c_MinRoughness) * (1 - metallic) * (1 / max(metallic, epsilon))) * materials[materialIdx].specularFactor.rgb; - baseColor = vec4(mix(baseColorDiffusePart, baseColorSpecularPart, metallic * metallic), diffuse.a); - - } - - const float u_OcclusionStrength = 1.0f; - const float u_EmissiveFactor = 1.0f; - float ao = 1.0f; - - if ((materials[materialIdx].tex0 & MAP_EMISSIVE) == MAP_EMISSIVE) - emissive = SRGBtoLINEAR(texture(emissiveMap, inUV0)).rgb * u_EmissiveFactor; - else if ((materials[materialIdx].tex1 & MAP_EMISSIVE) == MAP_EMISSIVE) - emissive = SRGBtoLINEAR(texture(emissiveMap, inUV1)).rgb * u_EmissiveFactor; - - if ((materials[materialIdx].tex0 & MAP_AO) == MAP_AO) - ao = texture(aoMap, inUV0).r; - else if ((materials[materialIdx].tex1 & MAP_AO) == MAP_AO) - ao = texture(aoMap, inUV1).r; - - vec3 n = getNormal(); - vec3 p = inWorldPos; - - outColorRough = vec4 (baseColor.rgb, perceptualRoughness); - outEmitMetal = vec4 (emissive, metallic); - outN_AO = vec4 (n, ao); - outPos = vec4 (p, linearDepth(gl_FragCoord.z)); -}
\ No newline at end of file diff --git a/vke/shaders/deffered/GBuffPbr.vert b/vke/shaders/deffered/GBuffPbr.vert deleted file mode 100644 index 7cafe49..0000000 --- a/vke/shaders/deffered/GBuffPbr.vert +++ /dev/null @@ -1,37 +0,0 @@ -#version 450 - -layout (location = 0) in vec3 inPos; -layout (location = 1) in vec3 inNormal; -layout (location = 2) in vec2 inUV0; -layout (location = 3) in vec2 inUV1; - -layout (set = 0, binding = 0) uniform UBO { - mat4 projection; - mat4 model; - mat4 view; -} ubo; - -layout(push_constant) uniform PushConsts { - mat4 model; -} pc; - -layout (location = 0) out vec3 outWorldPos; -layout (location = 1) out vec3 outNormal; -layout (location = 2) out vec2 outUV0; -layout (location = 3) out vec2 outUV1; - -out gl_PerVertex -{ - vec4 gl_Position; -}; - -void main() -{ - vec4 locPos = ubo.model * pc.model * vec4(inPos, 1.0); - outNormal = normalize(transpose(inverse(mat3(ubo.model * pc.model))) * inNormal); - - outWorldPos = locPos.xyz; - outUV0 = inUV0; - outUV1 = inUV1; - gl_Position = ubo.projection * ubo.view * vec4(outWorldPos, 1.0); -} diff --git a/vke/shaders/deffered/GBuffPbrTexArray.frag b/vke/shaders/deffered/GBuffPbrTexArray.frag deleted file mode 100644 index dee3471..0000000 --- a/vke/shaders/deffered/GBuffPbrTexArray.frag +++ /dev/null @@ -1,211 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -#define MANUAL_SRGB 0 -#define DEBUG 0 - -layout (constant_id = 0) const float NEAR_PLANE = 0.1f; -layout (constant_id = 1) const float FAR_PLANE = 256.0f; -layout (constant_id = 2) const int MAT_COUNT = 1; - -struct Material { - vec4 baseColorFactor; - vec4 emissiveFactor; - vec4 diffuseFactor; - vec4 specularFactor; - - float workflow; - uint tex0; - uint tex1; - int baseColorTex; - - int physicalDescTex; - int normalTex; - int occlusionTex; - int emissiveTex; - - float metallicFactor; - float roughnessFactor; - float alphaMask; - float alphaMaskCutoff; -}; -const float M_PI = 3.141592653589793; -const float c_MinRoughness = 0.04; - -const float PBR_WORKFLOW_METALLIC_ROUGHNESS = 1.0; -const float PBR_WORKFLOW_SPECULAR_GLOSINESS = 2.0f; - -const uint MAP_COLOR = 0x1; -const uint MAP_NORMAL = 0x2; -const uint MAP_AO = 0x4; -const uint MAP_METAL = 0x8; -const uint MAP_ROUGHNESS = 0x10; -const uint MAP_METALROUGHNESS = 0x20; -const uint MAP_EMISSIVE = 0x40; - -layout (location = 0) in vec3 inWorldPos; -layout (location = 1) in vec3 inNormal; -layout (location = 2) in vec2 inUV0; -layout (location = 3) in vec2 inUV1; - -layout (set = 0, binding = 5) uniform UBOMaterials { - Material materials[MAT_COUNT]; -}; -layout (set = 0, binding = 7) uniform sampler2DArray texArray; - -layout (push_constant) uniform PushCsts { - layout(offset = 64) - int materialIdx; -}; - - -layout (location = 0) out vec4 outColorRough; -layout (location = 1) out vec4 outEmitMetal; -layout (location = 2) out vec4 outN_AO; -layout (location = 3) out vec4 outPos; - -vec4 SRGBtoLINEAR(vec4 srgbIn) -{ - #ifdef MANUAL_SRGB - #ifdef SRGB_FAST_APPROXIMATION - vec3 linOut = pow(srgbIn.xyz,vec3(2.2)); - #else //SRGB_FAST_APPROXIMATION - vec3 bLess = step(vec3(0.04045),srgbIn.xyz); - vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess ); - #endif //SRGB_FAST_APPROXIMATION - return vec4(linOut,srgbIn.w);; - #else //MANUAL_SRGB - return srgbIn; - #endif //MANUAL_SRGB -} - -// Find the normal for this fragment, pulling either from a predefined normal map -// or from the interpolated mesh normal and tangent attributes. -vec3 getNormal() -{ - vec3 tangentNormal; - // Perturb normal, see http://www.thetenthplanet.de/archives/1180 - if ((materials[materialIdx].tex0 & MAP_NORMAL) == MAP_NORMAL) - tangentNormal = texture(texArray, vec3(inUV0, materials[materialIdx].normalTex)).xyz * 2.0 - 1.0; - else if ((materials[materialIdx].tex1 & MAP_NORMAL) == MAP_NORMAL) - tangentNormal = texture(texArray, vec3(inUV1, materials[materialIdx].normalTex)).xyz * 2.0 - 1.0; - else - return normalize(inNormal); - - vec3 q1 = dFdx(inWorldPos); - vec3 q2 = dFdy(inWorldPos); - vec2 st1 = dFdx(inUV0); - vec2 st2 = dFdy(inUV0); - - vec3 N = normalize(inNormal); - vec3 T = normalize(q1 * st2.t - q2 * st1.t); - vec3 B = -normalize(cross(N, T)); - mat3 TBN = mat3(T, B, N); - - return normalize(TBN * tangentNormal); -} - -// Gets metallic factor from specular glossiness workflow inputs -float convertMetallic(vec3 diffuse, vec3 specular, float maxSpecular) { - float perceivedDiffuse = sqrt(0.299 * diffuse.r * diffuse.r + 0.587 * diffuse.g * diffuse.g + 0.114 * diffuse.b * diffuse.b); - float perceivedSpecular = sqrt(0.299 * specular.r * specular.r + 0.587 * specular.g * specular.g + 0.114 * specular.b * specular.b); - if (perceivedSpecular < c_MinRoughness) { - return 0.0; - } - float a = c_MinRoughness; - float b = perceivedDiffuse * (1.0 - maxSpecular) / (1.0 - c_MinRoughness) + perceivedSpecular - 2.0 * c_MinRoughness; - float c = c_MinRoughness - perceivedSpecular; - float D = max(b * b - 4.0 * a * c, 0.0); - return clamp((-b + sqrt(D)) / (2.0 * a), 0.0, 1.0); -} - -float linearDepth(float depth) -{ - float z = depth * 2.0f - 1.0f; - return (2.0f * NEAR_PLANE * FAR_PLANE) / (FAR_PLANE + NEAR_PLANE - z * (FAR_PLANE - NEAR_PLANE)); -} - -void main() -{ - float perceptualRoughness; - float metallic; - vec4 baseColor; - vec3 emissive = vec3(0); - - baseColor = materials[materialIdx].baseColorFactor; - - if (materials[materialIdx].workflow == PBR_WORKFLOW_METALLIC_ROUGHNESS) { - perceptualRoughness = materials[materialIdx].roughnessFactor; - metallic = materials[materialIdx].metallicFactor; - // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel. - // This layout intentionally reserves the 'r' channel for (optional) occlusion map data - if ((materials[materialIdx].tex0 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS){ - perceptualRoughness *= texture(texArray, vec3(inUV0, materials[materialIdx].physicalDescTex)).g; - metallic *= texture(texArray, vec3(inUV0, materials[materialIdx].physicalDescTex)).b; - }else if ((materials[materialIdx].tex1 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS){ - perceptualRoughness *= texture(texArray, vec3(inUV1, materials[materialIdx].physicalDescTex)).g; - metallic *= texture(texArray, vec3(inUV1, materials[materialIdx].physicalDescTex)).b; - } - perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0); - metallic = clamp(metallic, 0.0, 1.0); - - // The albedo may be defined from a base texture or a flat color - if ((materials[materialIdx].tex0 & MAP_COLOR) == MAP_COLOR) - baseColor *= SRGBtoLINEAR(texture(texArray, vec3(inUV0, materials[materialIdx].baseColorTex))); - else if ((materials[materialIdx].tex1 & MAP_COLOR) == MAP_COLOR) - baseColor *= SRGBtoLINEAR(texture(texArray, vec3(inUV1, materials[materialIdx].baseColorTex))); - } - - if (materials[materialIdx].alphaMask == 1.0f) { - if (baseColor.a < materials[materialIdx].alphaMaskCutoff) - discard; - } - - if (materials[materialIdx].workflow == PBR_WORKFLOW_SPECULAR_GLOSINESS) { - // Values from specular glossiness workflow are converted to metallic roughness - if ((materials[materialIdx].tex0 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS) - perceptualRoughness = 1.0 - texture(texArray, vec3(inUV0, materials[materialIdx].physicalDescTex)).a; - else if ((materials[materialIdx].tex1 & MAP_METALROUGHNESS) == MAP_METALROUGHNESS) - perceptualRoughness = 1.0 - texture(texArray, vec3(inUV1, materials[materialIdx].physicalDescTex)).a; - else - perceptualRoughness = 0.0; - - const float epsilon = 1e-6; - - vec4 diffuse = SRGBtoLINEAR(texture(texArray, vec3(inUV0, materials[materialIdx].baseColorTex))); - vec3 specular = SRGBtoLINEAR(texture(texArray, vec3(inUV0, materials[materialIdx].physicalDescTex))).rgb; - - float maxSpecular = max(max(specular.r, specular.g), specular.b); - - // Convert metallic value from specular glossiness inputs - metallic = convertMetallic(diffuse.rgb, specular, maxSpecular); - - vec3 baseColorDiffusePart = diffuse.rgb * ((1.0 - maxSpecular) / (1 - c_MinRoughness) / max(1 - metallic, epsilon)) * materials[materialIdx].diffuseFactor.rgb; - vec3 baseColorSpecularPart = specular - (vec3(c_MinRoughness) * (1 - metallic) * (1 / max(metallic, epsilon))) * materials[materialIdx].specularFactor.rgb; - baseColor = vec4(mix(baseColorDiffusePart, baseColorSpecularPart, metallic * metallic), diffuse.a); - - } - - const float u_OcclusionStrength = 1.0f; - const float u_EmissiveFactor = 1.0f; - float ao = 1.0f; - - if ((materials[materialIdx].tex0 & MAP_EMISSIVE) == MAP_EMISSIVE) - emissive = SRGBtoLINEAR(texture(texArray, vec3(inUV0, materials[materialIdx].emissiveTex))).rgb * u_EmissiveFactor; - else if ((materials[materialIdx].tex1 & MAP_EMISSIVE) == MAP_EMISSIVE) - emissive = SRGBtoLINEAR(texture(texArray, vec3(inUV1, materials[materialIdx].emissiveTex))).rgb * u_EmissiveFactor; - - if ((materials[materialIdx].tex0 & MAP_AO) == MAP_AO) - ao = texture(texArray, vec3(inUV0, materials[materialIdx].occlusionTex)).r; - else if ((materials[materialIdx].tex1 & MAP_AO) == MAP_AO) - ao = texture(texArray, vec3(inUV1, materials[materialIdx].occlusionTex)).r; - - vec3 n = getNormal(); - vec3 p = inWorldPos; - - outColorRough = vec4 (baseColor.rgb, perceptualRoughness); - outEmitMetal = vec4 (emissive, metallic); - outN_AO = vec4 (n, ao); - outPos = vec4 (p, linearDepth(gl_FragCoord.z)); -}
\ No newline at end of file diff --git a/vke/shaders/deffered/compose.frag b/vke/shaders/deffered/compose.frag deleted file mode 100644 index 81312bd..0000000 --- a/vke/shaders/deffered/compose.frag +++ /dev/null @@ -1,230 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (set = 0, binding = 0) uniform UBO { - mat4 projection; - mat4 model; - mat4 view; - vec4 camPos; - float exposure; - float gamma; - float prefilteredCubeMipLevels; - float scaleIBLAmbient; -} ubo; - -layout (constant_id = 0) const uint NUM_LIGHTS = 1; - -struct Light { - vec4 position; - vec4 color; - mat4 mvp; -}; - -layout (set = 0, binding = 4) uniform UBOLights { - Light lights[NUM_LIGHTS]; -}; - -const float M_PI = 3.141592653589793; -const float c_MinRoughness = 0.04; - -layout (input_attachment_index = 0, set = 1, binding = 0) uniform subpassInputMS samplerColorRough; -layout (input_attachment_index = 1, set = 1, binding = 1) uniform subpassInputMS samplerEmitMetal; -layout (input_attachment_index = 2, set = 1, binding = 2) uniform subpassInputMS samplerN_AO; -layout (input_attachment_index = 3, set = 1, binding = 3) uniform subpassInputMS samplerPos; - -layout (set = 0, binding = 1) uniform samplerCube samplerIrradiance; -layout (set = 0, binding = 2) uniform samplerCube prefilteredMap; -layout (set = 0, binding = 3) uniform sampler2D samplerBRDFLUT; - -layout (location = 0) in vec2 inUV; - -layout (location = 0) out vec4 outColor; - -// Encapsulate the various inputs used by the various functions in the shading equation -// We store values in this struct to simplify the integration of alternative implementations -// of the shading terms, outlined in the Readme.MD Appendix. -struct PBRInfo -{ - float NdotL; // cos angle between normal and light direction - float NdotV; // cos angle between normal and view direction - float NdotH; // cos angle between normal and half vector - float LdotH; // cos angle between light direction and half vector - float VdotH; // cos angle between view direction and half vector - float perceptualRoughness; // roughness value, as authored by the model creator (input to shader) - float metalness; // metallic value at the surface - vec3 reflectance0; // full reflectance color (normal incidence angle) - vec3 reflectance90; // reflectance color at grazing angle - float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2]) - vec3 diffuseColor; // color contribution from diffuse lighting - vec3 specularColor; // color contribution from specular lighting -}; - -// Calculation of the lighting contribution from an optional Image Based Light source. -// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1]. -// See our README.md on Environment Maps [3] for additional discussion. -vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection) -{ - float lod = (pbrInputs.perceptualRoughness * ubo.prefilteredCubeMipLevels); - // retrieve a scale and bias to F0. See [1], Figure 3 - vec3 brdf = (texture(samplerBRDFLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb; - vec3 diffuseLight = texture(samplerIrradiance, reflection).rgb; - - vec3 specularLight = textureLod(prefilteredMap, reflection, lod).rgb; - - vec3 diffuse = diffuseLight * pbrInputs.diffuseColor; - vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y); - - // For presentation, this allows us to disable IBL terms - // For presentation, this allows us to disable IBL terms - diffuse *= ubo.scaleIBLAmbient; - specular *= ubo.scaleIBLAmbient; - - return diffuse + specular; -} - -// Basic Lambertian diffuse -// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog -// See also [1], Equation 1 -vec3 diffuse(PBRInfo pbrInputs) -{ - return pbrInputs.diffuseColor / M_PI; -} - -// The following equation models the Fresnel reflectance term of the spec equation (aka F()) -// Implementation of fresnel from [4], Equation 15 -vec3 specularReflection(PBRInfo pbrInputs) -{ - return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0); -} - -// This calculates the specular geometric attenuation (aka G()), -// where rougher material will reflect less light back to the viewer. -// This implementation is based on [1] Equation 4, and we adopt their modifications to -// alphaRoughness as input as originally proposed in [2]. -float geometricOcclusion(PBRInfo pbrInputs) -{ - float NdotL = pbrInputs.NdotL; - float NdotV = pbrInputs.NdotV; - float r = pbrInputs.alphaRoughness; - - float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL))); - float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV))); - return attenuationL * attenuationV; -} - -// The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D()) -// Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz -// Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3. -float microfacetDistribution(PBRInfo pbrInputs) -{ - float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness; - float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0; - return roughnessSq / (M_PI * f * f); -} - -// Gets metallic factor from specular glossiness workflow inputs -float convertMetallic(vec3 diffuse, vec3 specular, float maxSpecular) { - float perceivedDiffuse = sqrt(0.299 * diffuse.r * diffuse.r + 0.587 * diffuse.g * diffuse.g + 0.114 * diffuse.b * diffuse.b); - float perceivedSpecular = sqrt(0.299 * specular.r * specular.r + 0.587 * specular.g * specular.g + 0.114 * specular.b * specular.b); - if (perceivedSpecular < c_MinRoughness) { - return 0.0; - } - float a = c_MinRoughness; - float b = perceivedDiffuse * (1.0 - maxSpecular) / (1.0 - c_MinRoughness) + perceivedSpecular - 2.0 * c_MinRoughness; - float c = c_MinRoughness - perceivedSpecular; - float D = max(b * b - 4.0 * a * c, 0.0); - return clamp((-b + sqrt(D)) / (2.0 * a), 0.0, 1.0); -} - -void main() -{ - if (subpassLoad(samplerPos, gl_SampleID).a == 1.0f) - discard; - - float perceptualRoughness = subpassLoad(samplerColorRough, gl_SampleID).a; - float metallic = subpassLoad(samplerEmitMetal, gl_SampleID).a; - vec3 diffuseColor; - vec4 baseColor = vec4(subpassLoad(samplerColorRough, gl_SampleID).rgb, 1); - vec3 emissive = subpassLoad (samplerEmitMetal, gl_SampleID).rgb; - - vec3 f0 = vec3(0.04); - - diffuseColor = baseColor.rgb * (vec3(1.0) - f0); - diffuseColor *= 1.0 - metallic; - - float alphaRoughness = perceptualRoughness * perceptualRoughness; - - vec3 specularColor = mix(f0, baseColor.rgb, metallic); - - // Compute reflectance. - float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b); - - // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect. - // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflecance to 0%. - float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0); - vec3 specularEnvironmentR0 = specularColor.rgb; - vec3 specularEnvironmentR90 = vec3(1.0) * reflectance90; - - vec3 n = subpassLoad(samplerN_AO, gl_SampleID).rgb; - vec3 pos = subpassLoad(samplerPos, gl_SampleID).rgb; - vec3 v = normalize(ubo.camPos.xyz - pos); // Vector from surface point to camera - - vec3 colors = vec3(0); - vec3 lightTarget = vec3(0); - - for (int i=0; i<NUM_LIGHTS; i++) { - - vec3 l = normalize(lights[i].position.xyz-pos); // Vector from surface point to light - vec3 h = normalize(l+v); // Half vector between both l and v - vec3 reflection = -normalize(reflect(v, n)); - reflection.y *= -1.0f; - - float NdotL = clamp(dot(n, l), 0.001, 1.0); - float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0); - float NdotH = clamp(dot(n, h), 0.0, 1.0); - float LdotH = clamp(dot(l, h), 0.0, 1.0); - float VdotH = clamp(dot(v, h), 0.0, 1.0); - - PBRInfo pbrInputs = PBRInfo( - NdotL, - NdotV, - NdotH, - LdotH, - VdotH, - perceptualRoughness, - metallic, - specularEnvironmentR0, - specularEnvironmentR90, - alphaRoughness, - diffuseColor, - specularColor - ); - - // Calculate the shading terms for the microfacet specular shading model - vec3 F = specularReflection(pbrInputs); - float G = geometricOcclusion(pbrInputs); - float D = microfacetDistribution(pbrInputs); - - // Calculation of analytical lighting contribution - vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs); - vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV); - // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law) - vec3 color = NdotL * lights[i].color.rgb * (diffuseContrib + specContrib); - // Calculate lighting contribution from image based lighting source (IBL) - colors += (color + getIBLContribution(pbrInputs, n, reflection)); - - - } - colors /= NUM_LIGHTS; - - - const float u_OcclusionStrength = 1.0f; - const float u_EmissiveFactor = 1.0f; - - //AO is in the alpha channel of the normalAttachment - colors = mix(colors, colors * subpassLoad(samplerN_AO, gl_SampleID).a, u_OcclusionStrength); - colors += emissive; - - outColor = vec4(colors, baseColor.a); -}
\ No newline at end of file diff --git a/vke/shaders/deffered/compose_with_shadows.frag b/vke/shaders/deffered/compose_with_shadows.frag deleted file mode 100644 index d8ad270..0000000 --- a/vke/shaders/deffered/compose_with_shadows.frag +++ /dev/null @@ -1,277 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (set = 0, binding = 0) uniform UBO { - mat4 projection; - mat4 model; - mat4 view; - vec4 camPos; - float exposure; - float gamma; - float prefilteredCubeMipLevels; - float scaleIBLAmbient; -} ubo; - -layout (constant_id = 0) const uint NUM_LIGHTS = 1; - -struct Light { - vec4 position; - vec4 color; - mat4 mvp; -}; - -layout (set = 0, binding = 4) uniform UBOLights { - Light lights[NUM_LIGHTS]; -}; - -const float M_PI = 3.141592653589793; -const float c_MinRoughness = 0.04; -#define SHADOW_FACTOR 0.15 - -layout (input_attachment_index = 0, set = 1, binding = 0) uniform subpassInputMS samplerColorRough; -layout (input_attachment_index = 1, set = 1, binding = 1) uniform subpassInputMS samplerEmitMetal; -layout (input_attachment_index = 2, set = 1, binding = 2) uniform subpassInputMS samplerN_AO; -layout (input_attachment_index = 3, set = 1, binding = 3) uniform subpassInputMS samplerPos; - -layout (set = 0, binding = 1) uniform samplerCube samplerIrradiance; -layout (set = 0, binding = 2) uniform samplerCube prefilteredMap; -layout (set = 0, binding = 3) uniform sampler2D samplerBRDFLUT; -layout (set = 0, binding = 6) uniform sampler2DArray samplerShadowMap; - -layout (location = 0) in vec2 inUV; - -layout (location = 0) out vec4 outColor; - -// Encapsulate the various inputs used by the various functions in the shading equation -// We store values in this struct to simplify the integration of alternative implementations -// of the shading terms, outlined in the Readme.MD Appendix. -struct PBRInfo -{ - float NdotL; // cos angle between normal and light direction - float NdotV; // cos angle between normal and view direction - float NdotH; // cos angle between normal and half vector - float LdotH; // cos angle between light direction and half vector - float VdotH; // cos angle between view direction and half vector - float perceptualRoughness; // roughness value, as authored by the model creator (input to shader) - float metalness; // metallic value at the surface - vec3 reflectance0; // full reflectance color (normal incidence angle) - vec3 reflectance90; // reflectance color at grazing angle - float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2]) - vec3 diffuseColor; // color contribution from diffuse lighting - vec3 specularColor; // color contribution from specular lighting -}; - -// Calculation of the lighting contribution from an optional Image Based Light source. -// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1]. -// See our README.md on Environment Maps [3] for additional discussion. -vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection) -{ - float lod = (pbrInputs.perceptualRoughness * ubo.prefilteredCubeMipLevels); - // retrieve a scale and bias to F0. See [1], Figure 3 - vec3 brdf = (texture(samplerBRDFLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb; - vec3 diffuseLight = texture(samplerIrradiance, reflection).rgb; - - vec3 specularLight = textureLod(prefilteredMap, reflection, lod).rgb; - - vec3 diffuse = diffuseLight * pbrInputs.diffuseColor; - vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y); - - // For presentation, this allows us to disable IBL terms - // For presentation, this allows us to disable IBL terms - diffuse *= ubo.scaleIBLAmbient; - specular *= ubo.scaleIBLAmbient; - - return diffuse + specular; -} - -// Basic Lambertian diffuse -// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog -// See also [1], Equation 1 -vec3 diffuse(PBRInfo pbrInputs) -{ - return pbrInputs.diffuseColor / M_PI; -} - -// The following equation models the Fresnel reflectance term of the spec equation (aka F()) -// Implementation of fresnel from [4], Equation 15 -vec3 specularReflection(PBRInfo pbrInputs) -{ - return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0); -} - -// This calculates the specular geometric attenuation (aka G()), -// where rougher material will reflect less light back to the viewer. -// This implementation is based on [1] Equation 4, and we adopt their modifications to -// alphaRoughness as input as originally proposed in [2]. -float geometricOcclusion(PBRInfo pbrInputs) -{ - float NdotL = pbrInputs.NdotL; - float NdotV = pbrInputs.NdotV; - float r = pbrInputs.alphaRoughness; - - float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL))); - float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV))); - return attenuationL * attenuationV; -} - -// The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D()) -// Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz -// Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3. -float microfacetDistribution(PBRInfo pbrInputs) -{ - float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness; - float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0; - return roughnessSq / (M_PI * f * f); -} - -// Gets metallic factor from specular glossiness workflow inputs -float convertMetallic(vec3 diffuse, vec3 specular, float maxSpecular) { - float perceivedDiffuse = sqrt(0.299 * diffuse.r * diffuse.r + 0.587 * diffuse.g * diffuse.g + 0.114 * diffuse.b * diffuse.b); - float perceivedSpecular = sqrt(0.299 * specular.r * specular.r + 0.587 * specular.g * specular.g + 0.114 * specular.b * specular.b); - if (perceivedSpecular < c_MinRoughness) { - return 0.0; - } - float a = c_MinRoughness; - float b = perceivedDiffuse * (1.0 - maxSpecular) / (1.0 - c_MinRoughness) + perceivedSpecular - 2.0 * c_MinRoughness; - float c = c_MinRoughness - perceivedSpecular; - float D = max(b * b - 4.0 * a * c, 0.0); - return clamp((-b + sqrt(D)) / (2.0 * a), 0.0, 1.0); -} - -float textureProj(vec4 P, float layer, vec2 offset) -{ - float shadow = 1.0; - vec4 shadowCoord = P / P.w; - shadowCoord.st = shadowCoord.st * 0.5 + 0.5; - - if (shadowCoord.z > -1.0 && shadowCoord.z < 1.0) - { - float dist = texture(samplerShadowMap, vec3(shadowCoord.st + offset, layer)).r; - if (shadowCoord.w > 0.0 && dist < shadowCoord.z) - shadow = SHADOW_FACTOR; - }else - shadow = 0.05f;//for debug view out of light proj - - return shadow; -} - -float filterPCF(vec4 sc, float layer) -{ - ivec2 texDim = textureSize(samplerShadowMap, 0).xy; - float scale = 1.5; - float dx = scale * 1.0 / float(texDim.x); - float dy = scale * 1.0 / float(texDim.y); - - float shadowFactor = 0.0; - int count = 0; - int range = 1; - - for (int x = -range; x <= range; x++) - { - for (int y = -range; y <= range; y++) - { - shadowFactor += textureProj(sc, layer, vec2(dx*x, dy*y)); - count++; - } - - } - return shadowFactor / count; -} - -void main() -{ - if (subpassLoad(samplerPos, gl_SampleID).a == 1.0f) - discard; - - float perceptualRoughness = subpassLoad(samplerColorRough, gl_SampleID).a; - float metallic = subpassLoad(samplerEmitMetal, gl_SampleID).a; - vec3 diffuseColor; - vec4 baseColor = vec4(subpassLoad(samplerColorRough, gl_SampleID).rgb, 1); - vec3 emissive = subpassLoad (samplerEmitMetal, gl_SampleID).rgb; - - vec3 f0 = vec3(0.04); - - diffuseColor = baseColor.rgb * (vec3(1.0) - f0); - diffuseColor *= 1.0 - metallic; - - float alphaRoughness = perceptualRoughness * perceptualRoughness; - - vec3 specularColor = mix(f0, baseColor.rgb, metallic); - - // Compute reflectance. - float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b); - - // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect. - // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflecance to 0%. - float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0); - vec3 specularEnvironmentR0 = specularColor.rgb; - vec3 specularEnvironmentR90 = vec3(1.0) * reflectance90; - - vec3 n = subpassLoad(samplerN_AO, gl_SampleID).rgb; - vec3 pos = subpassLoad(samplerPos, gl_SampleID).rgb; - vec3 v = normalize(ubo.camPos.xyz - pos); // Vector from surface point to camera - - vec3 colors = vec3(0); - vec3 lightTarget = vec3(0); - - for (int i=0; i<NUM_LIGHTS; i++) { - - vec3 l = normalize(lights[i].position.xyz-pos); // Vector from surface point to light - vec3 h = normalize(l+v); // Half vector between both l and v - vec3 reflection = -normalize(reflect(v, n)); - reflection.y *= -1.0f; - - float NdotL = clamp(dot(n, l), 0.001, 1.0); - float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0); - float NdotH = clamp(dot(n, h), 0.0, 1.0); - float LdotH = clamp(dot(l, h), 0.0, 1.0); - float VdotH = clamp(dot(v, h), 0.0, 1.0); - - PBRInfo pbrInputs = PBRInfo( - NdotL, - NdotV, - NdotH, - LdotH, - VdotH, - perceptualRoughness, - metallic, - specularEnvironmentR0, - specularEnvironmentR90, - alphaRoughness, - diffuseColor, - specularColor - ); - - // Calculate the shading terms for the microfacet specular shading model - vec3 F = specularReflection(pbrInputs); - float G = geometricOcclusion(pbrInputs); - float D = microfacetDistribution(pbrInputs); - - // Calculation of analytical lighting contribution - vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs); - vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV); - // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law) - vec4 shadowClip = lights[i].mvp * vec4(pos, 1); - float shadowFactor = filterPCF(shadowClip, i); - - - vec3 color = NdotL * lights[i].color.rgb * (diffuseContrib + specContrib); - - // Calculate lighting contribution from image based lighting source (IBL) - colors += shadowFactor * (color + getIBLContribution(pbrInputs, n, reflection)); - - - } - colors /= NUM_LIGHTS; - - - const float u_OcclusionStrength = 1.0f; - const float u_EmissiveFactor = 1.0f; - - //AO is in the alpha channel of the normalAttachment - colors = mix(colors, colors * subpassLoad(samplerN_AO, gl_SampleID).a, u_OcclusionStrength); - colors += emissive; - - outColor = vec4(colors, baseColor.a); -}
\ No newline at end of file diff --git a/vke/shaders/deffered/show_gbuff.frag b/vke/shaders/deffered/show_gbuff.frag deleted file mode 100644 index 7859e36..0000000 --- a/vke/shaders/deffered/show_gbuff.frag +++ /dev/null @@ -1,92 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (input_attachment_index = 0, set = 1, binding = 0) uniform subpassInputMS samplerColorRough; -layout (input_attachment_index = 1, set = 1, binding = 1) uniform subpassInputMS samplerEmitMetal; -layout (input_attachment_index = 2, set = 1, binding = 2) uniform subpassInputMS samplerN_AO; -layout (input_attachment_index = 3, set = 1, binding = 3) uniform subpassInputMS samplerPos; - -layout (set = 0, binding = 1) uniform samplerCube samplerIrradiance; -layout (set = 0, binding = 2) uniform samplerCube prefilteredMap; -layout (set = 0, binding = 3) uniform sampler2D samplerBRDFLUT; -layout (set = 0, binding = 6) uniform sampler2DArray samplerShadowMap; - -layout (push_constant) uniform PushCsts { - layout(offset = 64) - int imgIdx; -}; - -layout (location = 0) in vec2 inUV; -layout (location = 0) out vec4 outColor; - -const uint color = 0; -const uint normal = 1; -const uint pos = 2; -const uint occlusion = 3; -const uint emissive = 4; -const uint metallic = 5; -const uint roughness = 6; -const uint depth = 7; -const uint prefill = 8; -const uint irradiance = 9; -const uint shadowMap = 10; - -vec4 sampleCubeMap (samplerCube sc, uint face, uint lod) { - vec2 uv = 2.0 * inUV - vec2(1.0); - switch (face) { - case 0: - return vec4 (textureLod (sc, vec3(1, uv.t, uv.s), lod).rgb, 1); - case 1: - return vec4 (textureLod (sc, vec3(-1, uv.t, uv.s), lod).rgb, 1); - case 2: - return vec4 (textureLod (sc, vec3(uv.s, 1, -uv.t), lod).rgb, 1); - case 3: - return vec4 (textureLod (sc, vec3(uv.s, -1, uv.t), lod).rgb, 1); - case 4: - return vec4 (textureLod (sc, vec3(uv, 1), lod).rgb, 1); - case 5: - return vec4 (textureLod (sc, vec3(-uv.s, uv.t, -1), lod).rgb, 1); - } -} - -void main() -{ - uint imgNum = bitfieldExtract (imgIdx, 0, 8); - switch (imgNum) { - case color: - outColor = vec4(subpassLoad(samplerColorRough, gl_SampleID).rgb, 1); - break; - case normal: - outColor = vec4(subpassLoad(samplerN_AO, gl_SampleID).rgb, 1); - break; - case pos: - outColor = vec4(subpassLoad(samplerPos, gl_SampleID).rgb, 1); - break; - case occlusion: - outColor = vec4(subpassLoad(samplerN_AO, gl_SampleID).aaa, 1); - break; - case emissive: - outColor = vec4(subpassLoad(samplerEmitMetal, gl_SampleID).rgb, 1); - break; - case metallic: - outColor = vec4(subpassLoad(samplerEmitMetal, gl_SampleID).aaa, 1); - break; - case roughness: - outColor = vec4(subpassLoad(samplerColorRough, gl_SampleID).aaa, 1); - break; - case depth: - outColor = vec4(subpassLoad(samplerPos, gl_SampleID).aaa, 1); - break; - case shadowMap: - vec3 d = texture(samplerShadowMap, vec3(inUV, bitfieldExtract (imgIdx, 8, 8))).rrr; - outColor = vec4(d*d*d, 1); - break; - default: - if (imgNum == prefill) - outColor = sampleCubeMap (prefilteredMap, bitfieldExtract (imgIdx, 8, 8), bitfieldExtract (imgIdx, 16, 8)); - else if (imgNum == irradiance) - outColor = sampleCubeMap (samplerIrradiance, bitfieldExtract (imgIdx, 8, 8), bitfieldExtract (imgIdx, 16, 8)); - break; - } -}
\ No newline at end of file diff --git a/vke/shaders/deffered/tone_mapping.frag b/vke/shaders/deffered/tone_mapping.frag deleted file mode 100644 index d4053a7..0000000 --- a/vke/shaders/deffered/tone_mapping.frag +++ /dev/null @@ -1,61 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (set = 0, binding = 0) uniform UBO { - mat4 projection; - mat4 model; - mat4 view; - vec4 camPos; - float exposure; - float gamma; -} ubo; - -layout (input_attachment_index = 0, set = 1, binding = 4) uniform subpassInputMS samplerHDR; -layout (set = 0, binding = 8) uniform sampler2D downSamp; - -layout (location = 0) in vec2 inUV; -layout (location = 0) out vec4 outColor; - -vec3 Uncharted2Tonemap(vec3 color) -{ - const float A = 0.15; - const float B = 0.50; - const float C = 0.10; - const float D = 0.20; - const float E = 0.02; - const float F = 0.30; - const float W = 11.2; - return ((color*(A*color+C*B)+D*E)/(color*(A*color+B)+D*F))-E/F; -} - -vec3 tonemap(vec3 color) -{ - vec3 outcol = Uncharted2Tonemap(color.rgb * ubo.exposure); - outcol = outcol * (1.0f / Uncharted2Tonemap(vec3(11.2f))); - return pow(outcol, vec3(1.0f / ubo.gamma)); -} - -vec3 SRGBtoLINEAR(vec3 srgbIn) -{ - #ifdef MANUAL_SRGB - #ifdef SRGB_FAST_APPROXIMATION - return pow(srgbIn.xyz,vec3(2.2)); - #else //SRGB_FAST_APPROXIMATION - vec3 bLess = step(vec3(0.04045),srgbIn.xyz); - return linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess ); - #endif //SRGB_FAST_APPROXIMATION - #else //MANUAL_SRGB - return srgbIn; - #endif //MANUAL_SRGB -} - -void main() -{ - vec4 hdrColor = subpassLoad(samplerHDR, gl_SampleID); - outColor = vec4(SRGBtoLINEAR(tonemap(hdrColor.rgb)), hdrColor.a); - /* - vec3 mapped = vec3(1.0) - exp(-hdrColor.rgb * ubo.exposure); - mapped = pow(mapped, vec3(1.0 / ubo.gamma)); - outColor = vec4(mapped, hdrColor.a);*/ -}
\ No newline at end of file diff --git a/vke/shaders/emissive.frag b/vke/shaders/emissive.frag deleted file mode 100644 index 2efe331..0000000 --- a/vke/shaders/emissive.frag +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (input_attachment_index = 0, set = 2, binding = 0) uniform subpassInputMS samplerColorRough; -layout (input_attachment_index = 1, set = 2, binding = 1) uniform subpassInputMS samplerEmitMetal; -layout (input_attachment_index = 2, set = 2, binding = 2) uniform subpassInputMS samplerN_AO; -layout (input_attachment_index = 3, set = 2, binding = 3) uniform subpassInputMS samplerPos; - -layout (location = 0) in vec2 inUV; - -layout (location = 0) out vec4 outColor; - -const float offset[5] = float[](0.0, 1.0, 2.0, 3.0, 4.0); -const float weight[5] = float[](0.2270270270, 0.1945945946, 0.1216216216, - 0.0540540541, 0.0162162162); - -void main() -{ - if (subpassLoad(samplerPos, gl_SampleID).a == 1.0f) - discard; - vec3 emissive = subpassLoad (samplerEmitMetal, gl_SampleID).rgb; - - outColor = vec4(emissive, 1); -}
\ No newline at end of file diff --git a/vke/shaders/filtercube.vert b/vke/shaders/filtercube.vert deleted file mode 100644 index 1226e28..0000000 --- a/vke/shaders/filtercube.vert +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout (location = 0) in vec3 inPos; - -layout(push_constant) uniform PushConsts { - layout (offset = 0) mat4 mvp; -} pushConsts; - -layout (location = 0) out vec3 outUVW; - -out gl_PerVertex { - vec4 gl_Position; -}; - -void main() -{ - outUVW = inPos; - gl_Position = pushConsts.mvp * vec4(inPos.xyz, 1.0); -} diff --git a/vke/shaders/genbrdflut.frag b/vke/shaders/genbrdflut.frag deleted file mode 100644 index b6290dd..0000000 --- a/vke/shaders/genbrdflut.frag +++ /dev/null @@ -1,90 +0,0 @@ -#version 450 - -layout (location = 0) in vec2 inUV; -layout (location = 0) out vec4 outColor; -layout (constant_id = 0) const uint NUM_SAMPLES = 1024u; - -const float PI = 3.1415926536; - -// Based omn http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ -float random(vec2 co) -{ - float a = 12.9898; - float b = 78.233; - float c = 43758.5453; - float dt= dot(co.xy ,vec2(a,b)); - float sn= mod(dt,3.14); - return fract(sin(sn) * c); -} - -vec2 hammersley2d(uint i, uint N) -{ - // Radical inverse based on http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html - uint bits = (i << 16u) | (i >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - float rdi = float(bits) * 2.3283064365386963e-10; - return vec2(float(i) /float(N), rdi); -} - -// Based on http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_slides.pdf -vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal) -{ - // Maps a 2D point to a hemisphere with spread based on roughness - float alpha = roughness * roughness; - float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1; - float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha*alpha - 1.0) * Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta * cosTheta); - vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); - - // Tangent space - vec3 up = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 tangentX = normalize(cross(up, normal)); - vec3 tangentY = normalize(cross(normal, tangentX)); - - // Convert to world Space - return normalize(tangentX * H.x + tangentY * H.y + normal * H.z); -} - -// Geometric Shadowing function -float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) -{ - float k = (roughness * roughness) / 2.0; - float GL = dotNL / (dotNL * (1.0 - k) + k); - float GV = dotNV / (dotNV * (1.0 - k) + k); - return GL * GV; -} - -vec2 BRDF(float NoV, float roughness) -{ - // Normal always points along z-axis for the 2D lookup - const vec3 N = vec3(0.0, 0.0, 1.0); - vec3 V = vec3(sqrt(1.0 - NoV*NoV), 0.0, NoV); - - vec2 LUT = vec2(0.0); - for(uint i = 0u; i < NUM_SAMPLES; i++) { - vec2 Xi = hammersley2d(i, NUM_SAMPLES); - vec3 H = importanceSample_GGX(Xi, roughness, N); - vec3 L = 2.0 * dot(V, H) * H - V; - - float dotNL = max(dot(N, L), 0.0); - float dotNV = max(dot(N, V), 0.0); - float dotVH = max(dot(V, H), 0.0); - float dotNH = max(dot(H, N), 0.0); - - if (dotNL > 0.0) { - float G = G_SchlicksmithGGX(dotNL, dotNV, roughness); - float G_Vis = (G * dotVH) / (dotNH * dotNV); - float Fc = pow(1.0 - dotVH, 5.0); - LUT += vec2((1.0 - Fc) * G_Vis, Fc * G_Vis); - } - } - return LUT / float(NUM_SAMPLES); -} - -void main() -{ - outColor = vec4(BRDF(inUV.s, 1.0-inUV.t), 0.0, 1.0); -}
\ No newline at end of file diff --git a/vke/shaders/genbrdflut.vert b/vke/shaders/genbrdflut.vert deleted file mode 100644 index f3dd233..0000000 --- a/vke/shaders/genbrdflut.vert +++ /dev/null @@ -1,9 +0,0 @@ -#version 450 - -layout (location = 0) out vec2 outUV; - -void main() -{ - outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); - gl_Position = vec4(outUV * 2.0f - 1.0f, 0.0f, 1.0f); -}
\ No newline at end of file diff --git a/vke/shaders/irradiancecube.frag b/vke/shaders/irradiancecube.frag deleted file mode 100644 index 340d679..0000000 --- a/vke/shaders/irradiancecube.frag +++ /dev/null @@ -1,37 +0,0 @@ -// Generates an irradiance cube from an environment map using convolution - -#version 450 - -layout (location = 0) in vec3 inPos; -layout (location = 0) out vec4 outColor; -layout (binding = 0) uniform samplerCube samplerEnv; - -layout(push_constant) uniform PushConsts { - layout (offset = 64) float deltaPhi; - layout (offset = 68) float deltaTheta; -} consts; - -#define PI 3.1415926535897932384626433832795 - -void main() -{ - vec3 N = normalize(inPos); - vec3 up = vec3(0.0, 1.0, 0.0); - vec3 right = normalize(cross(up, N)); - up = cross(N, right); - - const float TWO_PI = PI * 2.0; - const float HALF_PI = PI * 0.5; - - vec3 color = vec3(0.0); - uint sampleCount = 0u; - for (float phi = 0.0; phi < TWO_PI; phi += consts.deltaPhi) { - for (float theta = 0.0; theta < HALF_PI; theta += consts.deltaTheta) { - vec3 tempVec = cos(phi) * right + sin(phi) * up; - vec3 sampleVector = cos(theta) * N + sin(theta) * tempVec; - color += texture(samplerEnv, sampleVector).rgb * cos(theta) * sin(theta); - sampleCount++; - } - } - outColor = vec4(PI * color / float(sampleCount), 1.0);//texture(samplerEnv, inPos).rgba; -} diff --git a/vke/shaders/prefilterenvmap.frag b/vke/shaders/prefilterenvmap.frag deleted file mode 100644 index ae1212e..0000000 --- a/vke/shaders/prefilterenvmap.frag +++ /dev/null @@ -1,105 +0,0 @@ -#version 450 - -layout (location = 0) in vec3 inPos; -layout (location = 0) out vec4 outColor; - -layout (binding = 0) uniform samplerCube samplerEnv; - -layout(push_constant) uniform PushConsts { - layout (offset = 64) float roughness; - layout (offset = 68) uint numSamples; -} consts; - -const float PI = 3.1415926536; - -// Based omn http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/ -float random(vec2 co) -{ - float a = 12.9898; - float b = 78.233; - float c = 43758.5453; - float dt= dot(co.xy ,vec2(a,b)); - float sn= mod(dt,3.14); - return fract(sin(sn) * c); -} - -vec2 hammersley2d(uint i, uint N) -{ - // Radical inverse based on http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html - uint bits = (i << 16u) | (i >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - float rdi = float(bits) * 2.3283064365386963e-10; - return vec2(float(i) /float(N), rdi); -} - -// Based on http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_slides.pdf -vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal) -{ - // Maps a 2D point to a hemisphere with spread based on roughness - float alpha = roughness * roughness; - float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1; - float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha*alpha - 1.0) * Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta * cosTheta); - vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta); - - // Tangent space - vec3 up = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 tangentX = normalize(cross(up, normal)); - vec3 tangentY = normalize(cross(normal, tangentX)); - - // Convert to world Space - return normalize(tangentX * H.x + tangentY * H.y + normal * H.z); -} - -// Normal Distribution function -float D_GGX(float dotNH, float roughness) -{ - float alpha = roughness * roughness; - float alpha2 = alpha * alpha; - float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; - return (alpha2)/(PI * denom*denom); -} - -vec3 prefilterEnvMap(vec3 R, float roughness) -{ - vec3 N = R; - vec3 V = R; - vec3 color = vec3(0.0); - float totalWeight = 0.0; - float envMapDim = float(textureSize(samplerEnv, 0).s); - for(uint i = 0u; i < consts.numSamples; i++) { - vec2 Xi = hammersley2d(i, consts.numSamples); - vec3 H = importanceSample_GGX(Xi, roughness, N); - vec3 L = 2.0 * dot(V, H) * H - V; - float dotNL = clamp(dot(N, L), 0.0, 1.0); - if(dotNL > 0.0) { - // Filtering based on https://placeholderart.wordpress.com/2015/07/28/implementation-notes-runtime-environment-map-filtering-for-image-based-lighting/ - - float dotNH = clamp(dot(N, H), 0.0, 1.0); - float dotVH = clamp(dot(V, H), 0.0, 1.0); - - // Probability Distribution Function - float pdf = D_GGX(dotNH, roughness) * dotNH / (4.0 * dotVH) + 0.0001; - // Slid angle of current smple - float omegaS = 1.0 / (float(consts.numSamples) * pdf); - // Solid angle of 1 pixel across all cube faces - float omegaP = 4.0 * PI / (6.0 * envMapDim * envMapDim); - // Biased (+1.0) mip level for better result - float mipLevel = roughness == 0.0 ? 0.0 : max(0.5 * log2(omegaS / omegaP) + 1.0, 0.0f); - color += textureLod(samplerEnv, L, mipLevel).rgb * dotNL; - totalWeight += dotNL; - - } - } - return (color / totalWeight); -} - - -void main() -{ - vec3 N = normalize(inPos); - outColor = vec4(prefilterEnvMap(N, consts.roughness), 1.0); -} diff --git a/vke/shaders/shadow.geom b/vke/shaders/shadow.geom deleted file mode 100644 index 283586d..0000000 --- a/vke/shaders/shadow.geom +++ /dev/null @@ -1,37 +0,0 @@ -#version 420 - -#define NUM_LIGHTS 2 - -layout (triangles, invocations = NUM_LIGHTS) in; -layout (triangle_strip, max_vertices = 3) out; - -struct Light { - vec4 position; - vec4 color; - mat4 mvp; -}; -layout (set = 0, binding = 0) uniform UBO { - mat4 projection; - mat4 model; - mat4 view; -}; -layout (set = 0, binding = 1) uniform UBOLights { - Light lights[NUM_LIGHTS]; -}; - -//layout (location = 0) in int inInstanceIndex[]; - -layout(push_constant) uniform PushConsts { - mat4 model; -} pc; - -void main() -{ - for (int i = 0; i < gl_in.length(); i++) - { - gl_Layer = gl_InvocationID; - gl_Position = lights[gl_InvocationID].mvp * model * pc.model * gl_in[i].gl_Position; - EmitVertex(); - } - EndPrimitive(); -}
\ No newline at end of file diff --git a/vke/shaders/shadow.vert b/vke/shaders/shadow.vert deleted file mode 100644 index 548f093..0000000 --- a/vke/shaders/shadow.vert +++ /dev/null @@ -1,8 +0,0 @@ -#version 450 - -layout (location = 0) in vec4 inPos; - -void main() -{ - gl_Position = inPos; -}
\ No newline at end of file diff --git a/vke/shaders/simpletexture.frag b/vke/shaders/simpletexture.frag index a081876..cee63cb 100644 --- a/vke/shaders/simpletexture.frag +++ b/vke/shaders/simpletexture.frag @@ -3,13 +3,13 @@ #extension GL_ARB_separate_shader_objects : enable #extension GL_ARB_shading_language_420pack : enable -layout (set = 0, binding = 0) uniform sampler2D samplerColor; +layout (set = 0, binding = 1) uniform sampler2D samplerColor; layout (location = 0) in vec2 inUV; layout (location = 0) out vec4 outFragColor; void main() -{ +{ outFragColor = texture(samplerColor, inUV); } diff --git a/vke/shaders/skybox.frag b/vke/shaders/skybox.frag deleted file mode 100644 index e505ef1..0000000 --- a/vke/shaders/skybox.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 450 - -layout (binding = 2) uniform samplerCube samplerEnv; - -layout (set = 0, location = 0) in vec3 inUVW; - -layout (set = 0, location = 0) out vec4 outColor; - -void main() -{ - outColor = vec4(textureLod(samplerEnv, inUVW, 1.5).rgb, 1.0); -}
\ No newline at end of file diff --git a/vke/shaders/skybox.vert b/vke/shaders/skybox.vert deleted file mode 100644 index 22e285e..0000000 --- a/vke/shaders/skybox.vert +++ /dev/null @@ -1,27 +0,0 @@ -#version 450 - -#extension GL_ARB_separate_shader_objects : enable -#extension GL_ARB_shading_language_420pack : enable - -layout (location = 0) in vec3 inPos; - -layout (binding = 0) uniform UBO -{ - mat4 projection; - mat4 model; - mat4 view; -} ubo; - -layout (location = 0) out vec3 outUVW; - -out gl_PerVertex -{ - vec4 gl_Position; -}; - -void main() -{ - outUVW = inPos; - outUVW.y = -outUVW.y; - gl_Position = ubo.projection * mat4(mat3(ubo.view)) * vec4(inPos, 1.0); -} diff --git a/vke/src/VkWindow.cs b/vke/src/VkWindow.cs index 5f329d6..3b2b953 100644 --- a/vke/src/VkWindow.cs +++ b/vke/src/VkWindow.cs @@ -1,28 +1,6 @@ -// -// VkWindow.cs +// Copyright (c) 2019 Jean-Philippe Bruyère <jp_bruyere@hotmail.com> // -// Author: -// Jean-Philippe Bruyère <jp_bruyere@hotmail.com> -// -// Copyright (c) 2019 jp -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. +// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) using System; using System.Linq; using System.Diagnostics; @@ -54,7 +32,7 @@ namespace CVKL { DebugReport dbgRepport; protected uint fps; - protected bool updateViewRequested = true, rebuildBuffers; + protected bool updateViewRequested = true; protected double lastMouseX, lastMouseY; protected bool[] MouseButton => buttons; @@ -143,7 +121,7 @@ namespace CVKL { //activate the device to have effective queues created accordingly to what's available dev.Activate (enabledFeatures, EnabledDeviceExtensions); - swapChain = new SwapChain (presentQueue as PresentQueue, width, height, VkFormat.B8g8r8a8Srgb, + swapChain = new SwapChain (presentQueue as PresentQueue, width, height, VkFormat.B8g8r8a8Unorm, vSync ? VkPresentModeKHR.FifoKHR : VkPresentModeKHR.MailboxKHR); swapChain.Create (); diff --git a/vke/src/base/CommandBuffer.cs b/vke/src/base/CommandBuffer.cs index be14fc3..0c381a7 100644 --- a/vke/src/base/CommandBuffer.cs +++ b/vke/src/base/CommandBuffer.cs @@ -10,23 +10,28 @@ using static VK.Vk; namespace CVKL { /// <summary> + /// Command buffers are objects used to record commands which can be subsequently submitted to a device queue for execution. + /// There are two levels of command buffers + /// - primary command buffers, which can execute secondary command buffers, and which are submitted to queues + /// - secondary command buffers, which can be executed by primary command buffers, and which are not directly submitted to queues. /// Command buffer are not derived from activable, because their state is retained by the pool which create them. /// </summary> - public class CommandBuffer { - public enum States { Init, Record, Pending, Invalid }; + public class CommandBuffer { + public enum States { Init, Record, Executable, Pending, Invalid }; CommandPool pool; VkCommandBuffer handle; - //States state; public VkCommandBuffer Handle => handle; public Device Device => pool?.Dev;//this help - //public States State => state; + //public States State { get; internal set; } internal CommandBuffer (VkDevice _dev, CommandPool _pool, VkCommandBuffer _buff) { pool = _pool; handle = _buff; + + //State = States.Init; } @@ -87,13 +92,25 @@ namespace CVKL { VkRect2D scissor = new VkRect2D (offsetX, offsetY, width, height); vkCmdSetScissor (handle, 0, 1, ref scissor); } - public void BindPipeline (Pipeline pipeline, VkPipelineBindPoint bindPoint = VkPipelineBindPoint.Graphics) { + public void BindPipeline (Pipeline pipeline, VkPipelineBindPoint bindPoint) { vkCmdBindPipeline (handle, bindPoint, pipeline.Handle); } public void Dispatch (uint groupCountX, uint groupCountY = 1, uint groupCountZ = 1) { vkCmdDispatch (handle, groupCountX, groupCountY, groupCountZ); } - + public void BindPipeline (Pipeline pl) { + pl.Bind (this); + } + /// <summary> + /// bind pipeline and descriptor set with default pipeline layout + /// </summary> + /// <param name="pl">pipeline to bind</param> + /// <param name="ds">descriptor set</param> + /// <param name="firstset">first set to bind</param> + public void BindPipeline (Pipeline pl, DescriptorSet ds, uint firstset = 0) { + pl.Bind (this); + pl.BindDescriptorSet (this, ds, firstset); + } public void BindDescriptorSet (PipelineLayout pipelineLayout, DescriptorSet descriptorSet, uint firstSet = 0) { vkCmdBindDescriptorSets (handle, VkPipelineBindPoint.Graphics, pipelineLayout.handle, firstSet, 1, ref descriptorSet.handle, 0, IntPtr.Zero); } @@ -106,7 +123,7 @@ namespace CVKL { public void BindIndexBuffer (Buffer indices, VkIndexType indexType = VkIndexType.Uint32, ulong offset = 0) { vkCmdBindIndexBuffer (handle, indices.handle, offset, indexType); } - public void DrawIndexed (uint indexCount, uint instanceCount = 1, uint firstIndex = 0, int vertexOffset = 0, uint firstInstance = 1) { + public void DrawIndexed (uint indexCount, uint instanceCount = 1, uint firstIndex = 0, int vertexOffset = 0, uint firstInstance = 0) { vkCmdDrawIndexed (Handle, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance); } public void Draw (uint vertexCount, uint instanceCount = 1, uint firstVertex = 0, uint firstInstance = 0) { @@ -116,6 +133,9 @@ namespace CVKL { vkCmdPushConstants (handle, pipelineLayout.handle, stageFlags, offset, (uint)Marshal.SizeOf (data), data.Pin ()); data.Unpin (); } + public void PushConstant (Pipeline pipeline, object obj, int rangeIndex = 0, uint offset = 0) { + PushConstant (pipeline.Layout, pipeline.Layout.PushConstantRanges[rangeIndex].stageFlags, obj, offset); + } public void PushConstant (PipelineLayout pipelineLayout, VkShaderStageFlags stageFlags, uint size, Object data, uint offset = 0) { vkCmdPushConstants (handle, pipelineLayout.handle, stageFlags, offset, size, data.Pin ()); data.Unpin (); diff --git a/vke/src/base/CommandPool.cs b/vke/src/base/CommandPool.cs index 255ecfc..3317733 100644 --- a/vke/src/base/CommandPool.cs +++ b/vke/src/base/CommandPool.cs @@ -8,17 +8,30 @@ using VK; using static VK.Vk; namespace CVKL { - public sealed class CommandPool : Activable { + /// <summary> + /// Command pools are opaque objects that command buffer memory is allocated from, and which allow the implementation + /// to amortize the cost of resource creation across multiple command buffers. + /// </summary> + public sealed class CommandPool : Activable { public readonly uint QFamIndex; VkCommandPool handle; #region CTORS + /// <summary> + /// Create and activate a new Command Pool. + /// </summary> + /// <param name="device">Vulkan Device.</param> + /// <param name="qFamIdx">Queue family index.</param> public CommandPool (Device device, uint qFamIdx) : base(device) { QFamIndex = qFamIdx; Activate (); } + /// <summary> + /// Initializes a new instance of the [[CommandPool]]"/> class. + /// </summary> + /// <param name="queue">Device Queue of the queue family to create the pool for.</param> public CommandPool (Queue queue) : this(queue.dev, queue.qFamIndex) {} #endregion @@ -33,8 +46,13 @@ namespace CVKL { } base.Activate (); } - - public CommandBuffer AllocateCommandBuffer (VkCommandBufferLevel level = VkCommandBufferLevel.Primary) { + /// <summary> + /// Allocates single command buffer. + /// When command buffers are first allocated, they are in the initial state. + /// </summary> + /// <returns>The command buffer in the Init state.</returns> + /// <param name="level">Command Buffer Level.</param> + public CommandBuffer AllocateCommandBuffer (VkCommandBufferLevel level = VkCommandBufferLevel.Primary) { VkCommandBuffer buff; VkCommandBufferAllocateInfo infos = VkCommandBufferAllocateInfo.New(); infos.commandPool = handle; @@ -45,6 +63,12 @@ namespace CVKL { return new CommandBuffer (Dev.VkDev, this, buff); } + /// <summary> + /// Allocates multiple command buffer. + /// </summary> + /// <returns>An array of command buffers alloocated from this pool.</returns> + /// <param name="count">Buffer count to create.</param> + /// <param name="level">Command Buffer Level.</param> public CommandBuffer[] AllocateCommandBuffer (uint count, VkCommandBufferLevel level = VkCommandBufferLevel.Primary) { VkCommandBufferAllocateInfo infos = VkCommandBufferAllocateInfo.New (); infos.commandPool = handle; @@ -59,16 +83,32 @@ namespace CVKL { return cmds; } + /// <summary> + /// Resetting a command pool recycles all of the resources from all of the command buffers allocated from the command + /// pool back to the command pool. All command buffers that have been allocated from the command pool are put in the initial state. + /// Any primary command buffer allocated from another VkCommandPool that is in the recording or executable state and has a secondary + /// command buffer allocated from commandPool recorded into it, becomes invalid. + /// </summary> + /// <param name="flags">Set `ReleaseResources` flag to recycles all of the resources from the command pool back to the system.</param> public void Reset (VkCommandPoolResetFlags flags = 0) { Vk.vkResetCommandPool (Dev.VkDev, handle, flags); } - + /// <summary> + /// Allocates a new command buffer and automatically start it. + /// </summary> + /// <returns>New command buffer in the recording state.</returns> + /// <param name="usage">Usage.</param> + /// <param name="level">Command buffer level, primary or secondary.</param> public CommandBuffer AllocateAndStart (VkCommandBufferUsageFlags usage = 0, VkCommandBufferLevel level = VkCommandBufferLevel.Primary) { CommandBuffer cmd = AllocateCommandBuffer (level); cmd.Start (usage); return cmd; } - public void FreeCommandBuffers (params CommandBuffer[] cmds) { + /// <summary> + /// Any primary command buffer that is in the recording or executable state and has any element of the command buffer list recorded into it, becomes invalid. + /// </summary> + /// <param name="cmds">Command buffer list to free.</param> + public void FreeCommandBuffers (params CommandBuffer[] cmds) { if (cmds.Length == 1) { VkCommandBuffer hnd = cmds[0].Handle; vkFreeCommandBuffers (Dev.VkDev, handle, 1, ref hnd); diff --git a/vke/src/base/GPUBuffer.cs b/vke/src/base/GPUBuffer.cs index 061dd65..61504fd 100644 --- a/vke/src/base/GPUBuffer.cs +++ b/vke/src/base/GPUBuffer.cs @@ -41,8 +41,12 @@ namespace CVKL { /// Device local Buffer /// </summary> public class GPUBuffer<T> : GPUBuffer { - public GPUBuffer (Device device, VkBufferUsageFlags usage, int elementCount) + + public int ElementCount { get; private set; } + + public GPUBuffer (Device device, VkBufferUsageFlags usage, int elementCount) : base (device, usage, (ulong)(Marshal.SizeOf<T> () * elementCount)) { + ElementCount = elementCount; } public GPUBuffer (Queue staggingQ, CommandPool staggingCmdPool, VkBufferUsageFlags usage, T[] elements) : base (staggingQ.Dev, usage | VkBufferUsageFlags.TransferDst, (ulong)(Marshal.SizeOf<T> () * elements.Length)) { diff --git a/vke/src/base/GraphicPipelineConfig.cs b/vke/src/base/GraphicPipelineConfig.cs index 4a21a78..6ccd3f2 100644 --- a/vke/src/base/GraphicPipelineConfig.cs +++ b/vke/src/base/GraphicPipelineConfig.cs @@ -55,6 +55,10 @@ namespace CVKL { } + /// <summary> + /// Create a default pipeline configuration with viewport and scissor as dynamic states. One blend attachment is + /// added automatically with blending disabled. (cfg.blendAttachments[0]) + /// </summary> public static GraphicPipelineConfig CreateDefault (VkPrimitiveTopology topology = VkPrimitiveTopology.TriangleList, VkSampleCountFlags samples = VkSampleCountFlags.SampleCount1, bool depthTestEnabled = true) { diff --git a/vke/src/base/Pipeline.cs b/vke/src/base/Pipeline.cs index 9a6b3aa..3e6eac3 100644 --- a/vke/src/base/Pipeline.cs +++ b/vke/src/base/Pipeline.cs @@ -49,6 +49,10 @@ namespace CVKL { public abstract void Bind (CommandBuffer cmd); public abstract void BindDescriptorSet (CommandBuffer cmd, DescriptorSet dset, uint firstSet = 0); + public void PushConstant (CommandBuffer cmd, object obj, int rangeIndex = 0, uint offset = 0) { + cmd.PushConstant (layout, layout.PushConstantRanges[rangeIndex].stageFlags, obj, offset); + } + protected override void Dispose (bool disposing) { if (state == ActivableState.Activated) { diff --git a/vke/src/base/RenderPass.cs b/vke/src/base/RenderPass.cs index 40401d5..773c436 100644 --- a/vke/src/base/RenderPass.cs +++ b/vke/src/base/RenderPass.cs @@ -57,8 +57,8 @@ namespace CVKL { Samples = samples; AddAttachment (colorFormat, (samples == VkSampleCountFlags.SampleCount1) ? VkImageLayout.PresentSrcKHR : VkImageLayout.ColorAttachmentOptimal, samples, - VkAttachmentLoadOp.Load, VkAttachmentStoreOp.Store, VkImageLayout.ColorAttachmentOptimal); - ClearValues.Add (new VkClearValue { color = new VkClearColorValue (0.0f, 0.0f, 0.0f) }); + VkAttachmentLoadOp.Clear, VkAttachmentStoreOp.Store, VkImageLayout.ColorAttachmentOptimal); + ClearValues.Add (new VkClearValue { color = new VkClearColorValue (0.0f, 0.0f, 0.2f) }); SubPass subpass0 = new SubPass (); subpass0.AddColorReference (0, VkImageLayout.ColorAttachmentOptimal); @@ -80,7 +80,7 @@ namespace CVKL { } /// <summary> - /// Create default renderpass with one color and one depth attachments + /// Create default renderpass with one color and one depth attachments. /// </summary> public RenderPass (Device device, VkFormat colorFormat, VkFormat depthFormat, VkSampleCountFlags samples = VkSampleCountFlags.SampleCount1) : this (device){ |