diff options
| author | Jean-Philippe Bruyère <jp_bruyere@hotmail.com> | 2019-08-24 05:28:31 +0200 |
|---|---|---|
| committer | j-p <jp_bruyere@hotmail.com> | 2019-08-28 11:32:06 +0200 |
| commit | 5be9ee777bf6ab6de674e9437fcc5d4f1d2abdfa (patch) | |
| tree | 53279afaac5a43a44b92d3243e075a9fdd15d615 | |
| parent | ba7dd7651b8ca546077f91e0b3b5610d10d23e00 (diff) | |
debug
38 files changed, 623 insertions, 444 deletions
diff --git a/VK/vulkan.csproj b/VK/vulkan.csproj index 9e7c9ee..0605ba7 100644 --- a/VK/vulkan.csproj +++ b/VK/vulkan.csproj @@ -13,7 +13,6 @@ <PackageVersion>$(AssemblyVersion)-beta</PackageVersion> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> <PackageProjectUrl>https://github.com/jpbruyere/vk.net/blob/master/README.md</PackageProjectUrl> - <PackageLicense>https://opensource.org/licenses/MIT</PackageLicense> <!--<PackageIconUrl>https://github.com/KhronosGroup/glTF/blob/master/specification/figures/gltf.png</PackageIconUrl>--> <SynchReleaseVersion>false</SynchReleaseVersion> <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props new file mode 100644 index 0000000..a2cc0c7 --- /dev/null +++ b/samples/Directory.Build.props @@ -0,0 +1,45 @@ +<Project> + <PropertyGroup> + <RootDirectory>$(MSBuildThisFileDirectory)../</RootDirectory> + <Deterministic>true</Deterministic> + + <TargetFrameworks>net471;netstandard2.0</TargetFrameworks> + + <RepositoryUrl>https://github.com/jpbruyere/vk.net</RepositoryUrl> + <License>MIT</License> + <Authors>Jean-Philippe Bruyère</Authors> + + <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> + <OutputType>Exe</OutputType> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0;_WITH_SHADOWS;_WITH_VKVG</DefineConstants> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DefineConstants>NETSTANDARD;NETSTANDARD2_0;WITH_SHADOWS;_WITH_VKVG</DefineConstants> + </PropertyGroup> + + <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> + <Reference Include="System" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="$(RootDirectory)vke\CVKL.csproj" /> + </ItemGroup> + + <ItemGroup> + <PackageReference Include="Vulkan" Version="0.1.3" /> + </ItemGroup> + + <ItemGroup> + <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert;shaders\**\*.comp;shaders\**\*.geom" /> + <None Remove="shaders\**\*.frag;shaders\**\*.vert" /> + <Datas Include="..\data\**\*.*"> + <Link>data\%(RecursiveDir)%(Filename)%(Extension)</Link> + </Datas> + </ItemGroup> + + <Import Project="$(RootDirectory)spirv.targets" /> +</Project> diff --git a/samples/Model/Model.csproj b/samples/Model/Model.csproj index df98d01..7007288 100644 --- a/samples/Model/Model.csproj +++ b/samples/Model/Model.csproj @@ -1,34 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> - <Import Project="$(RootDirectory)netfx.props" /> - <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - </PropertyGroup> - - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> - + <Import Project="$(RootDirectory)netfx.props" /> <ItemGroup> <PackageReference Include="glTF2Loader" Version="1.1.3-alpha" /> - <PackageReference Include="Vulkan" Version="0.1.3" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\vke\CVKL.csproj" /> </ItemGroup> - - <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert" /> - <None Remove="shaders\**\*.frag;shaders\**\*.vert" /> - </ItemGroup> - - <Import Project="$(SolutionDir)spirv.targets" /> + </Project> diff --git a/samples/Model/main.cs b/samples/Model/main.cs index 95a6e90..f941e5e 100644 --- a/samples/Model/main.cs +++ b/samples/Model/main.cs @@ -9,7 +9,7 @@ namespace ModelSample { static void Main (string[] args) { Instance.VALIDATION = true; - //Instance.DEBUG_UTILS = true; + Instance.DEBUG_UTILS = true; //Instance.RENDER_DOC_CAPTURE = true; using (Program vke = new Program ()) { @@ -47,10 +47,11 @@ namespace ModelSample { float rotX, rotY, rotZ = 0f, zoom = 2f; SimpleModel helmet; - DebugReport dbgReport; + CVKL.DebugUtils.Messenger dbgmsg; Program () : base () { - //dbgReport = new DebugReport (instance); + if (Instance.DEBUG_UTILS) + dbgmsg = new CVKL.DebugUtils.Messenger (instance); descriptorPool = new DescriptorPool (dev, 2, new VkDescriptorPoolSize (VkDescriptorType.UniformBuffer), @@ -65,7 +66,6 @@ namespace ModelSample { new VkDescriptorSetLayoutBinding (2, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler) ); - VkPushConstantRange pushConstantRange = new VkPushConstantRange { stageFlags = VkShaderStageFlags.Vertex, size = (uint)Marshal.SizeOf<PushConstants>(), @@ -249,7 +249,7 @@ namespace ModelSample { frameBuffers[i]?.Dispose (); descriptorPool.Dispose (); uboMats.Dispose (); - dbgReport?.Dispose (); + dbgmsg?.Dispose (); } } diff --git a/samples/Model/shaders/model.frag b/samples/Model/shaders/model.frag index 351f156..e0b131b 100644 --- a/samples/Model/shaders/model.frag +++ b/samples/Model/shaders/model.frag @@ -52,7 +52,7 @@ void main() vec4 diff = texture(samplerColor, inUV); vec3 n = normalize(inN); - vec3 l = normalize(light); + vec3 l = normalize(-light); vec3 pn = perturb_normal(n, inV, inUV); float lambert = max(0.0, dot(pn, l)); @@ -64,7 +64,7 @@ void main() vec3 rd = reflect(l, pn); float s = dot(rd, normalize(inV)); spec = vec3(0.9,0.9,0.9)* //light.specular.xyz * material.specular.xyz * - pow(max(0.0, s), 0.5); //0.5 = mat shininess + pow(max(0.0, s), 10.5); //0.5 = mat shininess } //outFragColor = vec4(1.0); // //outFragColor = vec4(diff.rgb , 1.0); // diff --git a/samples/Model/shaders/model.vert b/samples/Model/shaders/model.vert index d63c794..bfcc2a4 100644 --- a/samples/Model/shaders/model.vert +++ b/samples/Model/shaders/model.vert @@ -34,8 +34,8 @@ void main() mat4 mod = ubo.modelMatrix;// * pc.model; vec4 pos = mod * vec4(inPos.xyz, 1.0); - //outN = normalize(transpose(inverse(mat3(mod))) * inNormal); - outN = normalize(mat3(mod)* inNormal); + outN = normalize(transpose(inverse(mat3(mod))) * inNormal); + //outN = normalize(mat3(mod)* inNormal); mat4 viewInv = inverse(ubo.viewMatrix); outV = -(ubo.viewMatrix * pos).xyz;//normalize(vec3(viewInv * vec4(0.0, 0.0, 0.0, 1.0) - pos)); diff --git a/samples/Textured/Textured.csproj b/samples/Textured/Textured.csproj index 16716c7..1785b4a 100644 --- a/samples/Textured/Textured.csproj +++ b/samples/Textured/Textured.csproj @@ -1,39 +1,8 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> - <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - </PropertyGroup> - - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> <ItemGroup> <PackageReference Include="glTF2Loader" Version="1.1.3-alpha" /> - <PackageReference Include="Vulkan" Version="0.1.3" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\vke\CVKL.csproj"> - </ProjectReference> - </ItemGroup> + </ItemGroup> - <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert" /> - <None Remove="shaders\**\*.frag;shaders\**\*.vert" /> - <Datas Include="..\data\**\*.*"> - <Link>data\%(RecursiveDir)%(Filename)%(Extension)</Link> - </Datas> - <None Remove="mono_crash.1adb363697.0.json" /> - </ItemGroup> - - <Import Project="$(SolutionDir)spirv.targets" /> </Project> diff --git a/samples/Textured/main.cs b/samples/Textured/main.cs index c765ea6..3308290 100644 --- a/samples/Textured/main.cs +++ b/samples/Textured/main.cs @@ -4,21 +4,20 @@ using System.Runtime.InteropServices; using Glfw; using CVKL; using VK; -using Buffer = CVKL.Buffer; -using System.IO; namespace TextureSample { class Program : VkWindow { static void Main (string[] args) { Instance.VALIDATION = true; Instance.DEBUG_UTILS = true; + Instance.RENDER_DOC_CAPTURE = true; using (Program vke = new Program ()) { vke.Run (); } } protected override void configureEnabledFeatures (VkPhysicalDeviceFeatures available_features, ref VkPhysicalDeviceFeatures features) { base.configureEnabledFeatures (available_features, ref features); - //features.textureCompressionBC = available_features.textureCompressionBC; + features.textureCompressionBC = available_features.textureCompressionBC; features.textureCompressionASTC_LDR = available_features.textureCompressionASTC_LDR; } @@ -56,23 +55,31 @@ namespace TextureSample { ushort[] indices = { 0, 1, 2, 2, 0, 3 }; int currentImgIndex = 0; string[] imgPathes = { - "/mnt/devel/vulkan/vulkanExUpstream/data/textures/trail_astc_8x8_unorm.ktx", - //"data/textures/tex.astc", - "data/textures/tex256.jpg", - "data/textures/texture.jpg", + "/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", + "/mnt/devel/vulkan/vulkanExUpstream/data/textures/trail_astc_8x8_unorm.ktx", "data/textures/texturearray_rocks_bc3_unorm.ktx", + "data/textures/texture.jpg", + "data/textures/tex256.jpg", }; DebugReport dbgReport; + CVKL.DebugUtils.Messenger msg; Program () : base () { - dbgReport = new DebugReport (instance, - VkDebugReportFlagsEXT.DebugEXT| - VkDebugReportFlagsEXT.ErrorEXT | - VkDebugReportFlagsEXT.WarningEXT | - VkDebugReportFlagsEXT.PerformanceWarningEXT | - VkDebugReportFlagsEXT.InformationEXT); + + msg = new CVKL.DebugUtils.Messenger (instance); + + if (Instance.DEBUG_UTILS) + dbgReport = new DebugReport (instance, + VkDebugReportFlagsEXT.DebugEXT| + VkDebugReportFlagsEXT.ErrorEXT | + VkDebugReportFlagsEXT.WarningEXT | + VkDebugReportFlagsEXT.PerformanceWarningEXT | + VkDebugReportFlagsEXT.InformationEXT); + + loadTexture (imgPathes[currentImgIndex]); vbo = new GPUBuffer<float> (presentQueue, cmdPool, VkBufferUsageFlags.VertexBuffer, vertices); ibo = new GPUBuffer<ushort> (presentQueue, cmdPool, VkBufferUsageFlags.IndexBuffer, indices); @@ -86,7 +93,7 @@ namespace TextureSample { new VkDescriptorSetLayoutBinding (0, VkShaderStageFlags.Vertex, VkDescriptorType.UniformBuffer), new VkDescriptorSetLayoutBinding (1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler)); - GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault (VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount1); + GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault (VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount4); cfg.Layout = new PipelineLayout (dev, dsLayout); cfg.RenderPass = new RenderPass (dev, swapChain.ColorFormat, dev.GetSuitableDepthFormat (), cfg.Samples); @@ -99,16 +106,16 @@ namespace TextureSample { pipeline = new GraphicPipeline (cfg); + uboMats = new HostBuffer (dev, VkBufferUsageFlags.UniformBuffer, matrices); uboMats.Map ();//permanent map descriptorSet = descriptorPool.Allocate (dsLayout); + updateTextureSet (); + DescriptorSetWrites uboUpdate = new DescriptorSetWrites (descriptorSet, dsLayout.Bindings[0]); uboUpdate.Write (dev, uboMats.Descriptor); - - loadTexture (imgPathes[currentImgIndex]); - updateTextureSet (); } void buildCommandBuffers () { @@ -121,11 +128,8 @@ namespace TextureSample { cmds[i].End (); } - } + } void recordDraw (CommandBuffer cmd, Framebuffer fb) { - texture.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.Undefined, VkImageLayout.ShaderReadOnlyOptimal, - VkPipelineStageFlags.BottomOfPipe, VkPipelineStageFlags.FragmentShader); - pipeline.RenderPass.Begin (cmd, fb); cmd.SetViewport (fb.Width, fb.Height); @@ -140,28 +144,31 @@ namespace TextureSample { pipeline.RenderPass.End (cmd); } - + + VkMemoryPropertyFlags imgProp = VkMemoryPropertyFlags.DeviceLocal; + bool genMipMaps = true; + VkImageTiling tiling = VkImageTiling.Optimal; + //in the thread of the keyboard void loadTexture (string path) { - if (path.EndsWith ("ktx", StringComparison.OrdinalIgnoreCase)) - nextTexture = KTX.KTX.Load (presentQueue, cmdPool, path, - VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true, VkImageTiling.Optimal); - /*else if (path.EndsWith ("astc", StringComparison.OrdinalIgnoreCase)) { - using (Stream str = File.OpenRead (path)) { - str.Length - nextTexture = Image.Load (dev, presentQueue, cmdPool, str, VkFormat.Astc6x6UnormBlock, VkMemoryPropertyFlags.DeviceLocal, VkImageTiling.Optimal, false); - } - } */ - else - nextTexture = Image.Load (dev, presentQueue, cmdPool, path, VkFormat.R8g8b8a8Unorm, VkMemoryPropertyFlags.DeviceLocal, VkImageTiling.Optimal, false); - updateViewRequested = true; + try { + Console.WriteLine ($"Loading:{path}"); + if (path.EndsWith ("ktx", StringComparison.OrdinalIgnoreCase)) + nextTexture = KTX.KTX.Load (presentQueue, cmdPool, path, + VkImageUsageFlags.Sampled, imgProp, genMipMaps, tiling); + else + nextTexture = Image.Load (dev, presentQueue, cmdPool, path, VkFormat.R8g8b8a8Unorm, imgProp, tiling, genMipMaps); + updateViewRequested = true; + } catch (Exception ex) { + Console.WriteLine (ex); + nextTexture = null; + } } //in the main vulkan thread void updateTextureSet (){ nextTexture.CreateView (); nextTexture.CreateSampler (); - nextTexture.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; DescriptorSetWrites uboUpdate = new DescriptorSetWrites (descriptorSet, dsLayout.Bindings[1]); @@ -184,10 +191,9 @@ namespace TextureSample { public override void UpdateView () { if (nextTexture != null) { - dev.WaitIdle (); updateTextureSet (); buildCommandBuffers (); - } else + }else updateMatrices (); updateViewRequested = false; @@ -259,7 +265,8 @@ namespace TextureSample { vbo.Dispose (); ibo.Dispose (); uboMats.Dispose (); - dbgReport.Dispose (); + dbgReport?.Dispose (); + msg?.Dispose (); } } diff --git a/samples/TexturedCube/TexturedCube.csproj b/samples/TexturedCube/TexturedCube.csproj index 170d601..8e5fa63 100644 --- a/samples/TexturedCube/TexturedCube.csproj +++ b/samples/TexturedCube/TexturedCube.csproj @@ -1,38 +1,4 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> - <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - </PropertyGroup> - - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Vulkan" Version="0.1.3" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\vke\CVKL.csproj"> - </ProjectReference> - </ItemGroup> - - <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert" /> - <None Remove="shaders\**\*.frag;shaders\**\*.vert" /> - <Datas Include="..\data\**\*.*"> - <Link>data\%(RecursiveDir)%(Filename)%(Extension)</Link> - </Datas> - </ItemGroup> - - <Import Project="$(SolutionDir)spirv.targets" /> </Project> diff --git a/samples/TexturedCube/main.cs b/samples/TexturedCube/main.cs index 96ef778..4ef2927 100644 --- a/samples/TexturedCube/main.cs +++ b/samples/TexturedCube/main.cs @@ -9,6 +9,11 @@ using Buffer = CVKL.Buffer; namespace TextureCube { class Program : VkWindow { static void Main (string[] args) { + + Instance.VALIDATION = true; + Instance.DEBUG_UTILS = true; + Instance.RENDER_DOC_CAPTURE = true; + using (Program vke = new Program ()) { vke.Run (); } @@ -80,11 +85,11 @@ namespace TextureCube { }; int currentImgIndex = 0; string[] imgPathes = { + "data/textures/uffizi_cube.ktx", "data/textures/papermill.ktx", "data/textures/cubemap_yokohama_bc3_unorm.ktx", "data/textures/gcanyon_cube.ktx", "data/textures/pisa_cube.ktx", - "data/textures/uffizi_cube.ktx", }; @@ -157,7 +162,7 @@ namespace TextureCube { nextTexture = KTX.KTX.Load (presentQueue, cmdPool, path, VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true); else - nextTexture = Image.StbLoad (dev, path); + nextTexture = Image.Load (dev, path); updateViewRequested = true; } @@ -190,14 +195,17 @@ namespace TextureCube { } public override void UpdateView () { + //loadTexture (imgPathes[currentImgIndex]); + if (nextTexture != null) { dev.WaitIdle (); updateTextureSet (); buildCommandBuffers (); - } else + }else updateMatrices (); updateViewRequested = false; + //System.Threading.Thread.Sleep (1000); } protected override void onMouseMove (double xPos, double yPos) { @@ -212,6 +220,7 @@ namespace TextureCube { updateViewRequested = true; } + protected override void onKeyDown (Key key, int scanCode, Modifier modifiers) { switch (key) { case Key.Space: diff --git a/samples/Triangle/Triangle.csproj b/samples/Triangle/Triangle.csproj index d3956b0..63844b6 100644 --- a/samples/Triangle/Triangle.csproj +++ b/samples/Triangle/Triangle.csproj @@ -1,34 +1,3 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> - <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - </PropertyGroup> - - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="glTF2Loader" Version="1.1.3-alpha" /> - <PackageReference Include="Vulkan" Version="0.1.3" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\vke\CVKL.csproj" /> - </ItemGroup> - - <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert" /> - <None Remove="shaders\**\*.frag;shaders\**\*.vert" /> - </ItemGroup> - - <Import Project="$(SolutionDir)spirv.targets" /> </Project>
\ No newline at end of file diff --git a/samples/compute/compute.csproj b/samples/compute/compute.csproj index 1a8629c..e1734ff 100644 --- a/samples/compute/compute.csproj +++ b/samples/compute/compute.csproj @@ -1,43 +1,10 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - <DefineConstants>TRACE;RELEASE;NETFRAMEWORK;NET471</DefineConstants> - <DefineConstants>TRACE;RELEASE;NETFRAMEWORK;NET471</DefineConstants> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Vulkan" Version="0.1.3" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\vke\CVKL.csproj"> - </ProjectReference> - </ItemGroup> - + <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert;shaders\**\*.comp" /> - <None Remove="shaders\**\*.frag;shaders\**\*.vert" /> <Compile Include="delaunay.cs" /> - <Datas Include="..\data\**\*.*"> - <Link>data\%(RecursiveDir)%(Filename)%(Extension)</Link> - </Datas> </ItemGroup> - - <Import Project="$(SolutionDir)spirv.targets" /> </Project>
\ No newline at end of file diff --git a/samples/deferred/EnvironmentPipeline.cs b/samples/deferred/EnvironmentPipeline.cs index c8f128a..1619a94 100644 --- a/samples/deferred/EnvironmentPipeline.cs +++ b/samples/deferred/EnvironmentPipeline.cs @@ -23,7 +23,7 @@ namespace CVKL { cubemap = KTX.KTX.Load (staggingQ, cmdPool, cubemapPath, VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true); - cubemap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6, 0, cubemap.CreateInfo.mipLevels); + cubemap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color); cubemap.CreateSampler (VkSamplerAddressMode.ClampToEdge); cubemap.SetName ("skybox Texture"); cubemap.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; @@ -171,7 +171,7 @@ namespace CVKL { cmap.SetName ("prefilterenvmap"); else cmap.SetName ("irradianceCube"); - cmap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6, 0, numMips); + cmap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6, 0); cmap.CreateSampler (VkSamplerAddressMode.ClampToEdge); DescriptorPool dsPool = new DescriptorPool (Dev, 2, new VkDescriptorPoolSize (VkDescriptorType.CombinedImageSampler)); diff --git a/samples/deferred/deferred.csproj b/samples/deferred/deferred.csproj index d98f4cc..ac9eed1 100644 --- a/samples/deferred/deferred.csproj +++ b/samples/deferred/deferred.csproj @@ -1,30 +1,15 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <EnableDefaultNoneItems>false</EnableDefaultNoneItems> </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>WITH_SHADOWS;_WITH_VKVG;TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DefineConstants>WITH_SHADOWS;_WITH_VKVG</DefineConstants> - </PropertyGroup> - - <PropertyGroup Condition="$(Configuration) == 'DebugCrow' "> - <DefineConstants>WITH_SHADOWS;_WITH_VKVG;TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DefineConstants>TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0;MEMORY_POOLS;WITH_SHADOWS;_WITH_VKVG</DefineConstants> + </PropertyGroup> <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert;shaders\**\*.comp;shaders\**\*.geom" /> - <Datas Include="..\data\**\*.*"> - <Link>data\%(RecursiveDir)%(Filename)%(Extension)</Link> - </Datas> <Compile Include="EnvironmentPipeline.cs;deferredPbrRenderer.cs;shadowMapRenderer.cs" /> </ItemGroup> @@ -40,15 +25,9 @@ <Compile Include="main.cs" /> </ItemGroup> - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> <ItemGroup> - <PackageReference Include="Vulkan" Version="0.1.3" /> - <ProjectReference Include="..\..\vke\CVKL.csproj" /> <PackageReference Include="Crow.VK" Version="0.9.0-beta" /> </ItemGroup> - <Import Project="$(SolutionDir)spirv.targets" /> </Project>
\ No newline at end of file diff --git a/samples/deferred/deferredPbrRenderer.cs b/samples/deferred/deferredPbrRenderer.cs index d4c1ccb..edb50a9 100644 --- a/samples/deferred/deferredPbrRenderer.cs +++ b/samples/deferred/deferredPbrRenderer.cs @@ -12,8 +12,8 @@ namespace deferred { public static int MAX_MATERIAL_COUNT = 8; public static VkSampleCountFlags NUM_SAMPLES = VkSampleCountFlags.SampleCount1; - public static VkFormat HDR_FORMAT = VkFormat.R32g32b32a32Sfloat; - public static VkFormat MRT_FORMAT = VkFormat.R32g32b32a32Sfloat; + public static VkFormat HDR_FORMAT = VkFormat.R16g16b16a16Sfloat;// VkFormat.R32g32b32a32Sfloat; + public static VkFormat MRT_FORMAT = VkFormat.R16g16b16a16Sfloat; public static bool TEXTURE_ARRAY; public enum DebugView { @@ -473,7 +473,7 @@ namespace deferred { gBuffPipeline.Dispose (); composePipeline.Dispose (); toneMappingPipeline.Dispose (); - debugPipeline.Dispose (); + debugPipeline?.Dispose (); descLayoutMain.Dispose (); descLayoutTextures?.Dispose (); diff --git a/samples/deferred/main.cs b/samples/deferred/main.cs index 13bf08c..ccd5efc 100644 --- a/samples/deferred/main.cs +++ b/samples/deferred/main.cs @@ -8,14 +8,14 @@ namespace deferred { class Deferred : VkWindow { static void Main (string[] args) { - //Instance.VALIDATION = true; - //Instance.DEBUG_UTILS = true; + Instance.VALIDATION = true; + Instance.DEBUG_UTILS = true; //Instance.RENDER_DOC_CAPTURE = true; DeferredPbrRenderer.TEXTURE_ARRAY = true; DeferredPbrRenderer.NUM_SAMPLES = VkSampleCountFlags.SampleCount1; - PbrModelTexArray.TEXTURE_DIM = 512; + PbrModelTexArray.TEXTURE_DIM = 1024; using (Deferred vke = new Deferred ()) { vke.Run (); @@ -58,22 +58,17 @@ namespace deferred { Queue transferQ; DeferredPbrRenderer renderer; - DebugReport dbgRepport; + CVKL.DebugUtils.Messenger dbgmsg; Deferred () : base() { if (Instance.DEBUG_UTILS) - dbgRepport = new DebugReport (instance, - VkDebugReportFlagsEXT.ErrorEXT - | VkDebugReportFlagsEXT.DebugEXT - | VkDebugReportFlagsEXT.WarningEXT - | VkDebugReportFlagsEXT.PerformanceWarningEXT - ); + dbgmsg = new CVKL.DebugUtils.Messenger (instance); camera = new Camera (Utils.DegreesToRadians (45f), 1f, 0.1f, 16f); camera.SetPosition (0, 0, 2); - renderer = new DeferredPbrRenderer (dev, swapChain, presentQueue, cubemapPathes[2], camera.NearPlane, camera.FarPlane); + renderer = new DeferredPbrRenderer (dev, swapChain, presentQueue, cubemapPathes[0], camera.NearPlane, camera.FarPlane); renderer.LoadModel (transferQ, modelPathes[curModelIndex]); camera.Model = Matrix4x4.CreateScale (1f / Math.Max (Math.Max (renderer.modelAABB.Width, renderer.modelAABB.Height), renderer.modelAABB.Depth)); @@ -279,7 +274,7 @@ namespace deferred { if (disposing) { if (!isDisposed) { renderer.Dispose (); - dbgRepport?.Dispose (); + dbgmsg?.Dispose (); } } base.Dispose (disposing); diff --git a/samples/pbr/EnvironmentPipeline.cs b/samples/pbr/EnvironmentPipeline.cs index a03374b..59aaac7 100644 --- a/samples/pbr/EnvironmentPipeline.cs +++ b/samples/pbr/EnvironmentPipeline.cs @@ -27,7 +27,7 @@ namespace CVKL { cubemap = KTX.KTX.Load (staggingQ, cmdPool, cubemapPathes[2], VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true); - cubemap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6, 0, cubemap.CreateInfo.mipLevels); + cubemap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6); cubemap.CreateSampler (VkSamplerAddressMode.ClampToEdge); cubemap.SetName ("skybox Texture"); cubemap.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; @@ -186,7 +186,7 @@ namespace CVKL { cmap.SetName ("prefilterenvmap"); else cmap.SetName ("irradianceCube"); - cmap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6, 0, numMips); + cmap.CreateView (VkImageViewType.Cube, VkImageAspectFlags.Color, 6); cmap.CreateSampler (VkSamplerAddressMode.ClampToEdge); DescriptorPool dsPool = new DescriptorPool (Dev, 2, new VkDescriptorPoolSize (VkDescriptorType.CombinedImageSampler)); diff --git a/samples/pbr/PbrModel.cs b/samples/pbr/PbrModel.cs index 575f283..80476e9 100644 --- a/samples/pbr/PbrModel.cs +++ b/samples/pbr/PbrModel.cs @@ -131,7 +131,7 @@ namespace CVKL { } void loadMaterials (glTFLoader ctx, DescriptorSetLayout layout, params AttachmentType[] attachments) { - Model.Material[] mats = ctx.LoadMaterial (); + glTFLoader.Material[] mats = ctx.LoadMaterial (); materials = new PbrMaterial[mats.Length]; descriptorSets = new DescriptorSet[mats.Length]; diff --git a/samples/pbr/pbr.csproj b/samples/pbr/pbr.csproj index 96274aa..71696f8 100644 --- a/samples/pbr/pbr.csproj +++ b/samples/pbr/pbr.csproj @@ -1,43 +1,19 @@ <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RootDirectory)netfx.props" /> <PropertyGroup> - <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> - <OutputType>Exe</OutputType> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - <EnableDefaultCompileItems>true</EnableDefaultCompileItems> <EnableDefaultNoneItems>false</EnableDefaultNoneItems> + <DefineConstants>_WITH_VKVG</DefineConstants> </PropertyGroup> - - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DefineConstants>_WITH_VKVG;TRACE;DEBUG;NETSTANDARD;NETSTANDARD2_0</DefineConstants> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DefineConstants>_WITH_VKVG</DefineConstants> - </PropertyGroup> - - <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> - <Reference Include="System" /> - </ItemGroup> - + <ItemGroup> - <PackageReference Include="Vulkan" Version="0.1.3" /> <PackageReference Include="vkvg.net" Version="0.2.2-beta" /> </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\vke\CVKL.csproj" /> - </ItemGroup> <ItemGroup> - <GLSLShader Include="shaders\**\*.frag;shaders\**\*.vert;shaders\**\*.comp;shaders\**\*.geom" /> - <Datas Include="..\data\**\*.*"> - <Link>data\%(RecursiveDir)%(Filename)%(Extension)</Link> - </Datas> - <EmbeddedResource Include="ui\**\*.*"> <LogicalName>deferred.%(Filename)%(Extension)</LogicalName> </EmbeddedResource> </ItemGroup> - <Import Project="$(SolutionDir)spirv.targets" /> </Project> diff --git a/samples/tests/Program.cs b/samples/tests/Program.cs new file mode 100644 index 0000000..0f34ddf --- /dev/null +++ b/samples/tests/Program.cs @@ -0,0 +1,66 @@ +using System; +using CVKL; +using VK; +using static VK.Vk; + +namespace tests { + class Program : VkWindow { + static void Main (string[] args) { + Instance.VALIDATION = true; + Instance.DEBUG_UTILS = true; + using (Program vke = new Program ()) { + vke.Run (); + } + } + + DebugReport dbgReport; + CVKL.DebugUtils.Messenger msg; + + Image img; + + Program () : base () { + msg = new CVKL.DebugUtils.Messenger (instance); + + dbgReport = new DebugReport (instance, + VkDebugReportFlagsEXT.DebugEXT | + VkDebugReportFlagsEXT.ErrorEXT | + VkDebugReportFlagsEXT.WarningEXT | + VkDebugReportFlagsEXT.PerformanceWarningEXT | + VkDebugReportFlagsEXT.InformationEXT); + + + CommandBuffer cmd = cmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); + + using (StbImage stbi = new StbImage ("data/textures/texture.jpg")) { + + img = new Image (dev, VkFormat.R8g8b8a8Unorm, VkImageUsageFlags.TransferSrc | VkImageUsageFlags.TransferDst, + VkMemoryPropertyFlags.DeviceLocal, (uint)stbi.Width, (uint)stbi.Height, VkImageType.Image2D, + VkSampleCountFlags.SampleCount1, VkImageTiling.Optimal, Image.ComputeMipLevels (stbi.Width, stbi.Height)); + + using (HostBuffer stag = new HostBuffer (dev, VkBufferUsageFlags.TransferSrc, (ulong)stbi.Size, stbi.Handle)) { + + stag.CopyTo (cmd, img, VkImageLayout.TransferSrcOptimal); + img.BuildMipmaps (cmd); + + cmd.End (); + presentQueue.Submit (cmd); + presentQueue.WaitIdle (); + cmd.Free (); + + } + } + + + } + + + protected override void Dispose (bool disposing) { + if (disposing) { + if (!isDisposed) { + dbgReport?.Dispose (); + } + } + base.Dispose (); + } + } +} diff --git a/samples/tests/shaders/main.vert b/samples/tests/shaders/main.vert new file mode 100644 index 0000000..3b395bf --- /dev/null +++ b/samples/tests/shaders/main.vert @@ -0,0 +1,28 @@ +#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 (binding = 0) uniform UBO +{ + mat4 projectionMatrix; + mat4 viewMatrix; + mat4 modelMatrix; +} ubo; + +layout (location = 0) out vec3 outColor; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + + +void main() +{ + outColor = inColor; + gl_Position = ubo.projectionMatrix * ubo.viewMatrix * ubo.modelMatrix * vec4(inPos.xyz, 1.0); +} diff --git a/samples/tests/tests.csproj b/samples/tests/tests.csproj new file mode 100644 index 0000000..f4c1c6b --- /dev/null +++ b/samples/tests/tests.csproj @@ -0,0 +1,6 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <Import Project="$(RootDirectory)netfx.props" /> + <ItemGroup> + <Folder Include="shaders\" /> + </ItemGroup> +</Project> @@ -27,6 +27,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "pbr", "samples\pbr\pbr.cspr EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "samples\Model\Model.csproj", "{0E4346C3-87C0-4C0A-8CDB-DBF1E29F5385}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tests", "samples\tests\tests.csproj", "{1972F90F-9995-4B5D-9696-1B0692F8F650}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -113,6 +115,14 @@ Global {0E4346C3-87C0-4C0A-8CDB-DBF1E29F5385}.temp|Any CPU.Build.0 = Debug|Any CPU {0E4346C3-87C0-4C0A-8CDB-DBF1E29F5385}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU {0E4346C3-87C0-4C0A-8CDB-DBF1E29F5385}.DebugCrow|Any CPU.Build.0 = Debug|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.Release|Any CPU.Build.0 = Release|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.temp|Any CPU.ActiveCfg = Debug|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.temp|Any CPU.Build.0 = Debug|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.DebugCrow|Any CPU.ActiveCfg = Debug|Any CPU + {1972F90F-9995-4B5D-9696-1B0692F8F650}.DebugCrow|Any CPU.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {96A2E0B8-91AE-4EB9-A435-185D01E24067} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} @@ -123,6 +133,7 @@ Global {05515E15-D3C3-4A8C-A940-9467D9D77823} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} {790642C5-7AD1-437D-9F9C-3F721133AFEF} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} {0E4346C3-87C0-4C0A-8CDB-DBF1E29F5385} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} + {1972F90F-9995-4B5D-9696-1B0692F8F650} = {A2A2849A-0032-4AA8-BC0E-82C69D7DE354} EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution Policies = $0 diff --git a/vke/CVKL.csproj b/vke/CVKL.csproj index ff861c2..a5bf978 100644 --- a/vke/CVKL.csproj +++ b/vke/CVKL.csproj @@ -19,6 +19,7 @@ <AssemblyName>CVKL</AssemblyName> <OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> @@ -26,11 +27,12 @@ <DebugType>full</DebugType> <Optimize>false</Optimize> <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> - <DefineConstants>_RENDERDOC;NETSTANDARD;NETSTANDARD2_0;DEBUG;NETFRAMEWORK;NET471</DefineConstants> + <DefineConstants>MEMORY_POOLS;NETSTANDARD;NETSTANDARD2_0;DEBUG;NETFRAMEWORK;NET471</DefineConstants> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <Optimize>true</Optimize> + <DefineConstants>MEMORY_POOLS</DefineConstants> </PropertyGroup> <ItemGroup Condition="$(TargetFramework.StartsWith('net4'))"> diff --git a/vke/src/MemoryPool.cs b/vke/src/MemoryPool.cs index b9532ab..e2c27cd 100644 --- a/vke/src/MemoryPool.cs +++ b/vke/src/MemoryPool.cs @@ -6,6 +6,7 @@ using VK; using static VK.Vk; namespace CVKL { +#if MEMORY_POOLS public enum MemoryPoolType { Random, Linear @@ -79,7 +80,7 @@ namespace CVKL { mappedPointer = IntPtr.Zero; } - #region IDisposable Support +#region IDisposable Support private bool disposedValue; protected virtual void Dispose (bool disposing) { @@ -98,6 +99,7 @@ namespace CVKL { Dispose (true); GC.SuppressFinalize(this); } - #endregion +#endregion } +#endif }
\ No newline at end of file diff --git a/vke/src/ResourceManager.cs b/vke/src/ResourceManager.cs index 10fef13..490f591 100644 --- a/vke/src/ResourceManager.cs +++ b/vke/src/ResourceManager.cs @@ -7,7 +7,8 @@ using VK; using static VK.Vk; namespace CVKL { - public class ResourceManager : IDisposable { +#if MEMORY_POOLS + public class ResourceManager : IDisposable { VkPhysicalDeviceMemoryProperties memoryProperties; public MemoryPool[] memoryPools; ulong[] reservedHeapMemory; @@ -15,7 +16,7 @@ namespace CVKL { VkMemoryHeap getHeapFromMemoryIndex (uint i) => memoryProperties.memoryHeaps[memoryProperties.memoryTypes[i].heapIndex]; - public ResourceManager (Device dev, ulong defaultPoolsBlockDivisor = 4) { + public ResourceManager (Device dev, ulong defaultPoolsBlockDivisor = 16) { memoryProperties = dev.phy.memoryProperties; memoryPools = new MemoryPool[memoryProperties.memoryTypeCount]; reservedHeapMemory = new ulong[memoryProperties.memoryHeapCount]; @@ -51,4 +52,5 @@ namespace CVKL { memoryPools[i].Dispose (); } } +#endif }
\ No newline at end of file diff --git a/vke/src/StbImage.cs b/vke/src/StbImage.cs new file mode 100644 index 0000000..3ea1d7f --- /dev/null +++ b/vke/src/StbImage.cs @@ -0,0 +1,65 @@ +// 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.Runtime.InteropServices; + +namespace CVKL { + public class StbImage : IDisposable { + const string stblib = "stb"; + + [DllImport (stblib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "stbi_load")] + static extern IntPtr Load ([MarshalAs (UnmanagedType.LPStr)] string filename, out int x, out int y, out int channels_in_file, int desired_channels); + + [DllImport (stblib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "stbi_load_from_memory")] + static extern IntPtr Load (IntPtr bitmap, int byteCount, out int x, out int y, out int channels_in_file, int desired_channels); + + [DllImport (stblib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "stbi_image_free")] + static extern void FreeImage (IntPtr img); + + public readonly IntPtr Handle; + public readonly int Width; + public readonly int Height; + public readonly int Channels; + public int Size => Width * Height * Channels; + + /// <summary> + /// Open image with STBI library + /// </summary> + /// <param name="path">file path</param> + /// <param name="requestedChannels">Force returned channels count, set 0 for original count</param> + public StbImage (string path, int requestedChannels = 4) { + Handle = StbImage.Load (path, out Width, out Height, out Channels, requestedChannels); + if (Handle == IntPtr.Zero) + throw new Exception ($"STBI image loading error."); + if (requestedChannels > 0) + Channels = requestedChannels; + } + /// <summary> + /// Open image with STBI library + /// </summary> + /// <param name="bitmap">raw bitmap datas</param> + /// <param name="bitmapByteCount">Bitmap byte count.</param> + /// <param name="requestedChannels">Force returned channels count, set 0 for original count</param> + public StbImage (IntPtr bitmap, ulong bitmapByteCount, int requestedChannels = 4) { + Handle = StbImage.Load (bitmap, (int)bitmapByteCount, out Width, out Height, out Channels, requestedChannels); + if (Handle == IntPtr.Zero) + throw new Exception ($"STBI image loading error."); + if (requestedChannels > 0) + Channels = requestedChannels; + } + /// <summary> + /// copy pixels to destination. + /// </summary> + /// <param name="destPtr">Destination pointer.</param> + public void CoptyTo (IntPtr destPtr) { + unsafe { + System.Buffer.MemoryCopy (Handle.ToPointer (), destPtr.ToPointer (), Size, Size); + } + } + public void Dispose () { + StbImage.FreeImage (Handle); + } + } +} diff --git a/vke/src/VkWindow.cs b/vke/src/VkWindow.cs index 84e3b77..d0f3f61 100644 --- a/vke/src/VkWindow.cs +++ b/vke/src/VkWindow.cs @@ -173,6 +173,9 @@ namespace CVKL { return; } + if (cmds[idx] == null) + return; + presentQueue.Submit (cmds[idx], swapChain.presentComplete, drawComplete[idx]); presentQueue.Present (swapChain, drawComplete[idx]); diff --git a/vke/src/base/Buffer.cs b/vke/src/base/Buffer.cs index c43eda0..254d547 100644 --- a/vke/src/base/Buffer.cs +++ b/vke/src/base/Buffer.cs @@ -36,7 +36,13 @@ namespace CVKL { public override void Activate () { if (state != ActivableState.Activated) { Utils.CheckResult (vkCreateBuffer (Dev.VkDev, ref createInfo, IntPtr.Zero, out handle)); +#if MEMORY_POOLS Dev.resourceManager.Add (this); +#else + updateMemoryRequirements (); + allocateMemory (); + bindMemory (); +#endif SetupDescriptor (); } base.Activate (); @@ -47,7 +53,11 @@ namespace CVKL { } internal override void bindMemory () { +#if MEMORY_POOLS Utils.CheckResult (vkBindBufferMemory (Dev.VkDev, handle, memoryPool.vkMemory, poolOffset)); +#else + Utils.CheckResult (vkBindBufferMemory (Dev.VkDev, handle, vkMemory, 0)); +#endif } public void SetupDescriptor (ulong size = WholeSize, ulong offset = 0) { @@ -88,7 +98,7 @@ namespace CVKL { return string.Format ($"{base.ToString ()}[0x{handle.Handle.ToString("x")}]"); } - #region IDisposable Support +#region IDisposable Support protected override void Dispose (bool disposing) { if (state == ActivableState.Activated) { base.Dispose (disposing); @@ -96,6 +106,6 @@ namespace CVKL { } state = ActivableState.Disposed; } - #endregion +#endregion } } diff --git a/vke/src/base/DebugUtilsMessenger.cs b/vke/src/base/DebugUtilsMessenger.cs new file mode 100644 index 0000000..841b60e --- /dev/null +++ b/vke/src/base/DebugUtilsMessenger.cs @@ -0,0 +1,91 @@ +using System; +using System.Runtime.InteropServices; +using VK; +using static VK.Vk; + +namespace CVKL.DebugUtils { + + public class Messenger : IDisposable { + Instance inst; + VkDebugUtilsMessengerEXT handle; + PFN_vkDebugUtilsMessengerCallbackEXT onMessage = new PFN_vkDebugUtilsMessengerCallbackEXT(HandlePFN_vkDebugUtilsMessengerCallbackEXT); + + static VkBool32 HandlePFN_vkDebugUtilsMessengerCallbackEXT (VkDebugUtilsMessageSeverityFlagsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, IntPtr pCallbackData, IntPtr pUserData) { + //Console.WriteLine ("{0} {1}: {2}",messageSeverity, messageTypes, Marshal.PtrToStringAnsi(pUserData)); + Console.WriteLine ("MESSAGE RECEIVED"); + return false; + } + + + + // PFN_vkDebugReportCallbackEXT debugCallbackDelegate = new PFN_vkDebugReportCallbackEXT (debugCallback); + + // static VkBool32 debugCallback (VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, ulong obj, + // UIntPtr location, int messageCode, IntPtr pLayerPrefix, IntPtr pMessage, IntPtr pUserData) { + // string prefix = ""; + // switch (flags) { + // case 0: + // prefix = "?"; + // break; + // case VkDebugReportFlagsEXT.InformationEXT: + // Console.ForegroundColor = ConsoleColor.Gray; + // prefix = "INFO"; + // break; + // case VkDebugReportFlagsEXT.WarningEXT: + // Console.ForegroundColor = ConsoleColor.DarkYellow; + // prefix = "WARN"; + // break; + // case VkDebugReportFlagsEXT.PerformanceWarningEXT: + // Console.ForegroundColor = ConsoleColor.Yellow; + // prefix = "PERF"; + // break; + // case VkDebugReportFlagsEXT.ErrorEXT: + // Console.ForegroundColor = ConsoleColor.DarkRed; + // prefix = "EROR"; + // break; + // case VkDebugReportFlagsEXT.DebugEXT: + // Console.ForegroundColor = ConsoleColor.Red; + // prefix = "DBUG"; + // break; + // } + + // Console.WriteLine ("{0} {1}: {2}",prefix, messageCode, Marshal.PtrToStringAnsi(pMessage)); + //Console.ForegroundColor = ConsoleColor.White; + // return VkBool32.False; + //} + + public Messenger (Instance instance, VkDebugReportFlagsEXT flags = VkDebugReportFlagsEXT.ErrorEXT | VkDebugReportFlagsEXT.WarningEXT) { + inst = instance; + VkDebugUtilsMessengerCreateInfoEXT info = VkDebugUtilsMessengerCreateInfoEXT.New (); + info.messageType = VkDebugUtilsMessageTypeFlagsEXT.ValidationEXT | VkDebugUtilsMessageTypeFlagsEXT.GeneralEXT | VkDebugUtilsMessageTypeFlagsEXT.PerformanceEXT; + info.messageSeverity = VkDebugUtilsMessageSeverityFlagsEXT.ErrorEXT | VkDebugUtilsMessageSeverityFlagsEXT.WarningEXT | VkDebugUtilsMessageSeverityFlagsEXT.InfoEXT | VkDebugUtilsMessageSeverityFlagsEXT.VerboseEXT; + info.pfnUserCallback = Marshal.GetFunctionPointerForDelegate (onMessage); + + Utils.CheckResult (vkCreateDebugUtilsMessengerEXT (inst.VkInstance, ref info, IntPtr.Zero, out handle)); + } + + #region IDisposable Support + private bool disposedValue; + + protected virtual void Dispose (bool disposing) { + if (!disposedValue) { + if (disposing) { + // TODO: supprimer l'état managé (objets managés). + } + + vkDestroyDebugUtilsMessengerEXT (inst.Handle, handle, IntPtr.Zero); + + disposedValue = true; + } + } + + ~Messenger () { + Dispose (false); + } + public void Dispose () { + Dispose (true); + GC.SuppressFinalize (this); + } + #endregion + } +} diff --git a/vke/src/base/Device.cs b/vke/src/base/Device.cs index 811f446..e45d45c 100644 --- a/vke/src/base/Device.cs +++ b/vke/src/base/Device.cs @@ -49,7 +49,9 @@ namespace CVKL { internal List<Queue> queues = new List<Queue> (); internal bool debugMarkersEnabled; +#if MEMORY_POOLS public ResourceManager resourceManager; +#endif public Device (PhysicalDevice _phy) { phy = _phy; @@ -118,7 +120,9 @@ namespace CVKL { foreach (Queue q in queues) q.updateHandle (); +#if MEMORY_POOLS resourceManager = new ResourceManager (this); +#endif } public VkSemaphore CreateSemaphore () { @@ -286,13 +290,15 @@ namespace CVKL { return stream; } - #region IDisposable Support +#region IDisposable Support private bool disposedValue = false; // Pour détecter les appels redondants protected virtual void Dispose (bool disposing) { if (!disposedValue) { if (disposing) { +#if MEMORY_POOLS resourceManager.Dispose (); +#endif } else System.Diagnostics.Debug.WriteLine ("Device disposed by Finalizer."); @@ -311,6 +317,6 @@ namespace CVKL { Dispose (true); GC.SuppressFinalize(this); } - #endregion +#endregion } } diff --git a/vke/src/base/HostBuffer.cs b/vke/src/base/HostBuffer.cs index a12cfd0..20734c8 100644 --- a/vke/src/base/HostBuffer.cs +++ b/vke/src/base/HostBuffer.cs @@ -68,8 +68,13 @@ namespace CVKL { VkMappedMemoryRange mr = new VkMappedMemoryRange { sType = VkStructureType.MappedMemoryRange, - memory = memoryPool.vkMemory, +#if MEMORY_POOLS + memory = memoryPool.vkMemory, offset = poolOffset + (ulong)(startIndex * TSize), +#else + memory = vkMemory, + offset = (ulong)(startIndex * TSize), +#endif size = (ulong)((endIndex - startIndex) * TSize) }; vkFlushMappedMemoryRanges(Dev.VkDev, 1, ref mr); diff --git a/vke/src/base/Image.cs b/vke/src/base/Image.cs index 06cec8f..ddabb06 100644 --- a/vke/src/base/Image.cs +++ b/vke/src/base/Image.cs @@ -105,6 +105,23 @@ namespace CVKL { #endregion public static uint ComputeMipLevels(uint size) => (uint)Math.Floor (Math.Log (size)) + 1; + public static uint ComputeMipLevels (int width, int height) => (uint)Math.Floor (Math.Log (Math.Max (width, height))) + 1; + + /// <summary> + /// Load image from byte array containing full image file (jpg, png,...) + /// </summary> + public static Image Load (Device dev, Queue staggingQ, CommandPool staggingCmdPool, + byte[] bitmap, VkFormat format = VkFormat.Undefined, + VkMemoryPropertyFlags memoryProps = VkMemoryPropertyFlags.DeviceLocal, + VkImageTiling tiling = VkImageTiling.Optimal, bool generateMipmaps = true, + VkImageType imageType = VkImageType.Image2D, + VkImageUsageFlags usage = VkImageUsageFlags.Sampled | VkImageUsageFlags.TransferSrc | VkImageUsageFlags.TransferDst) { + + Image img = Load (dev, staggingQ, staggingCmdPool, bitmap.Pin (), (ulong)bitmap.Length, format, memoryProps, tiling, generateMipmaps, + imageType, usage); + bitmap.Unpin (); + return img; + } #region bitmap loading /// <summary> @@ -119,42 +136,21 @@ namespace CVKL { if (format == VkFormat.Undefined) format = DefaultTextureFormat; - - int width, height, channels; - IntPtr imgPtr = Stb.Load (bitmap, (int)bitmapByteCount, out width, out height, out channels, 4); - - if (imgPtr == IntPtr.Zero) - throw new Exception ($"STBI image loading error."); - - uint mipLevels = generateMipmaps ? (uint)Math.Floor (Math.Log (Math.Max (width, height))) + 1 : 1; - if (tiling == VkImageTiling.Optimal) usage |= VkImageUsageFlags.TransferDst; if (generateMipmaps) usage |= (VkImageUsageFlags.TransferSrc | VkImageUsageFlags.TransferDst); - Image img = new Image (dev, format, usage, memoryProps, (uint)width, (uint)height, imageType, VkSampleCountFlags.SampleCount1, tiling, mipLevels); + using (StbImage stbi = new StbImage (bitmap, bitmapByteCount)) { + uint mipLevels = generateMipmaps ? ComputeMipLevels (stbi.Width, stbi.Height) : 1; - img.load (staggingQ, staggingCmdPool, imgPtr, generateMipmaps); + Image img = new Image (dev, format, usage, memoryProps, (uint)stbi.Width, (uint)stbi.Height, imageType, + VkSampleCountFlags.SampleCount1, tiling, mipLevels); - Stb.FreeImage (imgPtr); - - return img; - } - /// <summary> - /// Load image from byte array containing full image file (jpg, png,...) - /// </summary> - public static Image Load (Device dev, Queue staggingQ, CommandPool staggingCmdPool, - byte[] bitmap, VkFormat format = VkFormat.Undefined, - VkMemoryPropertyFlags memoryProps = VkMemoryPropertyFlags.DeviceLocal, - VkImageTiling tiling = VkImageTiling.Optimal, bool generateMipmaps = true, - VkImageType imageType = VkImageType.Image2D, - VkImageUsageFlags usage = VkImageUsageFlags.Sampled | VkImageUsageFlags.TransferSrc | VkImageUsageFlags.TransferDst) { + img.load (staggingQ, staggingCmdPool, stbi.Handle, generateMipmaps); - Image img = Load (dev, staggingQ, staggingCmdPool, bitmap.Pin (), (ulong)bitmap.Length, format, memoryProps, tiling, generateMipmaps, - imageType, usage); - bitmap.Unpin (); - return img; + return img; + } } /// <summary> @@ -170,26 +166,21 @@ namespace CVKL { if (format == VkFormat.Undefined) format = DefaultTextureFormat; - - int width, height, channels; - IntPtr imgPtr = Stb.Load (path, out width, out height, out channels, 4); - if (imgPtr == IntPtr.Zero) - throw new Exception ($"File not found: {path}."); - - uint mipLevels = generateMipmaps ? (uint)Math.Floor (Math.Log (Math.Max (width, height))) + 1 : 1; - if (tiling == VkImageTiling.Optimal) usage |= VkImageUsageFlags.TransferDst; if (generateMipmaps) usage |= (VkImageUsageFlags.TransferSrc | VkImageUsageFlags.TransferDst); - Image img = new Image (dev, format, usage, memoryProps, (uint)width, (uint)height, imageType, VkSampleCountFlags.SampleCount1, tiling, mipLevels); + using (StbImage stbi = new StbImage (path)) { + uint mipLevels = generateMipmaps ? ComputeMipLevels (stbi.Width, stbi.Height) : 1; - img.load (staggingQ, staggingCmdPool, imgPtr, generateMipmaps); + Image img = new Image (dev, format, usage, memoryProps, (uint)stbi.Width, (uint)stbi.Height, imageType, + VkSampleCountFlags.SampleCount1, tiling, mipLevels); - Stb.FreeImage (imgPtr); + img.load (staggingQ, staggingCmdPool, stbi.Handle, generateMipmaps); - return img; + return img; + } } /// <summary> @@ -205,25 +196,18 @@ namespace CVKL { if (format == VkFormat.Undefined) format = DefaultTextureFormat; - int width, height, channels; - IntPtr imgPtr = Stb.Load (path, out width, out height, out channels, 4); - if (imgPtr == IntPtr.Zero) - throw new Exception ($"File not found: {path}."); - - long size = width * height * 4; - uint mipLevels = reserveSpaceForMipmaps ? (uint)Math.Floor (Math.Log (Math.Max (width, height))) + 1 : 1; + using (StbImage stbi = new StbImage (path)) { + uint mipLevels = reserveSpaceForMipmaps ? ComputeMipLevels (stbi.Width, stbi.Height) : 1; - Image img = new Image(dev, format, usage, memoryProps, (uint)width, (uint)height, imageType, VkSampleCountFlags.SampleCount1, tiling, mipLevels); + Image img = new Image (dev, format, usage, memoryProps, (uint)stbi.Width, (uint)stbi.Height, imageType, + VkSampleCountFlags.SampleCount1, tiling, mipLevels); - img.Map (); - unsafe { - System.Buffer.MemoryCopy (imgPtr.ToPointer (), img.MappedData.ToPointer (), size, size); - } - img.Unmap (); - - Stb.FreeImage (imgPtr); + img.Map (); + stbi.CoptyTo (img.MappedData); + img.Unmap (); - return img; + return img; + } } /// <summary> /// create host visible linear image without command from byte array @@ -252,30 +236,21 @@ namespace CVKL { if (format == VkFormat.Undefined) format = DefaultTextureFormat; - - int width, height, channels; - IntPtr imgPtr = Stb.Load (bitmap, (int)bitmapByteCount, out width, out height, out channels, 4); - - if (imgPtr == IntPtr.Zero) - throw new Exception ($"STBI image loading error."); - - uint mipLevels = generateMipmaps ? (uint)Math.Floor (Math.Log (Math.Max (width, height))) + 1 : 1; - if (generateMipmaps) usage |= (VkImageUsageFlags.TransferSrc | VkImageUsageFlags.TransferDst); - long size = width * height * 4; - Image img = new Image (dev, format, usage, memoryProps, (uint)width, (uint)height, imageType, VkSampleCountFlags.SampleCount1, tiling, mipLevels); + using (StbImage stbi = new StbImage (bitmap, bitmapByteCount)) { + uint mipLevels = generateMipmaps ? ComputeMipLevels (stbi.Width, stbi.Height) : 1; - img.Map (); - unsafe { - System.Buffer.MemoryCopy (imgPtr.ToPointer (), img.MappedData.ToPointer (), size, size); - } - img.Unmap (); + Image img = new Image (dev, format, usage, memoryProps, (uint)stbi.Width, (uint)stbi.Height, imageType, + VkSampleCountFlags.SampleCount1, tiling, mipLevels); - Stb.FreeImage (imgPtr); + img.Map (); + stbi.CoptyTo (img.MappedData); + img.Unmap (); - return img; + return img; + } } /// <summary> @@ -296,9 +271,7 @@ namespace CVKL { } else { using (HostBuffer stagging = new HostBuffer (Dev, VkBufferUsageFlags.TransferSrc, (UInt64)size, bitmap)) { - CommandBuffer cmd = staggingCmdPool.AllocateCommandBuffer (); - - cmd.Start (VkCommandBufferUsageFlags.OneTimeSubmit); + CommandBuffer cmd = staggingCmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); stagging.CopyTo (cmd, this); if (generateMipmaps) @@ -318,19 +291,30 @@ namespace CVKL { vkGetImageMemoryRequirements (Dev.VkDev, handle, out memReqs); } internal override void bindMemory () { +#if MEMORY_POOLS Utils.CheckResult (vkBindImageMemory (Dev.VkDev, handle, memoryPool.vkMemory, poolOffset)); +#else + Utils.CheckResult (vkBindImageMemory (Dev.VkDev, handle, vkMemory, 0)); +#endif } public override void Activate () { if (state != ActivableState.Activated) { Utils.CheckResult (vkCreateImage (Dev.VkDev, ref info, IntPtr.Zero, out handle)); +#if MEMORY_POOLS Dev.resourceManager.Add (this); +#else + updateMemoryRequirements (); + allocateMemory (); + bindMemory (); +#endif + } base.Activate (); } public void CreateView (VkImageViewType type = VkImageViewType.ImageView2D, VkImageAspectFlags aspectFlags = VkImageAspectFlags.Color, uint layerCount = 1, - uint baseMipLevel = 0, uint levelCount = 1, uint baseArrayLayer = 0, + uint baseMipLevel = 0, int levelCount = -1, uint baseArrayLayer = 0, VkComponentSwizzle r = VkComponentSwizzle.R, VkComponentSwizzle g = VkComponentSwizzle.G, VkComponentSwizzle b = VkComponentSwizzle.B, @@ -346,10 +330,10 @@ namespace CVKL { viewInfo.components.b = b; viewInfo.components.a = a; viewInfo.subresourceRange.aspectMask = aspectFlags; - viewInfo.subresourceRange.baseMipLevel = baseMipLevel; - viewInfo.subresourceRange.levelCount = levelCount; - viewInfo.subresourceRange.baseArrayLayer = baseArrayLayer; - viewInfo.subresourceRange.layerCount = layerCount; + viewInfo.subresourceRange.baseMipLevel = baseMipLevel; + viewInfo.subresourceRange.levelCount = levelCount < 0 ? info.mipLevels : (uint)levelCount; + viewInfo.subresourceRange.baseArrayLayer = baseArrayLayer; + viewInfo.subresourceRange.layerCount = layerCount; Utils.CheckResult (vkCreateImageView (Dev.VkDev, ref viewInfo, IntPtr.Zero, out view)); @@ -379,7 +363,9 @@ namespace CVKL { sampInfo.minFilter = minFilter; sampInfo.mipmapMode = mipmapMode; sampInfo.minLod = minLod; - sampInfo.maxLod = maxLod < 0f ? info.mipLevels : maxLod; + sampInfo.maxLod = maxLod < 0f ? info.mipLevels > 1 ? info.mipLevels : 0 : maxLod; + sampInfo.compareOp = VkCompareOp.Never; + sampInfo.borderColor = VkBorderColor.FloatOpaqueWhite; Utils.CheckResult (vkCreateSampler (Dev.VkDev, ref sampInfo, IntPtr.Zero, out sampler)); @@ -541,9 +527,6 @@ namespace CVKL { public void BuildMipmaps (CommandBuffer cmd) { VkImageSubresourceRange mipSubRange = new VkImageSubresourceRange (VkImageAspectFlags.Color, 0, 1, 0, info.arrayLayers); - SetLayout (cmd, VkImageLayout.Undefined, VkImageLayout.TransferSrcOptimal, mipSubRange, - VkPipelineStageFlags.BottomOfPipe, VkPipelineStageFlags.Transfer); - for (int i = 1; i < info.mipLevels; i++) { VkImageBlit imageBlit = new VkImageBlit { srcSubresource = new VkImageSubresourceLayers(VkImageAspectFlags.Color, info.arrayLayers, (uint)i - 1), @@ -552,13 +535,10 @@ namespace CVKL { dstOffsets_1 = new VkOffset3D ((int)info.extent.width >> i, (int)info.extent.height >> i, 1) }; - mipSubRange.baseMipLevel = (uint)i; - - SetLayout (cmd, VkImageLayout.Undefined, VkImageLayout.TransferDstOptimal, mipSubRange, - VkPipelineStageFlags.Transfer, VkPipelineStageFlags.Transfer); - vkCmdBlitImage (cmd.Handle, handle, VkImageLayout.TransferSrcOptimal, handle, VkImageLayout.TransferDstOptimal, 1, ref imageBlit, VkFilter.Linear); SetLayout (cmd, VkImageLayout.TransferDstOptimal, VkImageLayout.TransferSrcOptimal, mipSubRange, VkPipelineStageFlags.Transfer, VkPipelineStageFlags.Transfer); + vkCmdBlitImage (cmd.Handle, handle, VkImageLayout.TransferSrcOptimal, handle, VkImageLayout.TransferDstOptimal, 1, ref imageBlit, VkFilter.Linear); + mipSubRange.baseMipLevel = (uint)i; } SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.TransferSrcOptimal, VkImageLayout.ShaderReadOnlyOptimal, VkPipelineStageFlags.Transfer, VkPipelineStageFlags.FragmentShader); diff --git a/vke/src/base/Instance.cs b/vke/src/base/Instance.cs index 199bbdb..cf583dc 100644 --- a/vke/src/base/Instance.cs +++ b/vke/src/base/Instance.cs @@ -44,6 +44,7 @@ namespace CVKL { VkInstance inst; public IntPtr Handle => inst.Handle; + public VkInstance VkInstance => inst; static class Strings { @@ -55,7 +56,8 @@ namespace CVKL { public static FixedUtf8String VK_KHR_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_swapchain"; public static FixedUtf8String VK_EXT_DEBUG_REPORT_EXTENSION_NAME = "VK_EXT_debug_report"; public static FixedUtf8String VK_EXT_DEBUG_UTILS_EXTENSION_NAME = "VK_EXT_debug_utils"; - public static FixedUtf8String LayerValidation = "VK_LAYER_KHRONOS_validation"; + public static FixedUtf8String LayerValidation = "VK_LAYER_KHRONOS_validation"; + public static FixedUtf8String LayerValidation_old = "VK_LAYER_LUNARG_standard_validation"; public static FixedUtf8String LayerMonitor = "VK_LAYER_LUNARG_monitor"; public static FixedUtf8String VkTraceLayeName = "VK_LAYER_LUNARG_vktrace"; public static FixedUtf8String RenderdocCaptureLayerName = "VK_LAYER_RENDERDOC_Capture"; @@ -66,6 +68,24 @@ namespace CVKL { init (); } + unsafe bool ExtensionIsSupported (FixedUtf8String layer, string extName) { + uint count; + Utils.CheckResult (vkEnumerateInstanceExtensionProperties ((IntPtr)layer, out count, IntPtr.Zero)); + VkExtensionProperties[] tmp = new VkExtensionProperties[count]; + Utils.CheckResult (vkEnumerateInstanceExtensionProperties (layer, out count, tmp.Pin ())); + tmp.Unpin (); + + fixed (VkExtensionProperties* ep = tmp) { + for (int i = 0; i < tmp.Length; i++) { + IntPtr n = (IntPtr)ep[i].extensionName; + if (Marshal.PtrToStringAnsi (n) == extName) + return true; + } + } + return false; + } + + void init () { List<IntPtr> instanceExtensions = new List<IntPtr> (); @@ -80,15 +100,20 @@ namespace CVKL { throw new PlatformNotSupportedException (); } - if (VALIDATION) + if (VALIDATION) { enabledLayerNames.Add (Strings.LayerValidation); + enabledLayerNames.Add (Strings.LayerValidation_old); + + if (DEBUG_UTILS) { + //if (ExtensionIsSupported(Strings.LayerValidation, Strings.VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) + instanceExtensions.Add (Strings.VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + instanceExtensions.Add (Strings.VK_EXT_DEBUG_REPORT_EXTENSION_NAME); + } + + } if (RENDER_DOC_CAPTURE) enabledLayerNames.Add (Strings.RenderdocCaptureLayerName); - if (DEBUG_UTILS) { - instanceExtensions.Add (Strings.VK_EXT_DEBUG_UTILS_EXTENSION_NAME); - instanceExtensions.Add (Strings.VK_EXT_DEBUG_REPORT_EXTENSION_NAME); - } VkApplicationInfo appInfo = new VkApplicationInfo () { sType = VkStructureType.ApplicationInfo, diff --git a/vke/src/base/Resource.cs b/vke/src/base/Resource.cs index 50deb39..ebde92b 100644 --- a/vke/src/base/Resource.cs +++ b/vke/src/base/Resource.cs @@ -8,8 +8,13 @@ using static VK.Vk; namespace CVKL { public abstract class Resource : Activable { protected VkMemoryRequirements memReqs; +#if MEMORY_POOLS internal MemoryPool memoryPool; public ulong poolOffset; +#else + protected VkDeviceMemory vkMemory; +#endif + /// <summary> double linked list in memory pool </summary> internal Resource previous; public Resource next; @@ -33,20 +38,42 @@ namespace CVKL { internal VkMappedMemoryRange MapRange => new VkMappedMemoryRange { sType = VkStructureType.MappedMemoryRange, +#if MEMORY_POOLS memory = memoryPool.vkMemory, offset = poolOffset, +#else + memory = vkMemory, + offset = 0, +#endif size = AllocatedDeviceMemorySize }; +#if !MEMORY_POOLS + protected void allocateMemory () { + VkMemoryAllocateInfo memInfo = VkMemoryAllocateInfo.New (); + memInfo.allocationSize = memReqs.size; + memInfo.memoryTypeIndex = Dev.GetMemoryTypeIndex (memReqs.memoryTypeBits, MemoryFlags); + Utils.CheckResult (vkAllocateMemory (Dev.VkDev, ref memInfo, IntPtr.Zero, out vkMemory)); + } +#endif + public void Map (ulong offset = 0) { +#if MEMORY_POOLS if (!memoryPool.IsMapped) memoryPool.Map (); mappedData = new IntPtr(memoryPool.MappedData.ToInt64() + (long)(poolOffset + offset)); - } - public void Unmap () { - - } - public void Update (object data, ulong size, ulong offset = 0) { +#else + Utils.CheckResult (vkMapMemory (Dev.VkDev, vkMemory, offset, AllocatedDeviceMemorySize, 0, ref mappedData)); +#endif + } + public void Unmap () { +#if MEMORY_POOLS +#else + vkUnmapMemory (Dev.VkDev, vkMemory); + mappedData = IntPtr.Zero; +#endif + } + public void Update (object data, ulong size, ulong offset = 0) { GCHandle ptr = GCHandle.Alloc (data, GCHandleType.Pinned); unsafe { System.Buffer.MemoryCopy (ptr.AddrOfPinnedObject ().ToPointer (), (mappedData + (int)offset).ToPointer (), size, size); @@ -58,17 +85,22 @@ namespace CVKL { vkFlushMappedMemoryRanges (Dev.VkDev, 1, ref range); } - #region IDisposable Support +#region IDisposable Support protected override void Dispose (bool disposing) { if (!disposing) System.Diagnostics.Debug.WriteLine ("VKE Activable object disposed by finalizer"); if (state == ActivableState.Activated) { if (mappedData != IntPtr.Zero) Unmap (); +#if MEMORY_POOLS memoryPool.Remove (this); +#else + vkFreeMemory (Dev.VkDev, vkMemory, IntPtr.Zero); +#endif + } base.Dispose (disposing); } - #endregion +#endregion } }
\ No newline at end of file diff --git a/vke/src/ktx.cs b/vke/src/ktx.cs index 4c71dff..e78071f 100644 --- a/vke/src/ktx.cs +++ b/vke/src/ktx.cs @@ -58,10 +58,10 @@ namespace KTX { UInt32 glBaseInternalFormat = br.ReadUInt32 (); UInt32 pixelWidth = br.ReadUInt32 (); UInt32 pixelHeight = br.ReadUInt32 (); - UInt32 pixelDepth = Math.Min (1, br.ReadUInt32 ()); + UInt32 pixelDepth = Math.Max (1, br.ReadUInt32 ()); UInt32 numberOfArrayElements = br.ReadUInt32 ();//only for array text, else 0 - UInt32 numberOfFaces = br.ReadUInt32 ();//only for cube map, else - UInt32 numberOfMipmapLevels = Math.Min (1, br.ReadUInt32 ()); + UInt32 numberOfFaces = br.ReadUInt32 ();//only for cube map, else 1 + UInt32 numberOfMipmapLevels = Math.Max (1, br.ReadUInt32 ()); UInt32 bytesOfKeyValueData = br.ReadUInt32 (); VkFormat vkFormat = GLHelper.vkGetFormatFromOpenGLInternalFormat (glInternalFormat); @@ -90,7 +90,7 @@ namespace KTX { VkImageType imgType = (pixelWidth == 0) ? throw new KtxException ("pixelWidth must be > 0") : (pixelHeight == 0) ? imgType = VkImageType.Image1D : - (pixelDepth == 0) ? imgType = VkImageType.Image2D : imgType = VkImageType.Image3D; + (pixelDepth == 1) ? imgType = VkImageType.Image2D : imgType = VkImageType.Image3D; VkSampleCountFlags samples = VkSampleCountFlags.SampleCount1; @@ -106,9 +106,6 @@ namespace KTX { if (numberOfArrayElements == 0) numberOfArrayElements = 1; } - - if (imgType != VkImageType.Image3D) - pixelDepth = 1; img = new Image (staggingQ.Dev, vkFormat, usage, memoryProperty, pixelWidth, pixelHeight, imgType, samples, tiling, requestedMipsLevels, numberOfArrayElements, pixelDepth, createFlags); @@ -117,13 +114,12 @@ namespace KTX { if (memoryProperty.HasFlag (VkMemoryPropertyFlags.DeviceLocal)) { - ulong staggingSize = img.AllocatedDeviceMemorySize; + ulong staggingSize = (ulong)ktxStream.Length;//img.AllocatedDeviceMemorySize; using (HostBuffer stagging = new HostBuffer (staggingQ.Dev, VkBufferUsageFlags.TransferSrc, staggingSize)) { stagging.Map (); - CommandBuffer cmd = staggingCmdPool.AllocateCommandBuffer (); - cmd.Start (VkCommandBufferUsageFlags.OneTimeSubmit); + CommandBuffer cmd = staggingCmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); img.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.Undefined, VkImageLayout.TransferDstOptimal, VkPipelineStageFlags.AllCommands, VkPipelineStageFlags.Transfer); @@ -136,47 +132,64 @@ namespace KTX { }; ulong bufferOffset = 0; - uint imgWidth = img.CreateInfo.extent.height; - uint imgHeight = img.CreateInfo.extent.width; + uint imgWidth = img.CreateInfo.extent.width; + uint imgHeight = img.CreateInfo.extent.height; for (int mips = 0; mips < numberOfMipmapLevels; mips++) { UInt32 imgSize = br.ReadUInt32 (); - bufferCopyRegion.bufferImageHeight = imgWidth; - bufferCopyRegion.bufferRowLength = 0; //imgHeight; + bufferCopyRegion.bufferImageHeight = imgHeight; + bufferCopyRegion.bufferRowLength = imgWidth; bufferCopyRegion.bufferOffset = bufferOffset; + bufferCopyRegion.imageSubresource.mipLevel = (uint)mips; + bufferCopyRegion.imageExtent.width = imgWidth; + bufferCopyRegion.imageExtent.height = imgHeight; if (createFlags.HasFlag (VkImageCreateFlags.CubeCompatible)) { - IntPtr ptrFace = img.MappedData; - bufferCopyRegion.imageSubresource.layerCount = 1; + //IntPtr ptrFace = img.MappedData; + //bufferCopyRegion.imageSubresource.layerCount = 1; for (uint face = 0; face < numberOfFaces; face++) { - bufferCopyRegion.imageSubresource.baseArrayLayer = face; + //bufferCopyRegion.imageSubresource.baseArrayLayer = face; Marshal.Copy (br.ReadBytes ((int)imgSize), 0, stagging.MappedData + (int)bufferOffset, (int)imgSize); - buffCopies.Add (bufferCopyRegion); + uint faceOffset = imgSize + (imgSize % 4); - ptrFace += (int)faceOffset;//cube padding + //ptrFace += (int)faceOffset;//cube padding bufferOffset += faceOffset; - bufferCopyRegion.bufferOffset = bufferOffset; } + buffCopies.Add (bufferCopyRegion); + bufferCopyRegion.bufferOffset = bufferOffset; } else { - Marshal.Copy (br.ReadBytes ((int)imgSize), 0, stagging.MappedData, (int)imgSize); + + Marshal.Copy (br.ReadBytes ((int)imgSize), 0, stagging.MappedData + (int)bufferOffset, (int)imgSize); buffCopies.Add (bufferCopyRegion); + bufferOffset += imgSize; } - bufferOffset += imgSize; + imgWidth /= 2; imgHeight /= 2; + //break; } stagging.Unmap (); + Vk.vkCmdCopyBufferToImage (cmd.Handle, stagging.handle, img.handle, VkImageLayout.TransferDstOptimal, (uint)buffCopies.Count, buffCopies.Pin()); buffCopies.Unpin (); + /*cmd.End (); + + staggingQ.Submit (cmd); + staggingQ.WaitIdle (); + + cmd.Free (); + + cmd = staggingCmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); + */ if (requestedMipsLevels > numberOfMipmapLevels) - img.BuildMipmaps (cmd); + img.BuildMipmaps (cmd); else img.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.TransferDstOptimal, VkImageLayout.ShaderReadOnlyOptimal, - VkPipelineStageFlags.Transfer, VkPipelineStageFlags.AllGraphics); + VkPipelineStageFlags.Transfer, VkPipelineStageFlags.TopOfPipe); cmd.End (); diff --git a/vke/src/model/glTFLoader.cs b/vke/src/model/glTFLoader.cs index 9c6dae7..29abc6a 100644 --- a/vke/src/model/glTFLoader.cs +++ b/vke/src/model/glTFLoader.cs @@ -483,14 +483,11 @@ namespace CVKL { vkimg.Dispose (); } - uint imgCount = (uint)gltf.Images.Length; + cmd = cmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); VkImageSubresourceRange mipSubRange = new VkImageSubresourceRange (VkImageAspectFlags.Color, 0, 1, firstImg, imgCount); + uint imgCount = (uint)gltf.Images.Length; - cmd = cmdPool.AllocateAndStart (VkCommandBufferUsageFlags.OneTimeSubmit); - texArray.SetLayout (cmd, VkImageLayout.Undefined, VkImageLayout.TransferSrcOptimal, mipSubRange, - VkPipelineStageFlags.Transfer, VkPipelineStageFlags.Transfer); - for (int i = 1; i < texArray.CreateInfo.mipLevels; i++) { imageBlit = new VkImageBlit { srcSubresource = new VkImageSubresourceLayers (VkImageAspectFlags.Color, imgCount, (uint)i - 1, firstImg), @@ -498,14 +495,12 @@ namespace CVKL { dstSubresource = new VkImageSubresourceLayers (VkImageAspectFlags.Color, imgCount, (uint)i, firstImg), dstOffsets_1 = new VkOffset3D ((int)texDim >> i, (int)texDim >> i, 1) }; - mipSubRange.baseMipLevel = (uint)i; - texArray.SetLayout (cmd, VkImageLayout.Undefined, VkImageLayout.TransferDstOptimal, mipSubRange, - VkPipelineStageFlags.Transfer, VkPipelineStageFlags.Transfer); Vk.vkCmdBlitImage (cmd.Handle, texArray.handle, VkImageLayout.TransferSrcOptimal, texArray.handle, VkImageLayout.TransferDstOptimal, 1, ref imageBlit, VkFilter.Linear); texArray.SetLayout (cmd, VkImageLayout.TransferDstOptimal, VkImageLayout.TransferSrcOptimal, mipSubRange, VkPipelineStageFlags.Transfer, VkPipelineStageFlags.Transfer); + mipSubRange.baseMipLevel = (uint)i; } texArray.SetLayout (cmd, VkImageAspectFlags.Color, VkImageLayout.TransferSrcOptimal, VkImageLayout.ShaderReadOnlyOptimal, diff --git a/vke/src/stb.cs b/vke/src/stb.cs deleted file mode 100644 index b573a90..0000000 --- a/vke/src/stb.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace CVKL { - public static class Stb { - public const string stblib = "stb"; - - [DllImport (stblib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "stbi_load")] - public static extern IntPtr Load ([MarshalAs (UnmanagedType.LPStr)] string filename, out int x, out int y, out int channels_in_file, int desired_channels); - - [DllImport (stblib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "stbi_load_from_memory")] - public static extern IntPtr Load (IntPtr bitmap, int byteCount, out int x, out int y, out int channels_in_file, int desired_channels); - - [DllImport (stblib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "stbi_image_free")] - public static extern void FreeImage (IntPtr img); - } -} |