diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index c9afb01c1..616a6fe91 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -89,7 +89,7 @@ jobs: # Setup compilation mode and install project dependencies - name: Configure xmake and install dependencies - run: xmake config --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.config.arch }} --mode=coverage --yes + run: xmake config --ccache=n --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.config.arch }} --mode=coverage --yes # Build the engine - name: Build Nazara diff --git a/.github/workflows/linux-build.yml b/.github/workflows/linux-build.yml index 06bb9826a..2c446821b 100644 --- a/.github/workflows/linux-build.yml +++ b/.github/workflows/linux-build.yml @@ -68,7 +68,7 @@ jobs: # Setup compilation mode and install project dependencies - name: Configure xmake and install dependencies - run: xmake config --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes + run: xmake config --ccache=n --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes # Build the engine - name: Build Nazara diff --git a/.github/workflows/macos-build.yml b/.github/workflows/macos-build.yml index a6938aacd..34f18f19d 100644 --- a/.github/workflows/macos-build.yml +++ b/.github/workflows/macos-build.yml @@ -62,7 +62,7 @@ jobs: # Setup compilation mode and install project dependencies - name: Configure xmake and install dependencies - run: xmake config --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes + run: xmake config --ccache=n --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes # Build the engine - name: Build Nazara diff --git a/.github/workflows/msys2-build.yml b/.github/workflows/msys2-build.yml index c2992e63b..9b129f2d6 100644 --- a/.github/workflows/msys2-build.yml +++ b/.github/workflows/msys2-build.yml @@ -92,7 +92,7 @@ jobs: # Setup compilation mode and install project dependencies - name: Configure xmake and install dependencies - run: xmake config --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes + run: xmake config --ccache=n --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes # Build the engine - name: Build Nazara diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index 1e11a0cbd..df3ec8fbc 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -62,7 +62,7 @@ jobs: # Setup compilation mode and install project dependencies - name: Configure xmake and install dependencies - run: xmake.exe config --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes + run: xmake.exe config --ccache=n --shadernodes=y --tests=y --unitybuild=y --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes # Build the engine - name: Build Nazara diff --git a/examples/DeferredShading/main.cpp b/examples/DeferredShading/main.cpp index e5192246c..971696adb 100644 --- a/examples/DeferredShading/main.cpp +++ b/examples/DeferredShading/main.cpp @@ -3,8 +3,9 @@ #include #include #include -#include #include +#include +#include #include #include #include @@ -77,7 +78,7 @@ int main() Nz::Modules nazara(rendererConfig); - Nz::ShaderWriter::States states; + nzsl::ShaderWriter::States states; states.shaderModuleResolver = Nz::Graphics::Instance()->GetShaderModuleResolver(); Nz::RenderWindow window; @@ -136,13 +137,13 @@ int main() skyboxPipelineLayoutInfo.bindings.push_back({ 0, 0, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType_All + nzsl::ShaderStageType_All }); auto& textureBinding = skyboxPipelineLayoutInfo.bindings.emplace_back(); textureBinding.setIndex = 0; textureBinding.bindingIndex = 1; - textureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment; + textureBinding.shaderStageFlags = nzsl::ShaderStageType::Fragment; textureBinding.type = Nz::ShaderBindingType::Texture; std::shared_ptr skyboxPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(skyboxPipelineLayoutInfo)); @@ -153,7 +154,7 @@ int main() skyboxPipelineInfo.faceCulling = true; skyboxPipelineInfo.cullingSide = Nz::FaceSide::Front; skyboxPipelineInfo.pipelineLayout = skyboxPipelineLayout; - skyboxPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "skybox.nzsl", states)); + skyboxPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "skybox.nzsl", states)); skyboxPipelineInfo.vertexBuffers.push_back({ 0, meshPrimitiveParams.vertexDeclaration @@ -186,8 +187,8 @@ int main() auto customSettings = Nz::BasicMaterial::GetSettings()->GetBuilderData(); customSettings.shaders.clear(); - customSettings.shaders.emplace_back(std::make_shared(Nz::ShaderStageType::Fragment, Nz::ShaderLang::ParseFromFile(resourceDir / "deferred_frag.nzsl"))); - customSettings.shaders.emplace_back(std::make_shared(Nz::ShaderStageType::Vertex, Nz::ShaderLang::ParseFromFile(resourceDir / "deferred_vert.nzsl"))); + customSettings.shaders.emplace_back(std::make_shared(nzsl::ShaderStageType::Fragment, nzsl::ParseFromFile(resourceDir / "deferred_frag.nzsl"))); + customSettings.shaders.emplace_back(std::make_shared(nzsl::ShaderStageType::Vertex, nzsl::ParseFromFile(resourceDir / "deferred_vert.nzsl"))); auto customMatSettings = std::make_shared(std::move(customSettings)); @@ -269,7 +270,7 @@ int main() lightingPipelineLayoutInfo.bindings.push_back({ 0, 0, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType_All + nzsl::ShaderStageType_All }); for (unsigned int i = 0; i < 3; ++i) @@ -278,7 +279,7 @@ int main() 0, i + 1, Nz::ShaderBindingType::Texture, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }); } @@ -286,15 +287,15 @@ int main() 1, 0, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, + nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, }); - /*Nz::FieldOffsets pointLightOffsets(Nz::StructLayout::Std140); - std::size_t colorOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float3); - std::size_t positionOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float3); - std::size_t constantOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t linearOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t quadraticOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float1); + /*nzsl::FieldOffsets pointLightOffsets(nzsl::StructLayout::Std140); + std::size_t colorOffset = pointLightOffsets.AddField(nzsl::StructFieldType::Float3); + std::size_t positionOffset = pointLightOffsets.AddField(nzsl::StructFieldType::Float3); + std::size_t constantOffset = pointLightOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t linearOffset = pointLightOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t quadraticOffset = pointLightOffsets.AddField(nzsl::StructFieldType::Float1); std::size_t alignedPointLightSize = Nz::Align(pointLightOffsets.GetSize(), static_cast(deviceInfo.limits.minUniformBufferOffsetAlignment));*/ @@ -315,15 +316,15 @@ int main() } */ - Nz::FieldOffsets spotLightOffsets(Nz::StructLayout::Std140); - std::size_t transformMatrixOffset = spotLightOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true); - std::size_t colorOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float3); - std::size_t positionOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float3); - std::size_t directionOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float3); - std::size_t radiusOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t invRadiusOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t innerAngleOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t outerAngleOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); + nzsl::FieldOffsets spotLightOffsets(nzsl::StructLayout::Std140); + std::size_t transformMatrixOffset = spotLightOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + std::size_t colorOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float3); + std::size_t positionOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float3); + std::size_t directionOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float3); + std::size_t radiusOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t invRadiusOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t innerAngleOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t outerAngleOffset = spotLightOffsets.AddField(nzsl::StructFieldType::Float1); std::size_t alignedSpotLightSize = Nz::Align(spotLightOffsets.GetAlignedSize(), static_cast(deviceInfo.limits.minUniformBufferOffsetAlignment)); @@ -367,13 +368,13 @@ int main() fullscreenPipelineLayoutInfoViewer.bindings.push_back({ 0, 0, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType_All + nzsl::ShaderStageType_All }); fullscreenPipelineLayoutInfoViewer.bindings.push_back({ 0, 1, Nz::ShaderBindingType::Texture, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }); Nz::RenderPipelineInfo fullscreenPipelineInfoViewer; @@ -384,7 +385,7 @@ int main() fullscreenVertexDeclaration }); - fullscreenPipelineInfoViewer.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "bloom_bright.nzsl", states)); + fullscreenPipelineInfoViewer.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "bloom_bright.nzsl", states)); std::shared_ptr bloomBrightShaderBinding; @@ -397,18 +398,18 @@ int main() gaussianBlurPipelineLayoutInfo.bindings.push_back({ 0, 2, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }); Nz::RenderPipelineInfo gaussianBlurPipelineInfo = fullscreenPipelineInfoViewer; gaussianBlurPipelineInfo.pipelineLayout = device->InstantiateRenderPipelineLayout(gaussianBlurPipelineLayoutInfo); - Nz::FieldOffsets gaussianBlurDataOffsets(Nz::StructLayout::Std140); - std::size_t gaussianBlurDataDirection = gaussianBlurDataOffsets.AddField(Nz::StructFieldType::Float2); - std::size_t gaussianBlurDataSize = gaussianBlurDataOffsets.AddField(Nz::StructFieldType::Float1); + nzsl::FieldOffsets gaussianBlurDataOffsets(nzsl::StructLayout::Std140); + std::size_t gaussianBlurDataDirection = gaussianBlurDataOffsets.AddField(nzsl::StructFieldType::Float2); + std::size_t gaussianBlurDataSize = gaussianBlurDataOffsets.AddField(nzsl::StructFieldType::Float1); gaussianBlurPipelineInfo.shaderModules.clear(); - gaussianBlurPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "gaussian_blur.nzsl", states)); + gaussianBlurPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "gaussian_blur.nzsl", states)); std::shared_ptr gaussianBlurPipeline = device->InstantiateRenderPipeline(gaussianBlurPipelineInfo); std::vector> gaussianBlurShaderBinding(BloomSubdivisionCount * 2); @@ -438,7 +439,7 @@ int main() std::shared_ptr toneMappingShaderBinding; fullscreenPipelineInfoViewer.shaderModules.clear(); - fullscreenPipelineInfoViewer.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "tone_mapping.nzsl", states)); + fullscreenPipelineInfoViewer.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "tone_mapping.nzsl", states)); std::shared_ptr toneMappingPipeline = device->InstantiateRenderPipeline(fullscreenPipelineInfoViewer); @@ -450,19 +451,19 @@ int main() bloomBlendPipelineLayoutInfo.bindings.push_back({ 0, 0, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType_All + nzsl::ShaderStageType_All }); /*bloomBlendPipelineLayoutInfo.bindings.push_back({ 0, 1, Nz::ShaderBindingType::Texture, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, });*/ bloomBlendPipelineLayoutInfo.bindings.push_back({ 0, 2, Nz::ShaderBindingType::Texture, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }); @@ -477,7 +478,7 @@ int main() fullscreenVertexDeclaration }); - bloomBlendPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "bloom_final.nzsl", states)); + bloomBlendPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "bloom_final.nzsl", states)); std::shared_ptr bloomBlendPipeline = device->InstantiateRenderPipeline(bloomBlendPipelineInfo); @@ -490,7 +491,7 @@ int main() fullscreenPipelineLayoutInfo.bindings.push_back({ 0, 0, Nz::ShaderBindingType::Texture, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }); Nz::RenderPipelineInfo fullscreenPipelineInfo; @@ -501,7 +502,7 @@ int main() fullscreenVertexDeclaration }); - fullscreenPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "gamma.nzsl", states)); + fullscreenPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "gamma.nzsl", states)); // God rays @@ -512,17 +513,17 @@ int main() { 0, 0, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }, { 0, 1, Nz::ShaderBindingType::UniformBuffer, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }, { 0, 2, Nz::ShaderBindingType::Texture, - Nz::ShaderStageType::Fragment, + nzsl::ShaderStageType::Fragment, }, } }; @@ -535,16 +536,16 @@ int main() fullscreenVertexDeclaration }); - godraysPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "god_rays.nzsl", states)); + godraysPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "god_rays.nzsl", states)); std::shared_ptr godraysPipeline = device->InstantiateRenderPipeline(godraysPipelineInfo); - Nz::FieldOffsets godraysFieldOffsets(Nz::StructLayout::Std140); - std::size_t gr_exposureOffset = godraysFieldOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t gr_decayOffset = godraysFieldOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t gr_densityOffset = godraysFieldOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t gr_weightOffset = godraysFieldOffsets.AddField(Nz::StructFieldType::Float1); - std::size_t gr_lightPositionOffset = godraysFieldOffsets.AddField(Nz::StructFieldType::Float2); + nzsl::FieldOffsets godraysFieldOffsets(nzsl::StructLayout::Std140); + std::size_t gr_exposureOffset = godraysFieldOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t gr_decayOffset = godraysFieldOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t gr_densityOffset = godraysFieldOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t gr_weightOffset = godraysFieldOffsets.AddField(nzsl::StructFieldType::Float1); + std::size_t gr_lightPositionOffset = godraysFieldOffsets.AddField(nzsl::StructFieldType::Float2); std::shared_ptr godRaysShaderBinding = godraysPipelineInfo.pipelineLayout->AllocateShaderBinding(0); @@ -590,7 +591,7 @@ int main() lightingPipelineInfo.stencilBack.depthFail = Nz::StencilOperation::Zero; lightingPipelineInfo.stencilBack.pass = Nz::StencilOperation::Zero; - lightingPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "lighting.nzsl", states)); + lightingPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "lighting.nzsl", states)); std::shared_ptr lightingPipeline = device->InstantiateRenderPipeline(lightingPipelineInfo); @@ -612,7 +613,7 @@ int main() stencilPipelineInfo.stencilBack.compare = Nz::RendererComparison::Always; stencilPipelineInfo.stencilBack.depthFail = Nz::StencilOperation::Invert; - stencilPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "lighting.nzsl", states)); + stencilPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(nzsl::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "lighting.nzsl", states)); std::shared_ptr stencilPipeline = device->InstantiateRenderPipeline(stencilPipelineInfo); diff --git a/examples/GraphicsTest/main.cpp b/examples/GraphicsTest/main.cpp index 9b2aee326..590d876b8 100644 --- a/examples/GraphicsTest/main.cpp +++ b/examples/GraphicsTest/main.cpp @@ -2,9 +2,8 @@ #include #include #include -#include -#include -#include +#include +#include #include #include #include diff --git a/examples/Physics2DDemo/main.cpp b/examples/Physics2DDemo/main.cpp index d36630c25..498490574 100644 --- a/examples/Physics2DDemo/main.cpp +++ b/examples/Physics2DDemo/main.cpp @@ -1,191 +1,191 @@ -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -NAZARA_REQUEST_DEDICATED_GPU() - -int main() -{ - std::filesystem::path resourceDir = "resources"; - if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) - resourceDir = ".." / resourceDir; - - Nz::Renderer::Config rendererConfig; - std::cout << "Run using Vulkan? (y/n)" << std::endl; - if (std::getchar() != 'n') - rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; - else - rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; - - std::cin.ignore(std::numeric_limits::max(), '\n'); - - Nz::Modules nazara(rendererConfig); - - Nz::RenderWindow window; - - std::shared_ptr device = Nz::Graphics::Instance()->GetRenderDevice(); - - std::string windowTitle = "Graphics Test"; - if (!window.Create(device, Nz::VideoMode(1920, 1080, 32), windowTitle)) - { - std::cout << "Failed to create Window" << std::endl; - return __LINE__; - } - - entt::registry registry; - +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +NAZARA_REQUEST_DEDICATED_GPU() + +int main() +{ + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Renderer::Config rendererConfig; + std::cout << "Run using Vulkan? (y/n)" << std::endl; + if (std::getchar() != 'n') + rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; + else + rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; + + std::cin.ignore(std::numeric_limits::max(), '\n'); + + Nz::Modules nazara(rendererConfig); + + Nz::RenderWindow window; + + std::shared_ptr device = Nz::Graphics::Instance()->GetRenderDevice(); + + std::string windowTitle = "Graphics Test"; + if (!window.Create(device, Nz::VideoMode(1920, 1080, 32), windowTitle)) + { + std::cout << "Failed to create Window" << std::endl; + return __LINE__; + } + + entt::registry registry; + Nz::Physics2DSystem physSytem(registry); physSytem.GetPhysWorld().SetGravity({ 0.f, -9.81f }); - - Nz::RenderSystem renderSystem(registry); - - entt::entity viewer = registry.create(); - { - registry.emplace(viewer); - auto& cameraComponent = registry.emplace(viewer, window.GetRenderTarget(), Nz::ProjectionType::Orthographic); - cameraComponent.UpdateRenderMask(1); - cameraComponent.UpdateClearColor(Nz::Color(0.5f, 0.5f, 0.5f)); - } - std::shared_ptr material = std::make_shared(); - - std::shared_ptr materialPass = std::make_shared(Nz::BasicMaterial::GetSettings()); - material->AddPass("ForwardPass", materialPass); - - Nz::TextureSamplerInfo samplerInfo; - samplerInfo.anisotropyLevel = 8; - - Nz::TextureParams texParams; - texParams.renderDevice = device; - texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB; - - Nz::BasicMaterial basicMat(*materialPass); - basicMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams)); + Nz::RenderSystem renderSystem(registry); + + entt::entity viewer = registry.create(); + { + registry.emplace(viewer); + auto& cameraComponent = registry.emplace(viewer, window.GetRenderTarget(), Nz::ProjectionType::Orthographic); + cameraComponent.UpdateRenderMask(1); + cameraComponent.UpdateClearColor(Nz::Color(0.5f, 0.5f, 0.5f)); + } + + std::shared_ptr material = std::make_shared(); + + std::shared_ptr materialPass = std::make_shared(Nz::BasicMaterial::GetSettings()); + material->AddPass("ForwardPass", materialPass); + + Nz::TextureSamplerInfo samplerInfo; + samplerInfo.anisotropyLevel = 8; + + Nz::TextureParams texParams; + texParams.renderDevice = device; + texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB; + + Nz::BasicMaterial basicMat(*materialPass); + basicMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams)); basicMat.SetDiffuseSampler(samplerInfo); for (std::size_t y = 0; y < 10; ++y) - { - for (std::size_t x = 0; x < 10; ++x) - { - entt::entity spriteEntity = registry.create(); - { - std::shared_ptr sprite = std::make_shared(material); - sprite->SetSize({ 32.f, 32.f }); - sprite->SetOrigin({ 16.f, 16.f, 0.f }); - - registry.emplace(spriteEntity).SetPosition(1920 / 2 + x * 36.f, 1080 / 2 + y * 36.f); - registry.emplace(spriteEntity).AttachRenderable(sprite, 1); - auto& rigidBody = registry.emplace(spriteEntity, physSytem.CreateRigidBody(50.f, std::make_shared(Nz::Vector2f(32.f, 32.f)))); - rigidBody.SetElasticity(0.99f); - } - } + { + for (std::size_t x = 0; x < 10; ++x) + { + entt::entity spriteEntity = registry.create(); + { + std::shared_ptr sprite = std::make_shared(material); + sprite->SetSize({ 32.f, 32.f }); + sprite->SetOrigin({ 16.f, 16.f, 0.f }); + + registry.emplace(spriteEntity).SetPosition(1920 / 2 + x * 36.f, 1080 / 2 + y * 36.f); + + registry.emplace(spriteEntity).AttachRenderable(sprite, 1); + auto& rigidBody = registry.emplace(spriteEntity, physSytem.CreateRigidBody(50.f, std::make_shared(Nz::Vector2f(32.f, 32.f)))); + rigidBody.SetElasticity(0.99f); + } + } } entt::entity groundEntity = registry.create(); { std::shared_ptr whiteMaterial = std::make_shared(); - std::shared_ptr materialPass = std::make_shared(Nz::BasicMaterial::GetSettings()); - whiteMaterial->AddPass("ForwardPass", materialPass); + std::shared_ptr materialPass = std::make_shared(Nz::BasicMaterial::GetSettings()); + whiteMaterial->AddPass("ForwardPass", materialPass); std::shared_ptr sprite = std::make_shared(whiteMaterial); sprite->SetSize({ 800.f, 20.f }); sprite->SetOrigin({ 400.f, 10.f, 0.f }); - registry.emplace(groundEntity).SetPosition(1920.f / 2.f, 50.f); + registry.emplace(groundEntity).SetPosition(1920.f / 2.f, 50.f); registry.emplace(groundEntity).AttachRenderable(sprite, 1); auto& rigidBody = registry.emplace(groundEntity, physSytem.CreateRigidBody(0.f, std::make_shared(Nz::Vector2f(800.f, 20.f)))); rigidBody.SetElasticity(0.99f); } - - Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); - Nz::Quaternionf camQuat(camAngles); - - window.EnableEventPolling(true); - - Nz::Clock updateClock; - Nz::Clock secondClock; - unsigned int fps = 0; - - //Nz::Mouse::SetRelativeMouseMode(true); - - float elapsedTime = 0.f; - Nz::UInt64 time = Nz::GetElapsedMicroseconds(); - - Nz::PidController headingController(0.5f, 0.f, 0.05f); - Nz::PidController upController(1.f, 0.f, 0.1f); - - bool showColliders = false; - while (window.IsOpen()) - { - Nz::UInt64 now = Nz::GetElapsedMicroseconds(); - elapsedTime = (now - time) / 1'000'000.f; - time = now; - - Nz::WindowEvent event; - while (window.PollEvent(&event)) - { - switch (event.type) - { - case Nz::WindowEventType::Quit: - window.Close(); - break; - - case Nz::WindowEventType::KeyPressed: - break; - - case Nz::WindowEventType::MouseMoved: - break; - - default: - break; - } - } - - if (updateClock.GetMilliseconds() > 1000 / 60) + + Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); + Nz::Quaternionf camQuat(camAngles); + + window.EnableEventPolling(true); + + Nz::Clock updateClock; + Nz::Clock secondClock; + unsigned int fps = 0; + + //Nz::Mouse::SetRelativeMouseMode(true); + + float elapsedTime = 0.f; + Nz::UInt64 time = Nz::GetElapsedMicroseconds(); + + Nz::PidController headingController(0.5f, 0.f, 0.05f); + Nz::PidController upController(1.f, 0.f, 0.1f); + + bool showColliders = false; + while (window.IsOpen()) + { + Nz::UInt64 now = Nz::GetElapsedMicroseconds(); + elapsedTime = (now - time) / 1'000'000.f; + time = now; + + Nz::WindowEvent event; + while (window.PollEvent(&event)) { - float updateTime = updateClock.Restart() / 1'000'000.f; - + switch (event.type) + { + case Nz::WindowEventType::Quit: + window.Close(); + break; + + case Nz::WindowEventType::KeyPressed: + break; + + case Nz::WindowEventType::MouseMoved: + break; + + default: + break; + } + } + + if (updateClock.GetMilliseconds() > 1000 / 60) + { + float updateTime = updateClock.Restart() / 1'000'000.f; + physSytem.Update(registry, 1000.f / 60.f); } - - Nz::RenderFrame frame = window.AcquireFrame(); - if (!frame) - continue; - - renderSystem.Render(registry, frame); - - frame.Present(); - - fps++; - - if (secondClock.GetMilliseconds() >= 1000) - { - window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS" + " - " + Nz::NumberToString(registry.alive()) + " entities"); - - fps = 0; - - secondClock.Restart(); - } - } - - return EXIT_SUCCESS; -} + + Nz::RenderFrame frame = window.AcquireFrame(); + if (!frame) + continue; + + renderSystem.Render(registry, frame); + + frame.Present(); + + fps++; + + if (secondClock.GetMilliseconds() >= 1000) + { + window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS" + " - " + Nz::NumberToString(registry.alive()) + " entities"); + + fps = 0; + + secondClock.Restart(); + } + } + + return EXIT_SUCCESS; +} diff --git a/examples/PhysicsDemo/main.cpp b/examples/PhysicsDemo/main.cpp index 8a53dadc6..f4eb67459 100644 --- a/examples/PhysicsDemo/main.cpp +++ b/examples/PhysicsDemo/main.cpp @@ -9,9 +9,8 @@ #include #include #include -#include -#include -#include +#include +#include #include #include #include diff --git a/examples/RenderTest/main.cpp b/examples/RenderTest/main.cpp index 7d8efcb87..84ecaef29 100644 --- a/examples/RenderTest/main.cpp +++ b/examples/RenderTest/main.cpp @@ -1,8 +1,11 @@ #include +#include #include #include -#include -#include +#include +#include +#include +#include #include #include #include @@ -11,7 +14,6 @@ NAZARA_REQUEST_DEDICATED_GPU() const char barModuleSource[] = R"( [nzsl_version("1.0")] -[uuid("4BB09DEE-F70A-442E-859F-E8F2F3F8583D")] module Test.Bar; fn dummy() {} @@ -25,7 +27,6 @@ struct Bar const char dataModuleSource[] = R"( [nzsl_version("1.0")] -[uuid("E49DC9AD-469C-462C-9719-A6F012372029")] module Test.Data; import Test.Bar; @@ -133,36 +134,36 @@ int main() return __LINE__; } - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(std::string_view(shaderSource, sizeof(shaderSource))); + nzsl::Ast::ModulePtr shaderModule = nzsl::Parse(std::string_view(shaderSource, sizeof(shaderSource))); if (!shaderModule) { std::cout << "Failed to parse shader module" << std::endl; return __LINE__; } - auto directoryModuleResolver = std::make_shared(); + auto directoryModuleResolver = std::make_shared(); directoryModuleResolver->RegisterModule(std::string_view(barModuleSource)); directoryModuleResolver->RegisterModule(std::string_view(dataModuleSource)); - Nz::ShaderAst::SanitizeVisitor::Options sanitizeOpt; + nzsl::Ast::SanitizeVisitor::Options sanitizeOpt; sanitizeOpt.moduleResolver = directoryModuleResolver; - shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, sanitizeOpt); + shaderModule = nzsl::Ast::Sanitize(*shaderModule, sanitizeOpt); if (!shaderModule) { std::cout << "Failed to compile shader module" << std::endl; return __LINE__; } - Nz::LangWriter langWriter; + nzsl::LangWriter langWriter; std::string output = langWriter.Generate(*shaderModule); std::cout << output << std::endl; - assert(Nz::ShaderAst::Sanitize(*Nz::ShaderLang::Parse(output))); + assert(nzsl::Ast::Sanitize(*nzsl::Parse(output))); - Nz::ShaderWriter::States states; + nzsl::ShaderWriter::States states; states.optimize = true; - auto fragVertShader = device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, *shaderModule, states); + auto fragVertShader = device->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, *shaderModule, states); if (!fragVertShader) { std::cout << "Failed to instantiate shader" << std::endl; @@ -221,7 +222,7 @@ int main() auto& uboBinding = pipelineLayoutInfo.bindings.emplace_back(); uboBinding.setIndex = 0; uboBinding.bindingIndex = 0; - uboBinding.shaderStageFlags = Nz::ShaderStageType::Vertex; + uboBinding.shaderStageFlags = nzsl::ShaderStageType::Vertex; uboBinding.type = Nz::ShaderBindingType::UniformBuffer; std::shared_ptr basePipelineLayout = device->InstantiateRenderPipelineLayout(pipelineLayoutInfo); @@ -229,7 +230,7 @@ int main() auto& textureBinding = pipelineLayoutInfo.bindings.emplace_back(); textureBinding.setIndex = 1; textureBinding.bindingIndex = 0; - textureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment; + textureBinding.shaderStageFlags = nzsl::ShaderStageType::Fragment; textureBinding.type = Nz::ShaderBindingType::Texture; std::shared_ptr renderPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(pipelineLayoutInfo)); diff --git a/examples/Std140Debug/main.cpp b/examples/Std140Debug/main.cpp index 0fb4d7c5b..d582d6c97 100644 --- a/examples/Std140Debug/main.cpp +++ b/examples/Std140Debug/main.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include #include @@ -136,16 +136,16 @@ int main() std::vector computedOffsets; - Nz::FieldOffsets fieldOffsets(Nz::StructLayout::Std140); - computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); - computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); - computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); - computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); - computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); - computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); - computedOffsets.push_back(fieldOffsets.AddField(Nz::StructFieldType::Float2)); - computedOffsets.push_back(fieldOffsets.AddField(Nz::StructFieldType::Float2)); - computedOffsets.push_back(fieldOffsets.AddField(Nz::StructFieldType::Float3)); + nzsl::FieldOffsets fieldOffsets(nzsl::StructLayout::Std140); + computedOffsets.push_back(fieldOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddField(nzsl::StructFieldType::Float2)); + computedOffsets.push_back(fieldOffsets.AddField(nzsl::StructFieldType::Float2)); + computedOffsets.push_back(fieldOffsets.AddField(nzsl::StructFieldType::Float3)); GLint dataSize; diff --git a/examples/WidgetDemo/main.cpp b/examples/WidgetDemo/main.cpp index e8916f5ea..0dd15f1fd 100644 --- a/examples/WidgetDemo/main.cpp +++ b/examples/WidgetDemo/main.cpp @@ -9,9 +9,8 @@ #include #include #include -#include -#include -#include +#include +#include #include #include #include diff --git a/include/Nazara/Audio/AudioDevice.hpp b/include/Nazara/Audio/AudioDevice.hpp index f815f10b9..9caeaf12b 100644 --- a/include/Nazara/Audio/AudioDevice.hpp +++ b/include/Nazara/Audio/AudioDevice.hpp @@ -10,9 +10,10 @@ #include #include #include -#include +#include #include #include +#include #include namespace Nz diff --git a/include/Nazara/Audio/Enums.hpp b/include/Nazara/Audio/Enums.hpp index 70d2977cf..9a680f452 100644 --- a/include/Nazara/Audio/Enums.hpp +++ b/include/Nazara/Audio/Enums.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_AUDIO_ENUMS_HPP #define NAZARA_AUDIO_ENUMS_HPP -#include +#include namespace Nz { diff --git a/include/Nazara/Audio/OpenALDevice.hpp b/include/Nazara/Audio/OpenALDevice.hpp index 1771a3eac..78c4d8966 100644 --- a/include/Nazara/Audio/OpenALDevice.hpp +++ b/include/Nazara/Audio/OpenALDevice.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/Nazara/Core.hpp b/include/Nazara/Core.hpp index 215ecc289..1cc50c19f 100644 --- a/include/Nazara/Core.hpp +++ b/include/Nazara/Core.hpp @@ -32,43 +32,34 @@ #include #include #include -#include #include #include #include -#include #include #include #include #include #include #include -#include #include #include #include #include #include -#include #include #include #include #include #include #include -#include #include -#include #include #include #include #include -#include -#include #include #include #include -#include #include #include #include @@ -81,16 +72,10 @@ #include #include #include -#include -#include -#include -#include #include #include #include #include -#include -#include #include #include #include diff --git a/include/Nazara/Core/AbstractHash.hpp b/include/Nazara/Core/AbstractHash.hpp index 4b548b3d7..aa735d35f 100644 --- a/include/Nazara/Core/AbstractHash.hpp +++ b/include/Nazara/Core/AbstractHash.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_ABSTRACTHASH_HPP #include +#include #include #include diff --git a/include/Nazara/Core/AbstractLogger.hpp b/include/Nazara/Core/AbstractLogger.hpp index 9a7858997..480a786af 100644 --- a/include/Nazara/Core/AbstractLogger.hpp +++ b/include/Nazara/Core/AbstractLogger.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_ABSTRACTLOGGER_HPP #include +#include #include #include diff --git a/include/Nazara/Core/Algorithm.hpp b/include/Nazara/Core/Algorithm.hpp index 490d9e155..3fff66348 100644 --- a/include/Nazara/Core/Algorithm.hpp +++ b/include/Nazara/Core/Algorithm.hpp @@ -11,7 +11,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -22,74 +23,10 @@ namespace Nz { class ByteArray; - template decltype(auto) AccessByOffset(void* basePtr, std::size_t offset); - template decltype(auto) AccessByOffset(const void* basePtr, std::size_t offset); - template constexpr T Align(T offset, T alignment); - template constexpr T AlignPow2(T offset, T alignment); - template decltype(auto) Apply(F&& fn, Tuple&& t); - template decltype(auto) Apply(O& object, F&& fn, Tuple&& t); - template constexpr std::size_t BitCount(); template ByteArray ComputeHash(HashType hash, const T& v); template ByteArray ComputeHash(AbstractHash& hash, const T& v); - template constexpr std::size_t CountOf(T(&name)[N]) noexcept; - template std::size_t CountOf(const T& c); - constexpr UInt32 CRC32(const UInt8* data, std::size_t size) noexcept; - constexpr UInt32 CRC32(const char* str) noexcept; - constexpr UInt32 CRC32(const std::string_view& str) noexcept; - template constexpr std::size_t CountOf(const char(&str)[N]) noexcept; + inline bool HashAppend(AbstractHash* hash, const std::string_view& v); - template void HashCombine(std::size_t& seed, const T& v); - template bool IsPowerOfTwo(T value); - template V& Retrieve(std::unordered_map& map, const K& key); - template const V& Retrieve(const std::unordered_map& map, const K& key); - template T ReverseBits(T integer); - template To SafeCast(From&& value); - templatestd::unique_ptr StaticUniquePointerCast(std::unique_ptr&& ptr); - template constexpr auto UnderlyingCast(T value) -> std::underlying_type_t; - - template - struct AlwaysFalse : std::false_type {}; - - // Helper for std::visit - template struct Overloaded : Ts... - { - using Ts::operator()...; - }; - - template Overloaded(Ts...) -> Overloaded; - - template - struct OverloadResolver - { - template - constexpr auto operator()(R(T::* ptr)(Args...)) const noexcept - { - return ptr; - } - - template - constexpr auto operator()(R(T::* ptr)(Args...) const) const noexcept - { - return ptr; - } - - template - constexpr auto operator()(R(*ptr)(Args...)) const noexcept - { - return ptr; - } - }; - - template constexpr OverloadResolver Overload = {}; - - template - struct PointedType - { - using type = void; //< FIXME: I can't make SFINAE work - }; - - template - using Pointer = T*; template bool Serialize(SerializationContext& context, T&& value); diff --git a/include/Nazara/Core/Algorithm.inl b/include/Nazara/Core/Algorithm.inl index fc9756384..4770da7ae 100644 --- a/include/Nazara/Core/Algorithm.inl +++ b/include/Nazara/Core/Algorithm.inl @@ -2,10 +2,6 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp -// http://stackoverflow.com/questions/687490/c0x-how-do-i-expand-a-tuple-into-variadic-template-function-arguments -// Merci à Ryan "FullMetal Alchemist" Lahfa -// Merci aussi à Freedom de siteduzero.com - #include #include #include @@ -21,193 +17,6 @@ namespace Nz { - namespace Detail - { - // http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html - template - decltype(auto) ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence) - { - return std::forward(fn)(std::get(std::forward(t))...); - } - - template - decltype(auto) ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence) - { - return (object .* std::forward(fn))(std::get(std::forward(t))...); - } - - NAZARA_CORE_API extern const UInt8 BitReverseTable256[256]; - - // https://stackoverflow.com/questions/28675727/using-crc32-algorithm-to-hash-string-at-compile-time - // Generates CRC-32 table, algorithm based from this link: - // http://www.hackersdelight.org/hdcodetxt/crc.c.txt - constexpr auto GenerateCRC32Table(UInt32 polynomial = 0xEDB88320) - { -#ifdef NAZARA_COMPILER_MSVC -// Disable warning: unary minus operator applied to unsigned type, result still unsigned -#pragma warning(push) -#pragma warning(disable: 4146) -#endif - - constexpr UInt32 byteCount = 256; - constexpr UInt32 iterationCount = 8; - - std::array crc32Table{}; - for (UInt32 byte = 0u; byte < byteCount; ++byte) - { - UInt32 crc = byte; - - for (UInt32 i = 0; i < iterationCount; ++i) - { - UInt32 mask = static_cast(-(crc & 1)); - crc = (crc >> 1) ^ (polynomial & mask); - } - - crc32Table[byte] = crc; - } - - return crc32Table; - -#ifdef NAZARA_COMPILER_MSVC -#pragma warning(pop) -#endif - } - - // Stores CRC-32 table and softly validates it. - static constexpr auto crc32Table = GenerateCRC32Table(); - static_assert( - crc32Table.size() == 256 && - crc32Table[1] == 0x77073096 && - crc32Table[255] == 0x2D02EF8D, - "gen_crc32_table generated unexpected result." - ); - } - - /*! - * \ingroup core - * \brief Access a non-typed struct field by offset - * \return A pointer to the field of the asked type - * - * \param basePtr Pointer to the start of the struct - * \param offset Offset to the field (as generated by offsetof or similar) - */ - template - decltype(auto) AccessByOffset(void* basePtr, std::size_t offset) - { - if constexpr (std::is_lvalue_reference_v) - return *reinterpret_cast*>(static_cast(basePtr) + offset); - else if constexpr (std::is_pointer_v) - return reinterpret_cast(static_cast(basePtr) + offset); - else - static_assert(AlwaysFalse(), "AccessByOffset requires a reference or pointer type"); - } - - /*! - * \ingroup core - * \brief Access a non-typed struct field by offset - * \return A pointer to the field of the asked type - * - * \param basePtr Pointer to the start of the struct - * \param offset Offset to the field (as generated by offsetof or similar) - */ - template - decltype(auto) AccessByOffset(const void* basePtr, std::size_t offset) - { - static_assert(std::is_lvalue_reference_v || std::is_pointer_v); - - if constexpr (std::is_lvalue_reference_v) - return *reinterpret_cast*>(static_cast(basePtr) + offset); - else if constexpr (std::is_pointer_v) - return reinterpret_cast(static_cast(basePtr) + offset); - else - static_assert(AlwaysFalse(), "AccessByOffset requires a reference or pointer type"); - } - - /*! - * \ingroup core - * \brief Align an offset - * \return Aligned offset according to alignment - * - * \param offset Base offset - * \param alignment Non-zero alignment - * - * \see AlignPow2 - */ - template - constexpr T Align(T offset, T alignment) - { - assert(alignment > 0); - return ((offset + alignment - 1) / alignment) * alignment; - } - - /*! - * \ingroup core - * \brief Align an offset - * \return Aligned offset according to a power of two alignment - * - * \param offset Base offset - * \param alignment Non-zero power of two alignment - * - * \see Align - * \remark This function is quicker than Align but only works with power of two alignment values - */ - template - constexpr T AlignPow2(T offset, T alignment) - { - assert(alignment > 0); - assert(IsPowerOfTwo(alignment)); - - return (offset + alignment - 1) & ~(alignment - 1); - } - - /*! - * \ingroup core - * \brief Applies the tuple to the function (e.g. calls the function using the tuple content as arguments) - * \return The result of the function - * - * \param fn Function - * \param t Tuple of arguments for the function - * - * \see Apply - */ - template - decltype(auto) Apply(F&& fn, Tuple&& t) - { - constexpr std::size_t tSize = std::tuple_size::type>::value; - - return Detail::ApplyImplFunc(std::forward(fn), std::forward(t), std::make_index_sequence()); - } - - /*! - * \ingroup core - * \brief Applies the tuple to the member function on an object (e.g. calls the member function using the tuple content as arguments) - * \return The result of the member function called - * - * \param object Object of a class - * \param fn Member function - * \param t Tuple of arguments for the member function - * - * \see Apply - */ - template - decltype(auto) Apply(O& object, F&& fn, Tuple&& t) - { - constexpr std::size_t tSize = std::tuple_size::type>::value; - - return Detail::ApplyImplMethod(object, std::forward(fn), std::forward(t), std::make_index_sequence()); - } - - /*! - * \ingroup core - * \brief Returns the number of bits occupied by the type T - * \return Number of bits occupied by the type - */ - template - constexpr std::size_t BitCount() - { - return CHAR_BIT * sizeof(T); - } - /*! * \ingroup core * \brief Computes the hash of a hashable object @@ -249,279 +58,12 @@ namespace Nz return hash.End(); } - // From https://stackoverflow.com/questions/28675727/using-crc32-algorithm-to-hash-string-at-compile-time - constexpr UInt32 CRC32(const UInt8* input, std::size_t size) noexcept - { - UInt32 crc = 0xFFFFFFFFu; - - for (std::size_t i = 0u; i < size; ++i) - crc = Detail::crc32Table[(crc ^ input[i]) & 0xFF] ^ (crc >> 8); - - return ~crc; - } - - constexpr UInt32 CRC32(const char* str) noexcept - { - UInt32 crc = 0xFFFFFFFFu; - - for (std::size_t i = 0u; str[i]; ++i) - crc = Detail::crc32Table[(crc ^ str[i]) & 0xFF] ^ (crc >> 8); - - return ~crc; - } - - constexpr UInt32 CRC32(const std::string_view& str) noexcept - { - UInt32 crc = 0xFFFFFFFFu; - - for (std::size_t i = 0u; i < str.size(); ++i) - crc = Detail::crc32Table[(crc ^ str[i]) & 0xFF] ^ (crc >> 8); - - return ~crc; - } - - template - constexpr UInt32 CRC32(const char (&str)[N]) noexcept - { - UInt32 crc = 0xFFFFFFFFu; - - for (std::size_t i = 0u; i < N - 1; ++i) - crc = Detail::crc32Table[(crc ^ str[i]) & 0xFF] ^ (crc >> 8); - - return ~crc; - } - - /*! - * \ingroup core - * \brief Returns the number of elements in a C-array - * \return The number of elements - * - * \see CountOf - */ - template - constexpr std::size_t CountOf(T(&)[N]) noexcept - { - return N; - } - - /*! - * \ingroup core - * \brief Returns the number of elements in a container - * \return The number of elements - * - * \param c Container with the member function "size()" - * - * \see CountOf - */ - template - std::size_t CountOf(const T& c) - { - return c.size(); - } - inline bool HashAppend(AbstractHash& hash, const std::string_view& v) { hash.Append(reinterpret_cast(v.data()), v.size()); return true; } - /*! - * \ingroup core - * \brief Combines two hash in one - * - * \param seed First value that will be modified (expected to be 64bits) - * \param v Second value to hash - */ - // Algorithm from CityHash by Google - // http://stackoverflow.com/questions/8513911/how-to-create-a-good-hash-combine-with-64-bit-output-inspired-by-boosthash-co - template - void HashCombine(std::size_t& seed, const T& v) - { - const UInt64 kMul = 0x9ddfea08eb382d69ULL; - - std::hash hasher; - UInt64 a = (hasher(v) ^ seed) * kMul; - a ^= (a >> 47); - - UInt64 b = (seed ^ a) * kMul; - b ^= (b >> 47); - - seed = static_cast(b * kMul); - } - - /*! - * \ingroup core - * \brief Check if a value is a power of two - * \return true if value is a power of two - * - * \param value Non-zero value - */ - template - bool IsPowerOfTwo(T value) - { - assert(value != 0); - return (value & (value - 1)) == 0; - } - - /*! - * \ingroup core - * \brief Helper function to retrieve a key in a map which has to exist - * \return Value associated with key - * - * \param map Map - * \param key Key, has to exist in map - */ - template - V& Retrieve(std::unordered_map& map, const K& key) - { - auto it = map.find(key); - assert(it != map.end()); - return it->second; - } - - /*! - * \ingroup core - * \brief Helper function to retrieve a key in a map which has to exist - * \return Value associated with key - * - * \param map Map - * \param key Key, has to exist in map - */ - template - const V& Retrieve(const std::unordered_map& map, const K& key) - { - auto it = map.find(key); - assert(it != map.end()); - return it->second; - } - - /*! - * \ingroup core - * \brief Reverse the bit order of the integer - * \return integer with reversed bits - * - * \param integer Integer whose bits are to be reversed - */ - template - T ReverseBits(T integer) - { - T reversed = 0; - for (std::size_t i = 0; i < sizeof(T); ++i) - reversed |= T(Detail::BitReverseTable256[(integer >> i * 8) & 0xFF]) << (sizeof(T) * 8 - (i + 1) * 8); - - return reversed; - } - - template - To SafeCast(From&& value) - { -#ifdef NAZARA_COMPILER_MSVC - // Disable unreachable code warnings - #pragma warning(push) - #pragma warning(disable: 4702) -#endif - -#if defined(NAZARA_DEBUG) && !defined(NDEBUG) - - if constexpr (std::is_integral_v) - { - if constexpr (std::is_enum_v) - { - return SafeCast(static_cast>(value)); - } - else if constexpr (std::is_floating_point_v) - { - assert(std::floor(value) == value); - - assert(value <= static_cast(std::numeric_limits::max())); - assert(value >= static_cast(std::numeric_limits::lowest())); - } - else if constexpr (std::is_integral_v) - { - // Type capable of storing the biggest value between the two types - using MaxValueType = std::conditional_t<(sizeof(From) > sizeof(To) || (sizeof(From) == sizeof(To) && std::is_signed_v)), From, To>; - // Type capable of storing the smallest value between the two types - using MinValueType = std::conditional_t<(sizeof(From) > sizeof(To) || (sizeof(From) == sizeof(To) && std::is_signed_v)), From, To>; - - if constexpr (!std::is_signed_v) - assert(value >= 0); - - assert(static_cast(value) <= static_cast(std::numeric_limits::max())); - assert(static_cast(value) >= static_cast(std::numeric_limits::lowest())); - } - } - else if constexpr (std::is_enum_v) - { - return static_cast(SafeCast>(value)); - } - else if constexpr (std::is_floating_point_v) - { - if constexpr (std::is_floating_point_v) - { - // Type capable of storing the biggest value between the two types - using MaxValueType = std::conditional_t<(sizeof(From) > sizeof(To)), From, To>; - // Type capable of storing the smallest value between the two types - using MinValueType = std::conditional_t<(sizeof(From) > sizeof(To)), From, To>; - - assert(static_cast(value) <= static_cast(std::numeric_limits::max())); - assert(static_cast(value) >= static_cast(std::numeric_limits::lowest())); - } - } - else if constexpr (std::is_reference_v) - { - if constexpr (std::is_reference_v) - { - using BaseFromType = std::remove_reference_t>; - using BaseToType = std::remove_reference_t>; - - if constexpr (!std::is_same_v && std::is_base_of_v && std::is_polymorphic_v) - { - using ToPtr = std::add_pointer_t>; - assert(dynamic_cast(&value) != nullptr); - } - } - } - else if constexpr (std::is_pointer_v) - { - if constexpr (std::is_pointer_v) - { - using BaseFromType = std::remove_pointer_t>; - using BaseToType = std::remove_pointer_t>; - - if constexpr (!std::is_same_v && std::is_base_of_v && std::is_polymorphic_v) - { - assert(dynamic_cast(value) != nullptr); - } - } - } - -#endif - - return static_cast(value); - -#ifdef NAZARA_COMPILER_MSVC - #pragma warning(pop) -#endif - } - - template - std::unique_ptr StaticUniquePointerCast(std::unique_ptr&& ptr) - { - return std::unique_ptr(SafeCast(ptr.release())); - } - - template - constexpr auto UnderlyingCast(T value) -> std::underlying_type_t - { - return static_cast>(value); - } - - template struct PointedType { using type = T; }; - template struct PointedType { using type = T; }; - template struct PointedType { using type = T; }; - template struct PointedType { using type = T; }; - - template bool Serialize(SerializationContext& context, T&& value) { diff --git a/include/Nazara/Core/Bitset.hpp b/include/Nazara/Core/Bitset.hpp deleted file mode 100644 index 1244ed252..000000000 --- a/include/Nazara/Core/Bitset.hpp +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_BITSET_HPP -#define NAZARA_CORE_BITSET_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class AbstractHash; - - template> - class Bitset - { - static_assert(std::is_integral::value && std::is_unsigned::value, "Block must be a unsigned integral type"); - - public: - class Bit; - using PointerSequence = std::pair; //< Start pointer, bit offset - - Bitset(); - explicit Bitset(std::size_t bitCount, bool val); - explicit Bitset(const char* bits); - Bitset(const char* bits, std::size_t bitCount); - Bitset(const Bitset& bitset) = default; - explicit Bitset(const std::string_view& bits); - explicit Bitset(const std::string& bits); - template Bitset(T value); - Bitset(Bitset&& bitset) noexcept = default; - ~Bitset() noexcept = default; - - template void AppendBits(T bits, std::size_t bitCount); - - void Clear() noexcept; - std::size_t Count() const; - void Flip(); - - std::size_t FindFirst() const; - std::size_t FindNext(std::size_t bit) const; - - Block GetBlock(std::size_t i) const; - std::size_t GetBlockCount() const; - std::size_t GetCapacity() const; - std::size_t GetSize() const; - - void PerformsAND(const Bitset& a, const Bitset& b); - void PerformsNOT(const Bitset& a); - void PerformsOR(const Bitset& a, const Bitset& b); - void PerformsXOR(const Bitset& a, const Bitset& b); - - bool Intersects(const Bitset& bitset) const; - - void Reserve(std::size_t bitCount); - void Resize(std::size_t bitCount, bool defaultVal = false); - - void Reset(); - void Reset(std::size_t bit); - - void Reverse(); - - void Set(bool val = true); - void Set(std::size_t bit, bool val = true); - void SetBlock(std::size_t i, Block block); - - void ShiftLeft(std::size_t pos); - void ShiftRight(std::size_t pos); - - void Swap(Bitset& bitset) noexcept; - - bool Test(std::size_t bit) const; - bool TestAll() const; - bool TestAny() const; - bool TestNone() const; - - template T To() const; - std::string ToString() const; - - void UnboundedReset(std::size_t bit); - void UnboundedSet(std::size_t bit, bool val = true); - bool UnboundedTest(std::size_t bit) const; - - PointerSequence Write(const void* ptr, std::size_t bitCount); - PointerSequence Write(const PointerSequence& sequence, std::size_t bitCount); - - Bit operator[](std::size_t index); - bool operator[](std::size_t index) const; - - Bitset operator~() const; - - Bitset& operator=(const Bitset& bitset) = default; - Bitset& operator=(const std::string_view& bits); - template Bitset& operator=(T value); - Bitset& operator=(Bitset&& bitset) noexcept = default; - - Bitset operator<<(std::size_t pos) const; - Bitset& operator<<=(std::size_t pos); - - Bitset operator>>(std::size_t pos) const; - Bitset& operator>>=(std::size_t pos); - - Bitset& operator&=(const Bitset& bitset); - Bitset& operator|=(const Bitset& bitset); - Bitset& operator^=(const Bitset& bitset); - - static constexpr Block fullBitMask = std::numeric_limits::max(); - static constexpr std::size_t bitsPerBlock = BitCount(); - static constexpr std::size_t npos = std::numeric_limits::max(); - - static Bitset FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence = nullptr); - - private: - std::size_t FindFirstFrom(std::size_t blockIndex) const; - Block GetLastBlockMask() const; - void ResetExtraBits(); - - static std::size_t ComputeBlockCount(std::size_t bitCount); - static std::size_t GetBitIndex(std::size_t bit); - static std::size_t GetBlockIndex(std::size_t bit); - - std::vector m_blocks; - std::size_t m_bitCount; - }; - - template - class Bitset::Bit - { - friend Bitset; - - public: - Bit(const Bit& bit) = default; - - Bit& Flip(); - Bit& Reset(); - Bit& Set(bool val = true); - bool Test() const; - - template - void* operator&() const; - - explicit operator bool() const; - Bit& operator=(bool val); - Bit& operator=(const Bit& bit); - - Bit& operator|=(bool val); - Bit& operator&=(bool val); - Bit& operator^=(bool val); - Bit& operator-=(bool val); - - private: - Bit(Block& block, Block mask) : - m_block(block), - m_mask(mask) - { - } - - Block& m_block; - Block m_mask; - }; - - template - std::ostream& operator<<(std::ostream& out, const Bitset& bitset); - - template - bool operator==(const Bitset& lhs, const Nz::Bitset& rhs); - - template - bool operator!=(const Bitset& lhs, const Nz::Bitset& rhs); - - template - bool operator<(const Bitset& lhs, const Nz::Bitset& rhs); - - template - bool operator<=(const Bitset& lhs, const Nz::Bitset& rhs); - - template - bool operator>(const Bitset& lhs, const Nz::Bitset& rhs); - - template - bool operator>=(const Bitset& lhs, const Nz::Bitset& rhs); - - template - Bitset operator&(const Bitset& lhs, const Bitset& rhs); - - template - Bitset operator|(const Bitset& lhs, const Bitset& rhs); - - template - Bitset operator^(const Bitset& lhs, const Bitset& rhs); -} - -namespace std -{ - template - void swap(Nz::Bitset& lhs, Nz::Bitset& rhs) noexcept; -} - -#include - -#endif // NAZARA_CORE_BITSET_HPP diff --git a/include/Nazara/Core/Bitset.inl b/include/Nazara/Core/Bitset.inl deleted file mode 100644 index 9df60ff2f..000000000 --- a/include/Nazara/Core/Bitset.inl +++ /dev/null @@ -1,1671 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include - -#ifdef NAZARA_COMPILER_MSVC - // Bits tricks require us to disable some warnings under VS - #pragma warning(push) - #pragma warning(disable: 4146) - #pragma warning(disable: 4804) -#endif - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Bitset - * \brief Core class that represents a set of bits - * - * This class meets the requirements of Container, AllocatorAwareContainer, SequenceContainer - */ - - /*! - * \brief Constructs a Bitset object by default - */ - - template - Bitset::Bitset() : - m_bitCount(0) - { - } - - /*! - * \brief Constructs a Bitset object of bitCount bits to value val - * - * \param bitCount Number of bits - * \param val Value of those bits, by default false - */ - - template - Bitset::Bitset(std::size_t bitCount, bool val) : - Bitset() - { - Resize(bitCount, val); - } - - /*! - * \brief Constructs a Bitset object from the contents initialized with a copy of the null-terminated character string pointed to by bits - * - * \param bits Null-terminated character string containing only '0' and '1' - * - * \remark The length of the string is determined by the first null character, if there is no null character, the behaviour is undefined - */ - - template - Bitset::Bitset(const char* bits) : - Bitset(bits, std::strlen(bits)) - { - } - - /*! - * \brief Constructs a Bitset object from the contents initialized with a copy of the character string pointed to by bits takings the bitCount first characters - * - * \param bits Character string containing only '0' and '1' - * \param bitCount Number of characters to take into consideration - * - * \remark If the length of the string is inferior to the bitCount, the behaviour is undefined - */ - - template - Bitset::Bitset(const char* bits, std::size_t bitCount) : - m_blocks(ComputeBlockCount(bitCount), 0U), - m_bitCount(bitCount) - { - for (std::size_t i = 0; i < bitCount; ++i) - { - switch (*bits++) - { - case '1': - // We adapt the index (inversion in comparison to the string) - Set(m_bitCount - i - 1, true); - break; - - case '0': - // Each block is zero-initialised, nothing to do - break; - - default: - NazaraAssert(false, "Unexpected char (neither 1 nor 0)"); - break; - } - } - } - - /*! - * \brief Constructs a Bitset object from a std::string_view - * - * \param bits String containing only '0' and '1' - */ - template - Bitset::Bitset(const std::string_view& bits) : - Bitset(bits.data(), bits.size()) - { - } - - /*! - * \brief Constructs a Bitset object from a std::string - * - * \param bits String containing only '0' and '1' - */ - template - Bitset::Bitset(const std::string& bits) : - Bitset(bits.data(), bits.size()) - { - } - - /*! - * \brief Constructs a Bitset copying an unsigned integral number - * - * \param value Number to be used as a base - */ - template - template - Bitset::Bitset(T value) : - Bitset() - { - if constexpr (sizeof(T) <= sizeof(Block)) - { - m_bitCount = BitCount(); - m_blocks.push_back(static_cast(value)); - } - else - { - // Note: I was kinda tired when I wrote this, there's probably a much easier method than checking bits to write bits - for (std::size_t bitPos = 0; bitPos < BitCount(); bitPos++) - { - if (value & (T(1U) << bitPos)) - UnboundedSet(bitPos, true); - } - } - } - - /*! - * \brief Appends bits to the bitset - * - * This function extends the bitset with bits extracted from an integer value - * - * \param bits An integer value from where bits will be extracted - * \param bitCount Number of bits to extract from the value - * - * \remark This function does not require bitCount to be lower or equal to the number of bits of T, thus - * reading 32 bits from a UInt8 will work (by extracting the first 8 bits values and appending 24 zeros afterneath). - * - * \see AppendBits - * \see Read - */ - template - template - void Bitset::AppendBits(T bits, std::size_t bitCount) - { - std::size_t bitShift = m_bitCount % bitsPerBlock; - m_bitCount += bitCount; - - if (bitShift != 0) - { - std::size_t remainingBits = bitsPerBlock - bitShift; - m_blocks.back() |= Block(bits) << bitShift; - bits >>= bitsPerBlock - bitShift; - - bitCount -= std::min(remainingBits, bitCount); - } - - if (bitCount > 0) - { - std::size_t blockCount = ComputeBlockCount(bitCount); - for (std::size_t block = 0; block < blockCount - 1; ++block) - { - m_blocks.push_back(static_cast(bits)); - bits = (BitCount() < BitCount()) ? bits >> BitCount() : 0U; - bitCount -= BitCount(); - } - - // For the last iteration, mask out the bits we don't want - std::size_t remainingBits = bitCount; - - bits &= ((Block(1U) << remainingBits) - 1U); - m_blocks.push_back(static_cast(bits)); - } - } - - /*! - * \brief Clears the content of the bitset - * - * This function clears the bitset content, resetting its bit and block count at zero. - * - * \remark This does not changes the bits values to zero but empties the bitset, to reset the bits use the Reset() function - * \remark This call does not changes the bitset capacity - * - * \see Reset() - */ - template - void Bitset::Clear() noexcept - { - m_bitCount = 0; - m_blocks.clear(); - } - - /*! - * \brief Counts the number of bits set to 1 - * - * \return Number of bits set to 1 - */ - template - std::size_t Bitset::Count() const - { - if (m_blocks.empty()) - return 0; - - std::size_t count = 0; - for (std::size_t i = 0; i < m_blocks.size(); ++i) - count += CountBits(m_blocks[i]); - - return count; - } - - /*! - * \brief Flips each bit of the bitset - * - * This function flips every bit of the bitset, which means every '1' turns into a '0' and conversely. - */ - template - void Bitset::Flip() - { - for (Block& block : m_blocks) - block ^= fullBitMask; - - ResetExtraBits(); - } - - /*! - * \brief Finds the first bit set to one in the bitset - * - * \return The 0-based index of the first bit enabled - */ - template - std::size_t Bitset::FindFirst() const - { - return FindFirstFrom(0); - } - - /*! - * \brief Finds the next enabled in the bitset - * - * \param bit Index of the last bit found, which will not be treated by this function - * - * \return Index of the next enabled bit or npos if all the following bits are disabled - * - * \remark This function is typically used in for-loops to iterate on bits - */ - template - std::size_t Bitset::FindNext(std::size_t bit) const - { - NazaraAssert(bit < m_bitCount, "Bit index out of range"); - - if (++bit >= m_bitCount) - return npos; - - // The block of the bit and its index - std::size_t blockIndex = GetBlockIndex(bit); - std::size_t bitIndex = GetBitIndex(bit); - - // We get the block - Block block = m_blocks[blockIndex]; - - // We ignore the X first bits - block >>= bitIndex; - - // If the block is not empty, it's good, else we must keep trying with the next block - if (block) - return IntegralLog2Pot(block & -block) + bit; - else - return FindFirstFrom(blockIndex + 1); - } - - /*! - * \brief Gets the ith block - * \return Block in the bitset - * - * \param i Index of the block - * - * \remark Produce a NazaraAssert if i is greather than number of blocks in bitset - */ - - template - Block Bitset::GetBlock(std::size_t i) const - { - NazaraAssert(i < m_blocks.size(), "Block index out of range"); - - return m_blocks[i]; - } - - /*! - * \brief Gets the number of blocks - * \return Number of blocks - */ - - template - std::size_t Bitset::GetBlockCount() const - { - return m_blocks.size(); - } - - /*! - * \brief Gets the capacity of the bitset - * \return Capacity of the bitset - */ - - template - std::size_t Bitset::GetCapacity() const - { - return m_blocks.capacity()*bitsPerBlock; - } - - /*! - * \brief Gets the number of bits - * \return Number of bits - */ - - template - std::size_t Bitset::GetSize() const - { - return m_bitCount; - } - - /*! - * \brief Writes a byte sequence into a bitset - * - * This function extends the bitset with bits read from a byte sequence. - * - * \param ptr A pointer to the start of the byte sequence - * \param bitCount Number of bits to read from the byte sequence - * - * \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times) - * - * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) - * - * \see AppendBits - * \see Read - * \see Write - */ - template - typename Bitset::PointerSequence Bitset::Write(const void* ptr, std::size_t bitCount) - { - return Write(PointerSequence(ptr, 0U), bitCount); - } - - /*! - * \brief Writes a byte sequence into a bitset - * - * This function extends the bitset with bits read from a pointer sequence (made of a pointer and a bit index). - * - * \param sequence A pointer sequence to the start of the byte sequence - * \param bitCount Number of bits to read from the byte sequence - * - * \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times) - * - * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) - * - * \see AppendBits - * \see Read - * \see Write - */ - template - typename Bitset::PointerSequence Bitset::Write(const PointerSequence& sequence, std::size_t bitCount) - { - NazaraAssert(sequence.first, "Invalid pointer sequence"); - NazaraAssert(sequence.second < 8, "Invalid next bit index (must be < 8)"); - - std::size_t totalBitCount = sequence.second + bitCount; - - const UInt8* u8Ptr = static_cast(sequence.first); - const UInt8* endPtr = u8Ptr + ((totalBitCount != 0) ? (totalBitCount - 1) / 8 : 0); - const UInt8* nextPtr = endPtr + ((totalBitCount % 8 != 0) ? 0 : 1); - - // Read the first block apart to apply a mask on the first byte if necessary - if (sequence.second != 0) - { - UInt8 mask = ~((1U << sequence.second) - 1U); - - std::size_t readCount = std::min(bitCount, 8 - sequence.second); - AppendBits(Block(*u8Ptr++ & mask) >> sequence.second, readCount); - bitCount -= readCount; - } - - // And then read the remaining bytes - while (u8Ptr <= endPtr) - { - std::size_t bitToRead = std::min(bitCount, 8); - AppendBits(*u8Ptr++, bitToRead); - bitCount -= bitToRead; - } - - // Returns informations to continue reading - return PointerSequence(nextPtr, totalBitCount % 8); - } - - /*! - * \brief Performs the "AND" operator between two bitsets - * - * \param a First bitset - * \param b Second bitset - * - * \remark The "AND" is performed with all the bits of the smallest bitset and the capacity of this is set to the largest of the two bitsets - */ - - template - void Bitset::PerformsAND(const Bitset& a, const Bitset& b) - { - std::pair minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount()); - - m_blocks.resize(minmax.second); - m_bitCount = std::max(a.GetSize(), b.GetSize()); - - // In case of the "AND", we can stop with the smallest size (because x & 0 = 0) - for (std::size_t i = 0; i < minmax.first; ++i) - m_blocks[i] = a.GetBlock(i) & b.GetBlock(i); - - // And then reset every other block to zero - for (std::size_t i = minmax.first; i < minmax.second; ++i) - m_blocks[i] = 0U; - - ResetExtraBits(); - } - - /*! - * \brief Performs the "NOT" operator of the bitset - * - * \param a Bitset to negate - */ - - template - void Bitset::PerformsNOT(const Bitset& a) - { - m_blocks.resize(a.GetBlockCount()); - m_bitCount = a.GetSize(); - - for (std::size_t i = 0; i < m_blocks.size(); ++i) - m_blocks[i] = ~a.GetBlock(i); - - ResetExtraBits(); - } - - /*! - * \brief Performs the "OR" operator between two bitsets - * - * \param a First bitset - * \param b Second bitset - * - * \remark The "OR" is performed with all the bits of the smallest bitset and the others are copied from the largest and the capacity of this is set to the largest of the two bitsets - */ - - template - void Bitset::PerformsOR(const Bitset& a, const Bitset& b) - { - const Bitset& greater = (a.GetSize() > b.GetSize()) ? a : b; - const Bitset& lesser = (a.GetSize() > b.GetSize()) ? b : a; - - std::size_t maxBlockCount = greater.GetBlockCount(); - std::size_t minBlockCount = lesser.GetBlockCount(); - m_blocks.resize(maxBlockCount); - m_bitCount = greater.GetSize(); - - for (std::size_t i = 0; i < minBlockCount; ++i) - m_blocks[i] = a.GetBlock(i) | b.GetBlock(i); - - for (std::size_t i = minBlockCount; i < maxBlockCount; ++i) - m_blocks[i] = greater.GetBlock(i); // (x | 0 = x) - - ResetExtraBits(); - } - - /*! - * \brief Performs the "XOR" operator between two bitsets - * - * \param a First bitset - * \param b Second bitset - * - * \remark The "XOR" is performed with all the bits of the smallest bitset and the others are copied from the largest and the capacity of this is set to the largest of the two bitsets - */ - - template - void Bitset::PerformsXOR(const Bitset& a, const Bitset& b) - { - const Bitset& greater = (a.GetSize() > b.GetSize()) ? a : b; - const Bitset& lesser = (a.GetSize() > b.GetSize()) ? b : a; - - std::size_t maxBlockCount = greater.GetBlockCount(); - std::size_t minBlockCount = lesser.GetBlockCount(); - m_blocks.resize(maxBlockCount); - m_bitCount = greater.GetSize(); - - for (std::size_t i = 0; i < minBlockCount; ++i) - m_blocks[i] = a.GetBlock(i) ^ b.GetBlock(i); - - for (std::size_t i = minBlockCount; i < maxBlockCount; ++i) - m_blocks[i] = greater.GetBlock(i); // (x ^ 0 = x) - - ResetExtraBits(); - } - - /*! - * \brief Checks if bitsets have one block in common - * - * \param bitset Bitset to test - */ - - template - bool Bitset::Intersects(const Bitset& bitset) const - { - // We only test the blocks in common - std::size_t sharedBlocks = std::min(GetBlockCount(), bitset.GetBlockCount()); - for (std::size_t i = 0; i < sharedBlocks; ++i) - { - Block a = GetBlock(i); - Block b = bitset.GetBlock(i); - if (a & b) - return true; - } - - return false; - } - - /*! - * \brief Reserves enough blocks to contain bitCount bits - * - * \param bitCount Number of bits to reserve - */ - - template - void Bitset::Reserve(std::size_t bitCount) - { - m_blocks.reserve(ComputeBlockCount(bitCount)); - } - - /*! - * \brief Resizes the bitset to the size of bitCount - * - * \param bitCount Number of bits to resize - * \param defaultVal Value of the bits if new size is greather than the old one - */ - - template - void Bitset::Resize(std::size_t bitCount, bool defaultVal) - { - // We begin with changing the size of container, with the correct value of initialisation - std::size_t lastBlockIndex = m_blocks.size() - 1; - m_blocks.resize(ComputeBlockCount(bitCount), (defaultVal) ? fullBitMask : 0U); - - std::size_t remainingBits = GetBitIndex(m_bitCount); - if (bitCount > m_bitCount && remainingBits > 0 && defaultVal) - // Initialisation of unused bits in the last block before the size change - m_blocks[lastBlockIndex] |= fullBitMask << remainingBits; - - m_bitCount = bitCount; - ResetExtraBits(); - } - - /*! - * \brief Reset all bits value to zero - */ - template - void Bitset::Reset() - { - Set(false); - } - - /*! - * \brief Resets the bit at the index - * - * \param bit Index of the bit - * - * \see UnboundReset - */ - - template - void Bitset::Reset(std::size_t bit) - { - Set(bit, false); - } - - /*! - * \brief Reverse the order of bits in a bitset - * - * Reverse the order of bits in the bitset (first bit swap with the last one, etc.) - */ - template - void Bitset::Reverse() - { - if (m_bitCount == 0) - return; - - std::size_t i = 0; - std::size_t j = m_bitCount - 1; - - while (i < j) - { - bool bit1 = Test(i); - bool bit2 = Test(j); - - Set(i++, bit2); - Set(j--, bit1); - } - } - - /*! - * \brief Sets the bitset to val - * - * \param val Value of the bits - */ - - template - void Bitset::Set(bool val) - { - std::fill(m_blocks.begin(), m_blocks.end(), (val) ? fullBitMask : Block(0U)); - if (val) - ResetExtraBits(); - } - - /*! - * \brief Sets the bit at the index - * - * \param bit Index of the bit - * \param val Value of the bit - * - * \remark Produce a NazaraAssert if bit is greather than number of bits in bitset - * - * \see UnboundSet - */ - - template - void Bitset::Set(std::size_t bit, bool val) - { - NazaraAssert(bit < m_bitCount, "Bit index out of range"); - - Block& block = m_blocks[GetBlockIndex(bit)]; - Block mask = Block(1U) << GetBitIndex(bit); - - // Activation of the bit without branching - // https://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching - block = (block & ~mask) | (-static_cast(val) & mask); - } - - /*! - * \brief Set the ith block - * - * \param i Index of the block - * \param block Block to set - * - * \remark Produce a NazaraAssert if i is greather than number of blocks in bitset - */ - template - void Bitset::SetBlock(std::size_t i, Block block) - { - NazaraAssert(i < m_blocks.size(), "Block index out of range"); - - m_blocks[i] = block; - if (i == m_blocks.size()-1) - ResetExtraBits(); - } - - /*! - * \brief Shift all the bits toward the left - * - * \param pos Bit shifting to be applied - * - * \remark This does not changes the size of the bitset. - * - * \see operator<<= - */ - template - void Bitset::ShiftLeft(std::size_t pos) - { - if (pos == 0) - return; - - if (pos >= m_bitCount) - { - Reset(); - return; - } - - std::size_t blockShift = pos / bitsPerBlock; - std::size_t remainder = pos % bitsPerBlock; - if (remainder != 0) - { - std::size_t lastIndex = m_blocks.size() - 1; - std::size_t remaining = bitsPerBlock - remainder; - - for (std::size_t i = lastIndex - blockShift; i > 0; --i) - m_blocks[i + blockShift] = (m_blocks[i] << remainder) | (m_blocks[i - 1] >> remaining); - - m_blocks[blockShift] = m_blocks[0] << remainder; - - std::fill_n(m_blocks.begin(), blockShift, Block(0)); - } - else - { - for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it) - { - if (static_cast(std::distance(m_blocks.rbegin(), it) + blockShift) < m_blocks.size()) - { - auto shiftedIt = it; - std::advance(shiftedIt, blockShift); - - *it = *shiftedIt; - } - else - *it = 0U; - } - } - - ResetExtraBits(); - } - - /*! - * \brief Shift all the bits toward the right - * - * \param pos Bit shifting to be applied - * - * \remark This does not changes the size of the bitset. - * - * \see operator>>= - */ - template - void Bitset::ShiftRight(std::size_t pos) - { - if (pos == 0) - return; - - if (pos >= m_bitCount) - { - Reset(); - return; - } - - std::size_t blockShift = pos / bitsPerBlock; - std::size_t remainder = pos % bitsPerBlock; - if (remainder != 0) - { - std::size_t lastIndex = m_blocks.size() - 1; - std::size_t remaining = bitsPerBlock - remainder; - - for (std::size_t i = blockShift; i < lastIndex; ++i) - m_blocks[i - blockShift] = (m_blocks[i] >> remainder) | (m_blocks[i + 1] << remaining); - - m_blocks[lastIndex - blockShift] = m_blocks[lastIndex] >> remainder; - - std::fill_n(m_blocks.begin() + (m_blocks.size() - blockShift), blockShift, Block(0)); - } - else - { - for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) - { - if (static_cast(std::distance(m_blocks.begin(), it) + blockShift) < m_blocks.size()) - { - auto shiftedIt = it; - std::advance(shiftedIt, blockShift); - - *it = *shiftedIt; - } - else - *it = 0U; - } - } - - ResetExtraBits(); - } - - /*! - * \brief Swaps the two bitsets - * - * \param bitset Other bitset to swap - */ - template - void Bitset::Swap(Bitset& bitset) noexcept - { - std::swap(m_bitCount, bitset.m_bitCount); - std::swap(m_blocks, bitset.m_blocks); - } - - /*! - * \brief Tests the ith bit - * \return true if bit is set - * - * \param bit Index of the bit - * - * \remark Produce a NazaraAssert if bit is greather than number of bits in bitset - * - * \see UnboundTest - */ - - template - bool Bitset::Test(std::size_t bit) const - { - NazaraAssert(bit < m_bitCount, "Bit index out of range"); - - return (m_blocks[GetBlockIndex(bit)] & (Block(1U) << GetBitIndex(bit))) != 0; - } - - /*! - * \brief Tests each block - * \return true if each block is set - */ - - template - bool Bitset::TestAll() const - { - // Special case for the last block - Block lastBlockMask = GetLastBlockMask(); - - for (std::size_t i = 0; i < m_blocks.size(); ++i) - { - Block mask = (i == m_blocks.size() - 1) ? lastBlockMask : fullBitMask; - if (m_blocks[i] != mask) // The extra bits are set to zero, thus we can't test without proceeding with a mask - return false; - } - - return true; - } - - /*! - * \brief Tests if one bit is set - * \return true if one bit is set - */ - - template - bool Bitset::TestAny() const - { - if (m_blocks.empty()) - return false; - - for (std::size_t i = 0; i < m_blocks.size(); ++i) - { - if (m_blocks[i]) - return true; - } - - return false; - } - - /*! - * \brief Tests if one bit is not set - * \return true if one bit is not set - */ - - template - bool Bitset::TestNone() const - { - return !TestAny(); - } - - /*! - * \brief Converts the bitset to template type - * \return The conversion of the bitset - * - * \remark Produce a NazaraAssert if the template type can not hold the number of bits - */ - - template - template - T Bitset::To() const - { - static_assert(std::is_integral() && std::is_unsigned(), "T must be a unsigned integral type"); - - NazaraAssert(m_bitCount <= BitCount(), "Bit count cannot be greater than T bit count"); - - T value = 0; - for (std::size_t i = 0; i < m_blocks.size(); ++i) - value |= static_cast(m_blocks[i]) << i*bitsPerBlock; - - return value; - } - - /*! - * \brief Gives a string representation - * \return A string representation of the object with only '0' and '1' - */ - - template - std::string Bitset::ToString() const - { - std::string str(m_bitCount, '0'); - - for (std::size_t i = 0; i < m_bitCount; ++i) - { - if (Test(i)) - str[m_bitCount - i - 1] = '1'; // Inversion de l'indice - } - - return str; - } - - /*! - * \brief Resets the bit at the index - * - * \param bit Index of the bit - * - * \remark if bit is greather than the number of bits, the bitset is enlarged and the added bits are set to false - * - * \see Reset - */ - - template - void Bitset::UnboundedReset(std::size_t bit) - { - UnboundedSet(bit, false); - } - - /*! - * \brief Sets the bit at the index - * - * \param bit Index of the bit - * \param val Value of the bit - * - * \remark if bit is greater than the number of bits, the bitset is enlarged and the added bits are set to false and the one at bit is set to val - * - * \see Set - */ - - template - void Bitset::UnboundedSet(std::size_t bit, bool val) - { - if (bit < m_bitCount) - Set(bit, val); - else if (val) - { - // On élargit le bitset seulement s'il y a un bit à marquer - Resize(bit + 1, false); - Set(bit, true); - } - } - - /*! - * \brief Tests the ith bit - * \return true if bit is set - * - * \param bit Index of the bit - * - * \see Test - */ - - template - bool Bitset::UnboundedTest(std::size_t bit) const - { - if (bit < m_bitCount) - return Test(bit); - else - return false; - } - - /*! - * \brief Gets the ith bit - * \return bit in ith position - */ - - template - typename Bitset::Bit Bitset::operator[](std::size_t index) - { - return Bit(m_blocks[GetBlockIndex(index)], Block(1U) << GetBitIndex(index)); - } - - /*! - * \brief Gets the ith bit - * \return bit in ith position - */ - - template - bool Bitset::operator[](std::size_t index) const - { - return Test(index); - } - - /*! - * \brief Negates the bitset - * \return A new bitset which is the "NOT" of this bitset - */ - - template - Bitset Bitset::operator~() const - { - Bitset bitset; - bitset.PerformsNOT(*this); - - return bitset; - } - - /*! - * \brief Sets this bitset from a std::string - * \return A reference to this - * - * \param bits String containing only '0' and '1' - */ - - template - Bitset& Bitset::operator=(const std::string_view& bits) - { - Bitset bitset(bits); - std::swap(*this, bitset); - - return *this; - } - - /*! - * \brief Copies the internal representation of an unsigned integer - * \return A reference to this - * - * \param value Unsigned number which will be used as a source - */ - template - template - Bitset& Bitset::operator=(T value) - { - Bitset bitset(value); - std::swap(*this, bitset); - - return *this; - } - - /*! - * \brief Shift all the bits toward the left - * - * \param pos Bit shifting to be applied - * - * \return A copies of the bitset with shifted bits - * - * \remark This does not changes the size of the bitset. - * - * \see ShiftLeft - */ - template - Bitset Bitset::operator<<(std::size_t pos) const - { - Bitset bitset(*this); - return bitset <<= pos; - } - - /*! - * \brief Shift all the bits toward the left - * - * \param pos Bit shifting to be applied - * - * \return A reference to this - * - * \remark This does not changes the size of the bitset. - * - * \see ShiftLeft - */ - template - Bitset& Bitset::operator<<=(std::size_t pos) - { - ShiftLeft(pos); - - return *this; - } - - /*! - * \brief Shift all the bits toward the right - * - * \param pos Bit shifting to be applied - * - * \return A copies of the bitset with shifted bits - * - * \remark This does not changes the size of the bitset. - * - * \see ShiftRight - */ - template - Bitset Bitset::operator>>(std::size_t pos) const - { - Bitset bitset(*this); - return bitset >>= pos; - } - - /*! - * \brief Shift all the bits toward the right - * - * \param pos Bit shifting to be applied - * - * \return A reference to this - * - * \remark This does not changes the size of the bitset. - * - * \see ShiftRight - */ - template - Bitset& Bitset::operator>>=(std::size_t pos) - { - ShiftRight(pos); - - return *this; - } - - /*! - * \brief Performs an "AND" with another bitset - * \return A reference to this - * - * \param bitset Other bitset - */ - - template - Bitset& Bitset::operator&=(const Bitset& bitset) - { - PerformsAND(*this, bitset); - - return *this; - } - - /*! - * \brief Performs an "OR" with another bitset - * \return A reference to this - * - * \param bitset Other bitset - */ - - template - Bitset& Bitset::operator|=(const Bitset& bitset) - { - PerformsOR(*this, bitset); - - return *this; - } - - /*! - * \brief Performs an "XOR" with another bitset - * \return A reference to this - * - * \param bitset Other bitset - */ - - template - Bitset& Bitset::operator^=(const Bitset& bitset) - { - PerformsXOR(*this, bitset); - - return *this; - } - - /*! - * \brief Builds a bitset from a byte sequence - * - * This function builds a bitset using a byte sequence by reading bitCount bits from it - * - * \param ptr A pointer to the start of the byte sequence - * \param bitCount Number of bits to read from the byte sequence - * \param sequence Optional data to pass to a next call to Read - * - * \return The constructed bitset - * - * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) - * - * \see AppendBits - * \see Read - */ - template - Bitset Bitset::FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence) - { - Bitset bitset; - - if (sequence) - *sequence = bitset.Write(ptr, bitCount); - else - bitset.Write(ptr, bitCount); - - return bitset; - } - - /*! - * \brief Finds the position of the first bit set to true after the blockIndex - * \return The position of the bit - * - * \param blockIndex Index of the block - */ - template - std::size_t Bitset::FindFirstFrom(std::size_t blockIndex) const - { - if (blockIndex >= m_blocks.size()) - return npos; - - // We are looking for the first non-null block - std::size_t i = blockIndex; - for (; i < m_blocks.size(); ++i) - { - if (m_blocks[i]) - break; - } - - // Do we have a non-null block ? - if (i == m_blocks.size()) - return npos; - - Block block = m_blocks[i]; - - // Compute the position of LSB in the block (and adjustment of the position) - return IntegralLog2Pot(block & -block) + i*bitsPerBlock; - } - - /*! - * \brief Gets the mask associated to the last block - * \return Block which represents the mask - */ - - template - Block Bitset::GetLastBlockMask() const - { - std::size_t bitIndex = GetBitIndex(m_bitCount); - return (bitIndex) ? (Block(1U) << bitIndex) - 1U : fullBitMask; - } - - /*! - * \brief Sets to '0' the last bits unassigned in the last block - */ - - template - void Bitset::ResetExtraBits() - { - if (!m_blocks.empty()) - m_blocks.back() &= GetLastBlockMask(); - } - - /*! - * \brief Computes the block count with the index of the bit - * \return Number of the blocks to contain the bit - */ - - template - std::size_t Bitset::ComputeBlockCount(std::size_t bitCount) - { - return GetBlockIndex(bitCount) + ((GetBitIndex(bitCount) != 0U) ? 1U : 0U); - } - - /*! - * \brief Computes the bit position in the block - * \return Index of the bit in the block - */ - - template - std::size_t Bitset::GetBitIndex(std::size_t bit) - { - return bit & (bitsPerBlock - 1U); // bit % bitsPerBlock - } - - /*! - * \brief Computes the block index with the index of the bit - * \return Index of the block containing the bit - */ - - template - std::size_t Bitset::GetBlockIndex(std::size_t bit) - { - return bit / bitsPerBlock; - } - - /*! - * \brief Flips the bit - * \return A reference to this - */ - - template - typename Bitset::Bit& Bitset::Bit::Flip() - { - m_block ^= m_mask; - - return *this; - } - - /*! - * \brief Resets the bit - * \return A reference to this - */ - - template - typename Bitset::Bit& Bitset::Bit::Reset() - { - return Set(false); - } - - /*! - * \brief Sets the bit to a value - * \return A reference to this - * - * \param val Value of the bit - */ - - template - typename Bitset::Bit& Bitset::Bit::Set(bool val) - { - // https://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching - m_block = (m_block & ~m_mask) | (-val & m_mask); - - return *this; - } - - /*! - * \brief Tests the bit - * \return A reference to this - */ - - template - bool Bitset::Bit::Test() const - { - return (m_block & m_mask) != 0; - } - - /*! - * \brief Gets the adress of the bit - * \return Nullptr - * - * \see std::addressof - */ - - template - template - void* Bitset::Bit::operator&() const - { - // The template is necessary to make it fail only when used - static_assert(!BadCall, "It is impossible to take the address of a bit in a bitset"); - - return nullptr; - } - - /*! - * \brief Converts this to bool - * \return true if bit set to '1' - */ - - template - Bitset::Bit::operator bool() const - { - return Test(); - } - - /*! - * \brief Sets the bit to a value - * \return A reference to this - * - * \param val Value of the bit - */ - - template - typename Bitset::Bit& Bitset::Bit::operator=(bool val) - { - return Set(val); - } - - /*! - * \brief Sets the bit to the value of another one - * \return A reference to this - * - * \param bit Other bit - */ - - template - typename Bitset::Bit& Bitset::Bit::operator=(const Bit& bit) - { - return Set(bit); - } - - /*! - * \brief Performs the operator "OR" on this bit with a boolean - * \return A reference to this - * - * \param val Value - */ - - template - typename Bitset::Bit& Bitset::Bit::operator|=(bool val) - { - // Version without branching: - Set((val) ? true : Test()); - - // With branching: - /* - if (val) - Set(); - */ - - return *this; - } - - /*! - * \brief Performs the operator "AND" on this bit with a boolean - * \return A reference to this - * - * \param val Value - */ - - template - typename Bitset::Bit& Bitset::Bit::operator&=(bool val) - { - // Version without branching: - Set((val) ? Test() : false); - - // With branching: - /* - if (!val) - Reset(); - */ - - return *this; - } - - /*! - * \brief Performs the operator "XOR" on this bit with a boolean - * \return A reference to this - * - * \param val Value - */ - - template - typename Bitset::Bit& Bitset::Bit::operator^=(bool val) - { - // Version without branching: - Set((val) ? !Test() : Test()); - - // With branching: - /* - if (val) - Flip(); - */ - - return *this; - } - - /*! - * \brief Performs the operator "RESET" on this bit with a boolean - * \return A reference to this - * - * \param val Value - */ - - template - typename Bitset::Bit& Bitset::Bit::operator-=(bool val) - { - // Version without branching: - Set((val) ? false : Test()); - - // With branching: - /* - if (val) - Reset(); - */ - - return *this; - } - - - template - std::ostream& operator<<(std::ostream& out, const Bitset& bitset) - { - return out << bitset.ToString(); - } - - - /*! - * \brief Compares two bitsets - * \return true if the two bitsets are the same - * - * \param lhs First bitset to compare with - * \param rhs Other bitset to compare with - * - * \remark If one is bigger, they are equal only if the largest has the last bit set to '0' - */ - - template - bool operator==(const Bitset& lhs, const Bitset& rhs) - { - // The comparison uses that (uint8) 00001100 == (uint16) 00000000 00001100 - // and thus conserve this property - const Bitset& greater = (lhs.GetBlockCount() > rhs.GetBlockCount()) ? lhs : rhs; - const Bitset& lesser = (lhs.GetBlockCount() > rhs.GetBlockCount()) ? rhs : lhs; - - std::size_t maxBlockCount = greater.GetBlockCount(); - std::size_t minBlockCount = lesser.GetBlockCount(); - - // We test the blocks in common to check the equality of bits - for (std::size_t i = 0; i < minBlockCount; ++i) - { - if (lhs.GetBlock(i) != rhs.GetBlock(i)) - return false; - } - - // Now we check for the blocks that only the biggest bitset owns, and to be equal, they must be set to '0' - for (std::size_t i = minBlockCount; i < maxBlockCount; ++i) - if (greater.GetBlock(i)) - return false; - - return true; - } - - /*! - * \brief Compares two bitsets - * \return false if the two bitsets are the same - * - * \param lhs First bitset to compare with - * \param rhs Other bitset to compare with - */ - - template - bool operator!=(const Bitset& lhs, const Bitset& rhs) - { - return !(lhs == rhs); - } - - /*! - * \brief Compares two bitsets - * \return true if the binary number represented by the lhs bitset is smaller - * - * \param lhs First bitset to compare with - * \param rhs Other bitset to compare with - */ - - template - bool operator<(const Bitset& lhs, const Bitset& rhs) - { - const Bitset& greater = (lhs.GetBlockCount() > rhs.GetBlockCount()) ? lhs : rhs; - const Bitset& lesser = (lhs.GetBlockCount() > rhs.GetBlockCount()) ? rhs : lhs; - - std::size_t maxBlockCount = greater.GetBlockCount(); - std::size_t minBlockCount = lesser.GetBlockCount(); - - // If the greatest bitset has a single bit active in a block outside the lesser bitset range, then it is greater - for (std::size_t i = maxBlockCount; i > minBlockCount; ++i) - { - if (greater.GetBlock(i)) - return lhs.GetBlockCount() < rhs.GetBlockCount(); - } - - // Compare the common blocks - for (std::size_t i = 0; i < minBlockCount; ++i) - { - std::size_t index = (minBlockCount - i - 1); // Compare from the most significant block to the less significant block - if (lhs.GetBlock(index) < rhs.GetBlock(index)) - return true; - } - - return false; // They are equal - } - - /*! - * \brief Compares two bitsets - * \return true if the binary number represented by the lhs bitset is smaller or equal - * - * \param lhs First bitset to compare with - * \param rhs Other bitset to compare with - */ - - template - bool operator<=(const Bitset& lhs, const Bitset& rhs) - { - return lhs < rhs || lhs == rhs; - } - - /*! - * \brief Compares two bitsets - * \return true if the binary number represented by the lhs bitset is greather - * - * \param lhs First bitset to compare with - * \param rhs Other bitset to compare with - */ - - template - bool operator>(const Bitset& lhs, const Bitset& rhs) - { - return rhs < lhs; - } - - /*! - * \brief Compares two bitsets - * \return true if the binary number represented by the lhs bitset is greather or equal - * - * \param lhs First bitset to compare with - * \param rhs Other bitset to compare with - */ - - template - bool operator>=(const Bitset& lhs, const Bitset& rhs) - { - return rhs <= lhs; - } - - /*! - * \brief Performs the operator "AND" between two bitsets - * \return The result of operator "AND" - * - * \param lhs First bitset - * \param rhs Second bitset - */ - - template - Bitset operator&(const Bitset& lhs, const Bitset& rhs) - { - Bitset bitset; - bitset.PerformsAND(lhs, rhs); - - return bitset; - } - - /*! - * \brief Performs the operator "OR" between two bitsets - * \return The result of operator "OR" - * - * \param lhs First bitset - * \param rhs Second bitset - */ - - template - Bitset operator|(const Bitset& lhs, const Bitset& rhs) - { - Bitset bitset; - bitset.PerformsOR(lhs, rhs); - - return bitset; - } - - /*! - * \brief Performs the operator "XOR" between two bitsets - * \return The result of operator "XOR" - * - * \param lhs First bitset - * \param rhs Second bitset - */ - - template - Bitset operator^(const Bitset& lhs, const Bitset& rhs) - { - Bitset bitset; - bitset.PerformsXOR(lhs, rhs); - - return bitset; - } -} - - -namespace std -{ - /*! - * \brief Swaps two bitsets, specialisation of std - * - * \param lhs First bitset - * \param rhs Second bitset - */ - - template - void swap(Nz::Bitset& lhs, Nz::Bitset& rhs) noexcept - { - lhs.Swap(rhs); - } -} - -#ifdef NAZARA_COMPILER_MSVC - // Reenable those warnings - #pragma warning(pop) -#endif - -#include diff --git a/include/Nazara/Core/ByteStream.hpp b/include/Nazara/Core/ByteStream.hpp index 7abae3123..ae6e74787 100644 --- a/include/Nazara/Core/ByteStream.hpp +++ b/include/Nazara/Core/ByteStream.hpp @@ -8,6 +8,8 @@ #define NAZARA_CORE_BYTESTREAM_HPP #include +#include +#include #include #include diff --git a/include/Nazara/Core/CallOnExit.hpp b/include/Nazara/Core/CallOnExit.hpp deleted file mode 100644 index 217c14b0c..000000000 --- a/include/Nazara/Core/CallOnExit.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_CALLONEXIT_HPP -#define NAZARA_CORE_CALLONEXIT_HPP - -#include -#include - -namespace Nz -{ - template - class CallOnExit - { - public: - CallOnExit() = default; - CallOnExit(F&& functor); - CallOnExit(const CallOnExit&) = delete; - CallOnExit(CallOnExit&&) noexcept = delete; - ~CallOnExit(); - - void CallAndReset(); - void Reset(); - - CallOnExit& operator=(const CallOnExit&) = delete; - CallOnExit& operator=(CallOnExit&&) noexcept = default; - - private: - std::optional m_functor; - }; - - template - CallOnExit(F) -> CallOnExit; -} - -#include - -#endif // NAZARA_CORE_CALLONEXIT_HPP diff --git a/include/Nazara/Core/CallOnExit.inl b/include/Nazara/Core/CallOnExit.inl deleted file mode 100644 index cc7eb8da4..000000000 --- a/include/Nazara/Core/CallOnExit.inl +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::CallOnExit - * \brief Core class that represents a function to call at the end of the scope - */ - - /*! - * \brief Constructs a CallOnExit object with a functor - * - * \param func Function to call on exit - */ - template - CallOnExit::CallOnExit(F&& functor) : - m_functor(std::move(functor)) - { - } - - /*! - * \brief Destructs the object and calls the function - */ - template - CallOnExit::~CallOnExit() - { - if (m_functor) - (*m_functor)(); - } - - /*! - * \brief Calls the function and sets the new callback - * - * \param func Function to call on exit - */ - template - void CallOnExit::CallAndReset() - { - if (m_functor) - (*m_functor)(); - - m_functor.reset(); - } - - /*! - * \brief Resets the function - * - * \param func Function to call on exit - */ - template - void CallOnExit::Reset() - { - m_functor.reset(); - } -} - -#include diff --git a/include/Nazara/Core/Clock.hpp b/include/Nazara/Core/Clock.hpp index d54698991..8e68068c4 100644 --- a/include/Nazara/Core/Clock.hpp +++ b/include/Nazara/Core/Clock.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_CLOCK_HPP #include +#include namespace Nz { diff --git a/include/Nazara/Core/Config.hpp b/include/Nazara/Core/Config.hpp index 4a6cc1b75..c2809bc9a 100644 --- a/include/Nazara/Core/Config.hpp +++ b/include/Nazara/Core/Config.hpp @@ -61,9 +61,6 @@ // Number of spinlocks to use with the Windows critical sections (0 to disable) #define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096 -// Optimize the Windows implementation with technologies of Windows NT 6.0 (and greater) (Breaks the compatibility with Windows XP) -#define NAZARA_CORE_WINDOWS_NT6 1 - /* // Sets the time between waking thread timers and activating a timer (in milliseconds) diff --git a/include/Nazara/Core/Core.hpp b/include/Nazara/Core/Core.hpp index 4a7c382f7..e6584b7e2 100644 --- a/include/Nazara/Core/Core.hpp +++ b/include/Nazara/Core/Core.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace Nz { diff --git a/include/Nazara/Core/DynLib.hpp b/include/Nazara/Core/DynLib.hpp index 0f51eaaaa..1433fa1bb 100644 --- a/include/Nazara/Core/DynLib.hpp +++ b/include/Nazara/Core/DynLib.hpp @@ -8,7 +8,8 @@ #define NAZARA_CORE_DYNLIB_HPP #include -#include +#include +#include #include #if defined(NAZARA_PLATFORM_WINDOWS) diff --git a/include/Nazara/Core/Endianness.hpp b/include/Nazara/Core/Endianness.hpp deleted file mode 100644 index 45dd22765..000000000 --- a/include/Nazara/Core/Endianness.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_ENDIANNESS_HPP -#define NAZARA_CORE_ENDIANNESS_HPP - -#include -#include - -#if !defined(NAZARA_BIG_ENDIAN) && !defined(NAZARA_LITTLE_ENDIAN) - // Automatic detection following macros of compiler - #if defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || (defined(__MIPS__) && defined(__MISPEB__)) || \ - defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || defined(__sparc__) || defined(__hppa__) - #define NAZARA_BIG_ENDIAN - #elif defined(__i386__) || defined(__i386) || defined(__X86__) || defined (__x86_64) || defined(_M_I86) || \ - defined(_M_IX86) || defined(_M_X64) - #define NAZARA_LITTLE_ENDIAN - #else - #error Failed to identify endianness, you must define either NAZARA_BIG_ENDIAN or NAZARA_LITTLE_ENDIAN - #endif -#elif defined(NAZARA_BIG_ENDIAN) && defined(NAZARA_LITTLE_ENDIAN) - #error You cannot define both NAZARA_BIG_ENDIAN and NAZARA_LITTLE_ENDIAN -#endif - -namespace Nz -{ - inline constexpr Endianness GetPlatformEndianness(); - inline void SwapBytes(void* buffer, std::size_t size); - template T SwapBytes(T value); -} - -#include - -#endif // NAZARA_CORE_ENDIANNESS_HPP diff --git a/include/Nazara/Core/Endianness.inl b/include/Nazara/Core/Endianness.inl deleted file mode 100644 index 76c102c6d..000000000 --- a/include/Nazara/Core/Endianness.inl +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \brief Gets the platform endianness - * \return Type of the endianness - */ - inline constexpr Endianness GetPlatformEndianness() - { - #if defined(NAZARA_BIG_ENDIAN) - return Endianness::BigEndian; - #elif defined(NAZARA_LITTLE_ENDIAN) - return Endianness::LittleEndian; - #endif - } - - /*! - * \ingroup core - * \brief Swaps the byte for endianness operations - * - * \param buffer Raw memory - * \param size Size to change endianness - * - * \remark If size is greater than the preallocated buffer, the behavior is undefined - */ - inline void SwapBytes(void* buffer, std::size_t size) - { - UInt8* bytes = static_cast(buffer); - std::size_t i = 0; - std::size_t j = size - 1; - - while (i < j) - std::swap(bytes[i++], bytes[j--]); - } - - template - T SwapBytes(T value) - { - SwapBytes(&value, sizeof(T)); - return value; - } -} - -#include diff --git a/include/Nazara/Core/Enums.hpp b/include/Nazara/Core/Enums.hpp index 3219ead4c..a8b7dfd27 100644 --- a/include/Nazara/Core/Enums.hpp +++ b/include/Nazara/Core/Enums.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_CORE_ENUMS_HPP #define NAZARA_CORE_ENUMS_HPP -#include +#include namespace Nz { @@ -28,16 +28,6 @@ namespace Nz Max = AtEnd }; - enum class Endianness - { - Unknown = -1, - - BigEndian, - LittleEndian, - - Max = LittleEndian - }; - enum class ErrorMode { None, diff --git a/include/Nazara/Core/ErrorFlags.hpp b/include/Nazara/Core/ErrorFlags.hpp index 9024dd8f5..d825167d2 100644 --- a/include/Nazara/Core/ErrorFlags.hpp +++ b/include/Nazara/Core/ErrorFlags.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_ERRORFLAGS_HPP #include +#include #include namespace Nz diff --git a/include/Nazara/Core/File.hpp b/include/Nazara/Core/File.hpp index bd3493d7e..cad67251a 100644 --- a/include/Nazara/Core/File.hpp +++ b/include/Nazara/Core/File.hpp @@ -9,9 +9,9 @@ #include #include -#include -#include #include +#include +#include #include #include #include diff --git a/include/Nazara/Core/Flags.hpp b/include/Nazara/Core/Flags.hpp deleted file mode 100644 index bc670b96a..000000000 --- a/include/Nazara/Core/Flags.hpp +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_FLAGS_HPP -#define NAZARA_CORE_FLAGS_HPP - -#include -#include - -namespace Nz -{ - // From: https://www.justsoftwaresolutions.co.uk/cplusplus/using-enum-classes-as-bitfields.html - template - struct EnumAsFlags - { - }; - - - template - struct IsEnumFlag : std::false_type {}; - - template - struct IsEnumFlag::max)>> : std::true_type {}; - - - template - struct GetEnumAutoFlag : std::bool_constant {}; - - template - struct GetEnumAutoFlag> : std::bool_constant {}; - - template - class Flags - { - static_assert(std::is_enum_v, "Type must be an enumeration"); - static_assert(IsEnumFlag(), "Enum has not been enabled as flags by an EnumAsFlags specialization"); - static_assert(std::is_same_v::max)>, E>, "EnumAsFlags field max should be of the same type as the enum"); - - static constexpr std::size_t MaxValue = static_cast(EnumAsFlags::max); - static constexpr bool AutoFlag = GetEnumAutoFlag(); - - using BitField16 = std::conditional_t<(MaxValue >= 8), UInt16, UInt8>; - using BitField32 = std::conditional_t<(MaxValue >= 16), UInt32, BitField16>; - - public: - using BitField = std::conditional_t<(MaxValue >= 32), UInt64, BitField32>; - - constexpr Flags(BitField value = 0); - constexpr Flags(E enumVal); - - void Clear(); - void Clear(const Flags& flags); - - void Set(const Flags& flags); - - constexpr bool Test(const Flags& flags) const; - - explicit constexpr operator bool() const; - template::value && sizeof(T) >= sizeof(BitField)>> explicit constexpr operator T() const; - - constexpr Flags operator~() const; - constexpr Flags operator&(const Flags& rhs) const; - constexpr Flags operator|(const Flags& rhs) const; - constexpr Flags operator^(const Flags& rhs) const; - - constexpr bool operator==(const Flags& rhs) const; - constexpr bool operator!=(const Flags& rhs) const; - - /*constexpr*/ Flags& operator|=(const Flags& rhs); - /*constexpr*/ Flags& operator&=(const Flags& rhs); - /*constexpr*/ Flags& operator^=(const Flags& rhs); - - static constexpr BitField GetFlagValue(E enumValue); - - static constexpr BitField ValueMask = BitField((UInt64(1) << (MaxValue + 1)) - 1); - - private: - BitField m_value; - }; - - template constexpr Flags operator&(E lhs, Flags rhs); - template constexpr Flags operator|(E lhs, Flags rhs); - template constexpr Flags operator^(E lhs, Flags rhs); - - // Little hack to have them in both Nz and global scope - namespace FlagsOperators - { - template constexpr std::enable_if_t::value, Flags> operator~(E lhs); - template constexpr std::enable_if_t::value, Flags> operator&(E lhs, E rhs); - template constexpr std::enable_if_t::value, Flags> operator|(E lhs, E rhs); - template constexpr std::enable_if_t::value, Flags> operator^(E lhs, E rhs); - } - - using namespace FlagsOperators; -} - -using namespace Nz::FlagsOperators; - -#include - -#endif // NAZARA_CORE_FLAGS_HPP diff --git a/include/Nazara/Core/Flags.inl b/include/Nazara/Core/Flags.inl deleted file mode 100644 index 68c48e4e4..000000000 --- a/include/Nazara/Core/Flags.inl +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Flags - * \brief Core class used to combine enumeration values into flags bitfield - */ - - /*! - * \brief Constructs a Flags object using a bitfield - * - * \param value Bitfield to be used - * - * Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active). - */ - template - constexpr Flags::Flags(BitField value) : - m_value(value) - { - } - - /*! - * \brief Constructs a Flags object using an Enum value - * - * \param enumVal enumVal - * - * Setup a Flags object with only one flag active (corresponding to the enum value passed as argument). - */ - template - constexpr Flags::Flags(E enumVal) : - Flags(GetFlagValue(enumVal)) - { - } - - /*! - * \brief Clear all flags - * - * \see Test - */ - template - void Flags::Clear() - { - m_value = 0; - } - - /*! - * \brief Clear some flags - * - * \param flags Flags to be cleared - * - * \see Test - */ - template - void Flags::Clear(const Flags& flags) - { - m_value &= ~flags.m_value; - } - - /*! - * \brief Enable some flags - * - * \param flags Flags to be enabled - * - * \see Clear - * \see Test - */ - template - void Flags::Set(const Flags& flags) - { - m_value |= flags.m_value; - } - - /*! - * \brief Tests if all flags from a Flags object are enabled - * \return True if all tested flags are enabled. - * - * \see Clear - */ - template - constexpr bool Flags::Test(const Flags& flags) const - { - return (m_value & flags.m_value) == flags.m_value; - } - - /*! - * \brief Tests any flag - * \return True if any flag is enabled. - * - * This will convert to a boolean value allowing to check if any flag is set. - */ - template - constexpr Flags::operator bool() const - { - return m_value != 0; - } - - /*! - * \brief Converts to an integer - * \return Enabled flags as a integer - * - * This will only works if the integer type is large enough to store all flags states - */ - template - template - constexpr Flags::operator T() const - { - return m_value; - } - - /*! - * \brief Reverse flag states - * \return Opposite enabled flags - * - * This will returns a copy of the Flags object with reversed flags states. - */ - template - constexpr Flags Flags::operator~() const - { - return Flags((~m_value) & ValueMask); - } - - /*! - * \brief Compare flag states - * \return Shared flags - * - * \param rhs Flags to compare with. - * - * This will returns a copy of the Flags object with only enabled flags in common with the parameter - */ - template - constexpr Flags Flags::operator&(const Flags& rhs) const - { - return Flags(m_value & rhs.m_value); - } - - /*! - * \brief Combine flag states - * \return Combined flags - * - * This will returns a copy of the Flags object with combined flags from the parameter. - * - * \param rhs Flags to combine with. - */ - template - constexpr Flags Flags::operator|(const Flags& rhs) const - { - return Flags(m_value | rhs.m_value); - } - - /*! - * \brief XOR flag states - * \return XORed flags. - * - * \param rhs Flags to XOR with. - * - * This performs a XOR (Exclusive OR) on a copy of the flag object. - * This will returns a copy of the object with disabled common flags and enabled unique ones. - */ - template - constexpr Flags Flags::operator^(const Flags& rhs) const - { - return Flags((m_value ^ rhs.m_value) & ValueMask); - } - - /*! - * \brief Check equality with flag object - * \return True if both flags objects have the same states. - * - * \param rhs Flags to compare with. - * - * Compare two Flags object and returns true if the flag states are identical. - */ - template - constexpr bool Flags::operator==(const Flags& rhs) const - { - return m_value == rhs.m_value; - } - - /*! - * \brief Check inequality with flag object - * \return True if both flags objects have different states. - * - * \param rhs Flags to compare with. - * - * Compare two Flags object and returns true if the flag states are identical. - */ - template - constexpr bool Flags::operator!=(const Flags& rhs) const - { - return !operator==(rhs); - } - - /*! - * \brief Combine flag states - * \return A reference to the object. - * - * \param rhs Flags to combine with. - * - * This will enable flags which are enabled in parameter object and not in Flag object. - */ - template - /*constexpr*/ Flags& Flags::operator|=(const Flags& rhs) - { - m_value |= rhs.m_value; - - return *this; - } - - /*! - * \brief Compare flag states - * \return A reference to the object. - * - * \param rhs Flags to compare with. - * - * This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa). - */ - template - /*constexpr*/ Flags& Flags::operator&=(const Flags& rhs) - { - m_value &= rhs.m_value; - - return *this; - } - - /*! - * \brief XOR flag states - * \return A reference to the object. - * - * \param rhs Flags to XOR with. - * - * This performs a XOR (Exclusive OR) on the flag object. - * This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects. - */ - template - /*constexpr*/ Flags& Flags::operator^=(const Flags& rhs) - { - m_value ^= rhs.m_value; - m_value &= ValueMask; - - return *this; - } - - /*! - * \brief Returns a bitfield corresponding to an enum value. - * \return Bitfield representation of the enum value - * - * \param enumValue Enumeration value to get as a bitfield. - * - * Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled. - */ - template - constexpr typename Flags::BitField Flags::GetFlagValue(E enumValue) - { - if constexpr (AutoFlag) - return 1U << static_cast(enumValue); - else - return enumValue; - } - - /*! - * \brief Compare flag states - * \return Compared flags - * - * This will returns a copy of the Flags object compared with the enum state. - * - * \param lhs Enum to compare with flags. - * \param rhs Flags object. - */ - template - constexpr Flags operator&(E lhs, Flags rhs) - { - return rhs & lhs; - } - - /*! - * \brief Combine flag states - * \return Combined flags - * - * This will returns a copy of the Flags object combined with the enum state. - * - * \param lhs Enum to combine with flags. - * \param rhs Flags object. - */ - template - constexpr Flags operator|(E lhs, Flags rhs) - { - return rhs | lhs; - } - - /*! - * \brief XOR flag states - * \return XORed flags - * - * This will returns a copy of the Flags object XORed with the enum state. - * - * \param lhs Enum to XOR with flags. - * \param rhs Flags object. - */ - template - constexpr Flags operator^(E lhs, Flags rhs) - { - return rhs ^ lhs; - } - - - namespace FlagsOperators - { - /*! - * \brief Override binary NOT operator on enum to turns into a Flags object. - * \return A Flags object with reversed bits. - * - * \param lhs Enumeration value to reverse. - * - * Returns a Flags object with all state enabled except for the enum one. - */ - template - constexpr std::enable_if_t::value, Flags> operator~(E lhs) - { - return ~Flags(lhs); - } - - /*! - * \brief Override binary AND operator on enum to turns into a Flags object. - * \return A Flags object with compare enum states. - * - * \param lhs First enumeration value to compare. - * \param rhs Second enumeration value to compare. - * - * Returns a Flags object with compared states from the two enumeration values. - * In this case, only one flag will be enabled if both enumeration values are the same. - */ - template - constexpr std::enable_if_t::value, Flags> operator&(E lhs, E rhs) - { - return Flags(lhs) & rhs; - } - - /*! - * \brief Override binary OR operator on enum to turns into a Flags object. - * \return A Flags object with combined enum states. - * - * \param lhs First enumeration value to combine. - * \param rhs Second enumeration value to combine. - * - * Returns a Flags object with combined states from the two enumeration values. - */ - template - constexpr std::enable_if_t::value, Flags> operator|(E lhs, E rhs) - { - return Flags(lhs) | rhs; - } - - /*! - * \brief Override binary XOR operator on enum to turns into a Flags object. - * \return A Flags object with XORed enum states. - * - * \param lhs First enumeration value to compare. - * \param rhs Second enumeration value to compare. - * - * Returns a Flags object with XORed states from the two enumeration values. - * In this case, two flags will be enabled if both the enumeration values are different. - */ - template - constexpr std::enable_if_t::value, Flags> operator^(E lhs, E rhs) - { - return Flags(lhs) ^ rhs; - } - } -} - -namespace std -{ - template - struct hash> - { - std::size_t operator()(const Nz::Flags& flags) - { - using UnderlyingType = typename Nz::Flags::BitField; - using Hasher = hash; - Hasher hasher; - return hasher(static_cast(flags)); - } - }; -} - -#include diff --git a/include/Nazara/Core/HandledObject.hpp b/include/Nazara/Core/HandledObject.hpp index 823b692c8..7ffa4488c 100644 --- a/include/Nazara/Core/HandledObject.hpp +++ b/include/Nazara/Core/HandledObject.hpp @@ -7,8 +7,10 @@ #ifndef NAZARA_CORE_HANDLEDOBJECT_HPP #define NAZARA_CORE_HANDLEDOBJECT_HPP -#include -#include +#include +#include +#include +#include #include #include diff --git a/include/Nazara/Core/HardwareInfo.hpp b/include/Nazara/Core/HardwareInfo.hpp index 3f84b091e..fa4f1d2bd 100644 --- a/include/Nazara/Core/HardwareInfo.hpp +++ b/include/Nazara/Core/HardwareInfo.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_HARDWAREINFO_HPP #include +#include #include #include diff --git a/include/Nazara/Core/Log.hpp b/include/Nazara/Core/Log.hpp index f9aaef866..638df8000 100644 --- a/include/Nazara/Core/Log.hpp +++ b/include/Nazara/Core/Log.hpp @@ -8,7 +8,10 @@ #define NAZARA_CORE_LOG_HPP #include -#include +#include +#include +#include +#include #include #ifdef NAZARA_DEBUG diff --git a/include/Nazara/Core/MemoryHelper.hpp b/include/Nazara/Core/MemoryHelper.hpp deleted file mode 100644 index d3abdecb1..000000000 --- a/include/Nazara/Core/MemoryHelper.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_MEMORYHELPER_HPP -#define NAZARA_CORE_MEMORYHELPER_HPP - -#if defined(NAZARA_COMPILER_MSVC) || defined(NAZARA_COMPILER_MINGW) - -#include - -// with MSVC, using alloca with a size of zero returns a valid pointer -#define NAZARA_ALLOCA(size) _alloca(size) -#define NAZARA_ALLOCA_SUPPORT - -#elif defined(NAZARA_COMPILER_CLANG) || defined(NAZARA_COMPILER_GCC) || defined(NAZARA_COMPILER_INTEL) - -#include - -// with Clang/GCC, using alloca with a size of zero does nothing good -#define NAZARA_ALLOCA(size) alloca(((size) > 0) ? (size) : 1) -#define NAZARA_ALLOCA_SUPPORT - -#endif - -#include - -namespace Nz -{ - void OperatorDelete(void* ptr); - void* OperatorNew(std::size_t size); - - template - T* PlacementNew(T* ptr, Args&&... args); - - template - void PlacementDestroy(T* ptr); -} - -#include - -#endif // NAZARA_CORE_MEMORYHELPER_HPP diff --git a/include/Nazara/Core/MemoryHelper.inl b/include/Nazara/Core/MemoryHelper.inl deleted file mode 100644 index 2fb0b95e2..000000000 --- a/include/Nazara/Core/MemoryHelper.inl +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// I'm not proud of those five following lines but ti's hard to do with another way now -#ifdef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION - #define NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION_DEFINED -#else - #define NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION -#endif - -#include -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \fn Nz::MemoryHelper - * \brief Core functions that helps the handle of memory in the engine - */ - - /*! - * \brief Calls the operator delete on the pointer - * - * \remark Uses MemoryManager with NAZARA_CORE_MANAGE_MEMORY defined else operator delete - */ - inline void OperatorDelete(void* ptr) - { - #if NAZARA_CORE_MANAGE_MEMORY - MemoryManager::Free(ptr); - #else - operator delete(ptr); - #endif - } - - /*! - * \brief Calls the operator new on the pointer - * - * \remark Uses MemoryManager with NAZARA_CORE_MANAGE_MEMORY defined else operator new - */ - inline void* OperatorNew(std::size_t size) - { - #if NAZARA_CORE_MANAGE_MEMORY - return MemoryManager::Allocate(size); - #else - return operator new(size); - #endif - } - - /*! - * \brief Constructs the object inplace - * \return Pointer to the constructed object - * - * \param ptr Pointer to raw memory allocated - * \param args Arguments for the constructor - */ - template - T* PlacementNew(T* ptr, Args&&... args) - { - return new (ptr) T(std::forward(args)...); - } - - /*! - * \brief Calls the object destructor explicitly - * - * \param ptr Pointer to a previously constructed pointer on raw memory - * - * \remark This does not deallocate memory, and is a no-op on a null pointer - */ - template - void PlacementDestroy(T* ptr) - { - if (ptr) - ptr->~T(); - } -} - -#include - -// If we have defined the constant, then we have to undefine it (to avoid bloating in the engine) -#ifndef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION_DEFINED - #undef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION -#endif diff --git a/include/Nazara/Core/MemoryManager.hpp b/include/Nazara/Core/MemoryManager.hpp index dc6e7cc2c..7833e6e25 100644 --- a/include/Nazara/Core/MemoryManager.hpp +++ b/include/Nazara/Core/MemoryManager.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_MEMORYMANAGER_HPP #include +#include #include namespace Nz diff --git a/include/Nazara/Core/MemoryPool.hpp b/include/Nazara/Core/MemoryPool.hpp deleted file mode 100644 index 8d6ef54e8..000000000 --- a/include/Nazara/Core/MemoryPool.hpp +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_MEMORYPOOL_HPP -#define NAZARA_CORE_MEMORYPOOL_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - template - class MemoryPool - { - public: - class iterator; - friend iterator; - - MemoryPool(std::size_t blockSize); - MemoryPool(const MemoryPool&) = delete; - MemoryPool(MemoryPool&&) noexcept = default; - ~MemoryPool(); - - template T* Allocate(std::size_t& index, Args&&... args); - - void Clear(); - - void Free(std::size_t index); - - std::size_t GetAllocatedEntryCount() const; - std::size_t GetBlockCount() const; - std::size_t GetBlockSize() const; - std::size_t GetFreeEntryCount() const; - - void Reset(); - - T* RetrieveFromIndex(std::size_t index); - std::size_t RetrieveEntryIndex(const T* data); - - // std interface - iterator begin(); - iterator end(); - std::size_t size(); - - MemoryPool& operator=(const MemoryPool&) = delete; - MemoryPool& operator=(MemoryPool&& pool) noexcept = default; - - static constexpr std::size_t InvalidIndex = std::numeric_limits::max(); - - private: - void AllocateBlock(); - T* GetAllocatedPointer(std::size_t blockIndex, std::size_t localIndex); - std::pair GetFirstAllocatedEntry() const; - std::pair GetFirstAllocatedEntryFromBlock(std::size_t blockIndex) const; - std::pair GetNextAllocatedEntry(std::size_t blockIndex, std::size_t localIndex) const; - - using AlignedStorage = std::aligned_storage_t; - - struct Block - { - std::size_t occupiedEntryCount = 0; - std::unique_ptr memory; - Bitset freeEntries; - Bitset occupiedEntries; //< Opposite of freeEntries - }; - - std::size_t m_blockSize; - std::vector m_blocks; - }; - - template - class MemoryPool::iterator - { - friend MemoryPool; - - public: - using iterator_category = std::input_iterator_tag; - using value_type = T; - using difference_type = std::ptrdiff_t; - using pointer = T*; - using reference = T&; - - iterator(const iterator&) = default; - iterator(iterator&&) = default; - - iterator& operator=(const iterator&) = default; - iterator& operator=(iterator&&) = default; - - iterator operator++(int); - iterator& operator++(); - - bool operator==(const iterator& rhs) const; - bool operator!=(const iterator& rhs) const; - reference operator*() const; - - private: - iterator(MemoryPool* owner, std::size_t blockIndex, std::size_t localIndex); - - std::size_t m_blockIndex; - std::size_t m_localIndex; - MemoryPool* m_owner; - }; -} - -#include - -#endif // NAZARA_CORE_MEMORYPOOL_HPP diff --git a/include/Nazara/Core/MemoryPool.inl b/include/Nazara/Core/MemoryPool.inl deleted file mode 100644 index f9baae4e6..000000000 --- a/include/Nazara/Core/MemoryPool.inl +++ /dev/null @@ -1,384 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::MemoryPool - * \brief Core class that represents a memory pool - */ - - /*! - * \brief Constructs a MemoryPool object - * - * \param blockSize Size of blocks that will be allocated - */ - template - MemoryPool::MemoryPool(std::size_t blockSize) : - m_blockSize(blockSize) - { - // Allocate one block by default - AllocateBlock(); - } - - /*! - * \brief Destroy the memory pool, calling the destructor for every allocated object and desallocating blocks - */ - template - MemoryPool::~MemoryPool() - { - Reset(); - } - - /*! - * \brief Allocates enough memory for the size and returns a pointer to it - * \return A pointer to memory allocated - * - * \param index Output entry index (which can be used for deallocation) - * - * \remark If the size is greater than the blockSize of pool, new operator is called - */ - template - template - T* MemoryPool::Allocate(std::size_t& index, Args&&... args) - { - std::size_t blockIndex = 0; - std::size_t localIndex = InvalidIndex; - for (; blockIndex < m_blocks.size(); ++blockIndex) - { - auto& block = m_blocks[blockIndex]; - if (block.occupiedEntryCount == m_blockSize) - continue; - - localIndex = block.freeEntries.FindFirst(); - assert(localIndex != block.freeEntries.npos); - break; - } - - if (blockIndex >= m_blocks.size()) - { - // No more room, allocate a new block - blockIndex = m_blocks.size(); - localIndex = 0; - - AllocateBlock(); - } - - assert(localIndex != InvalidIndex); - - auto& block = m_blocks[blockIndex]; - block.freeEntries.Reset(localIndex); - block.occupiedEntries.Set(localIndex); - block.occupiedEntryCount++; - - T* entry = reinterpret_cast(&block.memory[localIndex]); - PlacementNew(entry, std::forward(args)...); - - index = blockIndex * m_blockSize + localIndex; - - return entry; - } - - /*! - * \brief Clears the memory pool - * - * This is call the destructor of every active entry and invalidate every entry index, and will free every allocated block - * - * \see Reset - */ - template - void MemoryPool::Clear() - { - Reset(); - - m_blocks.clear(); - } - - /*! - * \brief Returns an object memory to the memory pool - * - * Calls the destructor of the target object and returns its memory to the pool - * - * \param index Index of the allocated object - * - * \see Reset - */ - template - void MemoryPool::Free(std::size_t index) - { - std::size_t blockIndex = index / m_blockSize; - std::size_t localIndex = index % m_blockSize; - - T* entry = GetAllocatedPointer(blockIndex, localIndex); - PlacementDestroy(entry); - - auto& block = m_blocks[blockIndex]; - assert(block.occupiedEntryCount > 0); - block.occupiedEntryCount--; - - block.freeEntries.Set(localIndex); - block.occupiedEntries.Reset(localIndex); - } - - /*! - * \brief Returns the number of allocated entries - * \return How many entries are currently allocated - */ - template - std::size_t MemoryPool::GetAllocatedEntryCount() const - { - std::size_t count = 0; - for (auto& block : m_blocks) - count += block.occupiedEntryCount; - - return count; - } - - /*! - * \brief Gets the block count - * \return How many block are currently allocated for this memory pool - */ - template - std::size_t MemoryPool::GetBlockCount() const - { - return m_blocks.size(); - } - - /*! - * \brief Gets the block size - * \return Size of each block (i.e. how many items can fit in a block) - */ - template - std::size_t MemoryPool::GetBlockSize() const - { - return m_blockSize; - } - - /*! - * \brief Returns the number of free entries - * \return How many entries are currently freed - */ - template - std::size_t MemoryPool::GetFreeEntryCount() const - { - std::size_t count = m_blocks.size() * m_blockSize; - return count - GetAllocatedEntryCount(); - } - - /*! - * \brief Resets the memory pool - * - * This is call the destructor of every active entry and invalidate every entry index, returning the pool to full capacity - * Note that memory is not freed - * - * \see Clear - */ - template - void MemoryPool::Reset() - { - for (std::size_t blockIndex = 0; blockIndex < m_blocks.size(); ++blockIndex) - { - auto& block = m_blocks[blockIndex]; - if (block.occupiedEntryCount == 0) - continue; - - for (std::size_t localIndex = block.occupiedEntries.FindFirst(); localIndex != block.occupiedEntries.npos; localIndex = block.occupiedEntries.FindNext(localIndex)) - { - T* entry = reinterpret_cast(&m_blocks[blockIndex].memory[localIndex]); - PlacementDestroy(entry); - } - - block.freeEntries.Reset(true); - block.occupiedEntries.Reset(false); - block.occupiedEntryCount = 0; - } - } - - /*! - * \brief Retrieve an allocated pointer based on a valid entry index - * - * \param index Entry index - * - * \return Pointer to the allocated entry - * - * \remark index must be valid - */ - template - T* MemoryPool::RetrieveFromIndex(std::size_t index) - { - std::size_t blockIndex = index / m_blockSize; - std::size_t localIndex = index % m_blockSize; - - return GetAllocatedPointer(blockIndex, localIndex); - } - - /*! - * \brief Retrieve an entry index based on an allocated pointer - * - * \param data Allocated entry pointed - * - * \return Corresponding index, or InvalidIndex if it's not part of this pool - */ - template - std::size_t MemoryPool::RetrieveEntryIndex(const T* data) - { - std::size_t blockIndex = 0; - std::size_t localIndex = InvalidIndex; - for (; blockIndex < m_blocks.size(); ++blockIndex) - { - auto& block = m_blocks[blockIndex]; - const T* startPtr = reinterpret_cast(&block.memory[0]); - if (data >= startPtr && data < startPtr + m_blockSize) - { - // Part of block - localIndex = SafeCast(data - startPtr); - assert(data == reinterpret_cast(&block.memory[localIndex])); - - break; - } - } - - if (blockIndex == m_blocks.size()) - return InvalidIndex; - - assert(localIndex != InvalidIndex); - - return blockIndex * m_blockSize + localIndex; - } - - template - auto MemoryPool::begin() -> iterator - { - auto [blockIndex, localIndex] = GetFirstAllocatedEntry(); - return iterator(this, blockIndex, localIndex); - } - - template - auto MemoryPool::end() -> iterator - { - return iterator(this, InvalidIndex, InvalidIndex); - } - - template - std::size_t MemoryPool::size() - { - return GetAllocatedEntryCount(); - } - - template - void MemoryPool::AllocateBlock() - { - auto& block = m_blocks.emplace_back(); - block.freeEntries.Resize(m_blockSize, true); - block.occupiedEntries.Resize(m_blockSize, false); - block.memory = std::make_unique(m_blockSize); - } - - template - T* MemoryPool::GetAllocatedPointer(std::size_t blockIndex, std::size_t localIndex) - { - assert(blockIndex < m_blocks.size()); - auto& block = m_blocks[blockIndex]; - assert(block.occupiedEntries.Test(localIndex)); - - return reinterpret_cast(&block.memory[localIndex]); - } - - template - std::pair MemoryPool::GetFirstAllocatedEntry() const - { - return GetFirstAllocatedEntryFromBlock(0); - } - - template - std::pair MemoryPool::GetFirstAllocatedEntryFromBlock(std::size_t blockIndex) const - { - // Search in next block - std::size_t localIndex = InvalidIndex; - for (; blockIndex < m_blocks.size(); ++blockIndex) - { - auto& block = m_blocks[blockIndex]; - if (block.occupiedEntryCount == 0) - continue; - - localIndex = block.occupiedEntries.FindFirst(); - assert(localIndex != block.occupiedEntries.npos); - break; - } - - if (blockIndex >= m_blocks.size()) - return { InvalidIndex, InvalidIndex }; - - return { blockIndex, localIndex }; - } - - template - std::pair MemoryPool::GetNextAllocatedEntry(std::size_t blockIndex, std::size_t localIndex) const - { - assert(blockIndex < m_blocks.size()); - auto& block = m_blocks[blockIndex]; - std::size_t nextLocalIndex = block.occupiedEntries.FindNext(localIndex); - if (nextLocalIndex != block.occupiedEntries.npos) - return { blockIndex, nextLocalIndex }; - - // Search in next block - return GetFirstAllocatedEntryFromBlock(blockIndex + 1); - } - - - template - MemoryPool::iterator::iterator(MemoryPool* owner, std::size_t blockIndex, std::size_t localIndex) : - m_blockIndex(blockIndex), - m_localIndex(localIndex), - m_owner(owner) - { - } - - template - auto MemoryPool::iterator::operator++(int) -> iterator - { - iterator copy(*this); - operator++(); - return copy; - } - - template - auto MemoryPool::iterator::operator++() -> iterator& - { - auto [blockIndex, localIndex] = m_owner->GetNextAllocatedEntry(m_blockIndex, m_localIndex); - m_blockIndex = blockIndex; - m_localIndex = localIndex; - - return *this; - } - - template - bool MemoryPool::iterator::operator==(const iterator& rhs) const - { - assert(m_owner == rhs.m_owner); - return m_blockIndex == rhs.m_blockIndex && m_localIndex == rhs.m_localIndex; - } - - template - bool MemoryPool::iterator::operator!=(const iterator& rhs) const - { - return !operator==(rhs); - } - - template - auto MemoryPool::iterator::operator*() const -> reference - { - return *m_owner->GetAllocatedPointer(m_blockIndex, m_localIndex); - } -} - -#include diff --git a/include/Nazara/Core/MemoryStream.hpp b/include/Nazara/Core/MemoryStream.hpp index 0543dc920..d5b4a489f 100644 --- a/include/Nazara/Core/MemoryStream.hpp +++ b/include/Nazara/Core/MemoryStream.hpp @@ -8,8 +8,8 @@ #define NAZARA_CORE_MEMORYSTREAM_HPP #include -#include #include +#include namespace Nz { diff --git a/include/Nazara/Core/ModuleBase.inl b/include/Nazara/Core/ModuleBase.inl index 7ed369abc..13c576746 100644 --- a/include/Nazara/Core/ModuleBase.inl +++ b/include/Nazara/Core/ModuleBase.inl @@ -19,7 +19,7 @@ namespace Nz ModuleBase::ModuleBase(std::string moduleName, T* pointer, NoLog) : m_moduleName(std::move(moduleName)) { - NazaraAssert(T::s_instance == nullptr, "only one instance of " + m_moduleName + " must exist at a given time"); + NazaraAssert(T::s_instance == nullptr, "only one instance of " + m_moduleName + " can exist at a given time"); T::s_instance = pointer; } diff --git a/include/Nazara/Core/Modules.hpp b/include/Nazara/Core/Modules.hpp index f922a5c25..7f8f2d7ca 100644 --- a/include/Nazara/Core/Modules.hpp +++ b/include/Nazara/Core/Modules.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_CORE_MODULES_HPP #define NAZARA_CORE_MODULES_HPP -#include +#include namespace Nz { diff --git a/include/Nazara/Core/MovablePtr.hpp b/include/Nazara/Core/MovablePtr.hpp deleted file mode 100644 index b1f9ca3fe..000000000 --- a/include/Nazara/Core/MovablePtr.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_MOVABLEPTR_HPP -#define NAZARA_CORE_MOVABLEPTR_HPP - -namespace Nz -{ - template - class MovablePtr - { - public: - MovablePtr(T* value = nullptr); - MovablePtr(const MovablePtr&) = default; - MovablePtr(MovablePtr&& ptr) noexcept; - ~MovablePtr() = default; - - T* Get() const; - - T* operator->() const; - - operator T*() const; - - MovablePtr& operator=(T* value); - MovablePtr& operator=(const MovablePtr&) = default; - MovablePtr& operator=(MovablePtr&& ptr) noexcept; - - private: - T* m_value; - }; -} - -#include - -#endif // NAZARA_CORE_MOVABLEPTR_HPP diff --git a/include/Nazara/Core/MovablePtr.inl b/include/Nazara/Core/MovablePtr.inl deleted file mode 100644 index 8c52a23d6..000000000 --- a/include/Nazara/Core/MovablePtr.inl +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::MovablePtr - * \brief Wraps a raw (non-proprietary) to allows it to be moved implicitly - */ - - template - MovablePtr::MovablePtr(T* value) : - m_value(value) - { - } - - template - MovablePtr::MovablePtr(MovablePtr&& ptr) noexcept : - m_value(ptr.m_value) - { - ptr.m_value = nullptr; - } - - template - inline T* MovablePtr::Get() const - { - return m_value; - } - - template - T* MovablePtr::operator->() const - { - return m_value; - } - - template - MovablePtr::operator T*() const - { - return m_value; - } - - template - inline MovablePtr& MovablePtr::operator=(T* value) - { - m_value = value; - - return *this; - } - - template - MovablePtr& MovablePtr::operator=(MovablePtr&& ptr) noexcept - { - std::swap(m_value, ptr.m_value); - return *this; - } -} - -#include diff --git a/include/Nazara/Core/MovableValue.hpp b/include/Nazara/Core/MovableValue.hpp deleted file mode 100644 index 095bbdc94..000000000 --- a/include/Nazara/Core/MovableValue.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_MOVABLEVALUE_HPP -#define NAZARA_CORE_MOVABLEVALUE_HPP - -namespace Nz -{ - template - class MovableValue - { - public: - MovableValue(T value = T{}); - MovableValue(const MovableValue&) = default; - MovableValue(MovableValue&& ptr) noexcept; - ~MovableValue() = default; - - T& Get(); - const T& Get() const; - - operator T&(); - operator const T&() const; - - MovableValue& operator=(T value); - MovableValue& operator=(const MovableValue&) = default; - MovableValue& operator=(MovableValue&& ptr) noexcept; - - private: - T m_value; - }; -} - -#include - -#endif // NAZARA_CORE_MOVABLEVALUE_HPP diff --git a/include/Nazara/Core/MovableValue.inl b/include/Nazara/Core/MovableValue.inl deleted file mode 100644 index 3ab14eeb1..000000000 --- a/include/Nazara/Core/MovableValue.inl +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - template - MovableValue::MovableValue(T value) : - m_value(std::move(value)) - { - } - - template - MovableValue::MovableValue(MovableValue&& val) noexcept : - m_value() - { - std::swap(m_value, val.m_value); - } - - template - T& MovableValue::Get() - { - return m_value; - } - - template - const T& MovableValue::Get() const - { - return m_value; - } - - template - MovableValue::operator T&() - { - return m_value; - } - - template - MovableValue::operator const T&() const - { - return m_value; - } - - template - MovableValue& MovableValue::operator=(T value) - { - m_value = std::move(value); - - return *this; - } - - template - MovableValue& MovableValue::operator=(MovableValue&& ptr) noexcept - { - std::swap(m_value, ptr.m_value); - return *this; - } -} - -#include diff --git a/include/Nazara/Core/OffsetOf.hpp b/include/Nazara/Core/OffsetOf.hpp deleted file mode 100644 index f9fc1f52e..000000000 --- a/include/Nazara/Core/OffsetOf.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_OFFSETOF_HPP -#define NAZARA_CORE_OFFSETOF_HPP - -// By "Jesse Good" from SO: -// http://stackoverflow.com/questions/12811330/c-compile-time-offsetof-inside-a-template?answertab=votes#tab-top - -namespace Nz -{ - namespace Detail - { - template T GetClassType(M T::*); - template M GetMemberType(M T::*); - - template - constexpr std::size_t OffsetOf() - { - return reinterpret_cast(&((static_cast(0))->*M)); - } - } -} - -#define NazaraOffsetOf(type, member) Nz::Detail::OffsetOf() - -#endif // NAZARA_CORE_OFFSETOF_HPP diff --git a/include/Nazara/Core/ParameterList.hpp b/include/Nazara/Core/ParameterList.hpp index 8a17051f7..66ff56fc2 100644 --- a/include/Nazara/Core/ParameterList.hpp +++ b/include/Nazara/Core/ParameterList.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/include/Nazara/Core/PluginManager.hpp b/include/Nazara/Core/PluginManager.hpp index 27b65ced1..1964259c9 100644 --- a/include/Nazara/Core/PluginManager.hpp +++ b/include/Nazara/Core/PluginManager.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_PLUGINMANAGER_HPP #include +#include #include #include #include diff --git a/include/Nazara/Core/RefCounted.hpp b/include/Nazara/Core/RefCounted.hpp index a1594bec5..ed44e3e79 100644 --- a/include/Nazara/Core/RefCounted.hpp +++ b/include/Nazara/Core/RefCounted.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_REFCOUNTED_HPP #include +#include #include namespace Nz diff --git a/include/Nazara/Core/Resource.hpp b/include/Nazara/Core/Resource.hpp index 383a8c95e..fdf0b1f27 100644 --- a/include/Nazara/Core/Resource.hpp +++ b/include/Nazara/Core/Resource.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_RESOURCE_HPP #include +#include #include namespace Nz diff --git a/include/Nazara/Core/SerializationContext.hpp b/include/Nazara/Core/SerializationContext.hpp index d0b0a115b..e6554ff87 100644 --- a/include/Nazara/Core/SerializationContext.hpp +++ b/include/Nazara/Core/SerializationContext.hpp @@ -9,9 +9,9 @@ #include #include -#include -#include -#include +#include +#include +#include namespace Nz { diff --git a/include/Nazara/Core/Signal.hpp b/include/Nazara/Core/Signal.hpp deleted file mode 100644 index 49d1c10f7..000000000 --- a/include/Nazara/Core/Signal.hpp +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_SIGNAL_HPP -#define NAZARA_CORE_SIGNAL_HPP - -#include -#include -#include - -#define NazaraDetailSignal(Keyword, SignalName, ...) using SignalName ## Type = Nz::Signal<__VA_ARGS__>; \ - Keyword SignalName ## Type SignalName - -#define NazaraSignal(SignalName, ...) NazaraDetailSignal(mutable, SignalName, __VA_ARGS__) -#define NazaraStaticSignal(SignalName, ...) NazaraDetailSignal(static, SignalName, __VA_ARGS__) -#define NazaraStaticSignalImpl(Class, SignalName) Class :: SignalName ## Type Class :: SignalName - -#define NazaraSlotType(Class, SignalName) Class::SignalName ## Type::ConnectionGuard -#define NazaraSlot(Class, SignalName, SlotName) NazaraSlotType(Class, SignalName) SlotName - -namespace Nz -{ - template - class Signal - { - public: - using Callback = std::function; - class Connection; - class ConnectionGuard; - - Signal(); - Signal(const Signal&); - Signal(Signal&& signal) noexcept; - ~Signal() = default; - - void Clear(); - - Connection Connect(const Callback& func); - Connection Connect(Callback&& func); - template Connection Connect(O& object, void (O::*method)(Args...)); - template Connection Connect(O* object, void (O::*method)(Args...)); - template Connection Connect(const O& object, void (O::*method)(Args...) const); - template Connection Connect(const O* object, void (O::*method)(Args...) const); - - void operator()(Args... args) const; - - Signal& operator=(const Signal&); - Signal& operator=(Signal&& signal) noexcept; - - private: - struct Slot; - - using SlotPtr = std::shared_ptr; - using SlotList = std::vector; - using SlotListIndex = typename SlotList::size_type; - - struct Slot - { - Slot(Signal* me) : - signal(me) - { - } - - Callback callback; - Signal* signal; - SlotListIndex index; - }; - - void Disconnect(const SlotPtr& slot) noexcept; - - SlotList m_slots; - mutable SlotListIndex m_slotIterator; - }; - - template - class Signal::Connection - { - using BaseClass = Signal; - friend BaseClass; - - public: - Connection() = default; - Connection(const Connection& connection) = default; - Connection(Connection&& connection) noexcept; - ~Connection() = default; - - template - void Connect(BaseClass& signal, ConnectArgs&&... args); - void Disconnect() noexcept; - - bool IsConnected() const; - - Connection& operator=(const Connection& connection) = default; - Connection& operator=(Connection&& connection) noexcept; - - private: - Connection(const SlotPtr& slot); - - std::weak_ptr m_ptr; - }; - - template - class Signal::ConnectionGuard - { - using BaseClass = Signal; - using Connection = typename BaseClass::Connection; - - public: - ConnectionGuard() = default; - ConnectionGuard(const Connection& connection); - ConnectionGuard(const ConnectionGuard& connection) = delete; - ConnectionGuard(Connection&& connection); - ConnectionGuard(ConnectionGuard&& connection) noexcept = default; - ~ConnectionGuard(); - - template - void Connect(BaseClass& signal, ConnectArgs&&... args); - void Disconnect() noexcept; - - Connection& GetConnection(); - - bool IsConnected() const; - - ConnectionGuard& operator=(const Connection& connection); - ConnectionGuard& operator=(const ConnectionGuard& connection) = delete; - ConnectionGuard& operator=(Connection&& connection); - ConnectionGuard& operator=(ConnectionGuard&& connection) noexcept; - - private: - Connection m_connection; - }; -} - -#include - -#endif // NAZARA_CORE_SIGNAL_HPP diff --git a/include/Nazara/Core/Signal.inl b/include/Nazara/Core/Signal.inl deleted file mode 100644 index 150eed342..000000000 --- a/include/Nazara/Core/Signal.inl +++ /dev/null @@ -1,485 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Signal - * \brief Core class that represents a signal, a list of objects waiting for its message - */ - - /*! - * \brief Constructs a Signal object by default - */ - template - Signal::Signal() : - m_slotIterator(0) - { - } - - /*! - * \brief Constructs a Signal object by default - * - * \remark It doesn't make sense to copy a signal, this is only available for convenience to allow compiler-generated copy constructors - */ - template - Signal::Signal(const Signal&) : - Signal() - { - } - - /*! - * \brief Constructs a Signal object by move semantic - * - * \param signal Signal to move in this - */ - - template - Signal::Signal(Signal&& signal) noexcept - { - operator=(std::move(signal)); - } - - /*! - * \brief Clears the list of actions attached to the signal - */ - - template - void Signal::Clear() - { - m_slots.clear(); - m_slotIterator = 0; - } - - /*! - * \brief Connects a function to the signal - * \return Connection attached to the signal - * - * \param func Non-member function - */ - - template - typename Signal::Connection Signal::Connect(const Callback& func) - { - return Connect(Callback(func)); - } - - /*! - * \brief Connects a function to the signal - * \return Connection attached to the signal - * - * \param func Non-member function - */ - - template - typename Signal::Connection Signal::Connect(Callback&& func) - { - NazaraAssert(func, "Invalid function"); - - // Since we're incrementing the slot vector size, we need to replace our iterator at the end - // (Except when we are iterating on the signal) - bool resetIt = (m_slotIterator >= m_slots.size()); - - auto tempPtr = std::make_shared(this); - tempPtr->callback = std::move(func); - tempPtr->index = m_slots.size(); - - m_slots.emplace_back(std::move(tempPtr)); - - if (resetIt) - m_slotIterator = m_slots.size(); //< Replace the iterator to the end - - return Connection(m_slots.back()); - } - - /*! - * \brief Connects a member function and its object to the signal - * \return Connection attached to the signal - * - * \param object Object to send the message - * \param method Member function - */ - - template - template - typename Signal::Connection Signal::Connect(O& object, void (O::*method) (Args...)) - { - return Connect([&object, method] (Args&&... args) - { - return (object .* method) (std::forward(args)...); - }); - } - - /*! - * \brief Connects a member function and its object to the signal - * \return Connection attached to the signal - * - * \param object Object to send the message - * \param method Member function - */ - - template - template - typename Signal::Connection Signal::Connect(O* object, void (O::*method)(Args...)) - { - return Connect([object, method] (Args&&... args) - { - return (object ->* method) (std::forward(args)...); - }); - } - - /*! - * \brief Connects a member function and its object to the signal - * \return Connection attached to the signal - * - * \param object Object to send the message - * \param method Member function - */ - - template - template - typename Signal::Connection Signal::Connect(const O& object, void (O::*method) (Args...) const) - { - return Connect([&object, method] (Args&&... args) - { - return (object .* method) (std::forward(args)...); - }); - } - - /*! - * \brief Connects a member function and its object to the signal - * \return Connection attached to the signal - * - * \param object Object to send the message - * \param method Member function - */ - - template - template - typename Signal::Connection Signal::Connect(const O* object, void (O::*method)(Args...) const) - { - return Connect([object, method] (Args&&... args) - { - return (object ->* method) (std::forward(args)...); - }); - } - - /*! - * \brief Applies the list of arguments to every callback functions - * - * \param args Arguments to send with the message - */ - - template - void Signal::operator()(Args... args) const - { - for (m_slotIterator = 0; m_slotIterator < m_slots.size(); ++m_slotIterator) - m_slots[m_slotIterator]->callback(args...); - } - - /*! - * \brief Doesn't do anything - * \return A reference to this - * - * \remark This is only for convenience to allow compiled-generated assignation operator - */ - template - Signal& Signal::operator=(const Signal&) - { - return *this; - } - - /*! - * \brief Moves the signal into this - * \return A reference to this - * - * \param signal Signal to move in this - */ - template - Signal& Signal::operator=(Signal&& signal) noexcept - { - m_slots = std::move(signal.m_slots); - m_slotIterator = signal.m_slotIterator; - - // We need to update the signal pointer inside of each slot - for (SlotPtr& slot : m_slots) - slot->signal = this; - - return *this; - } - - /*! - * \brief Disconnects a listener from this signal - * - * \param slot Pointer to the ith listener of the signal - * - * \remark Produces a NazaraAssert if slot is invalid (nullptr) - * \remark Produces a NazaraAssert if index of slot is invalid - * \remark Produces a NazaraAssert if slot is not attached to this signal - */ - - template - void Signal::Disconnect(const SlotPtr& slot) noexcept - { - NazaraAssert(slot, "Invalid slot pointer"); - NazaraAssert(slot->index < m_slots.size(), "Invalid slot index"); - NazaraAssert(slot->signal == this, "Slot is not attached to this signal"); - - // "Swap this slot with the last one and pop" idiom - // This will preserve slot indexes - - // Can we safely "remove" this slot? - if (m_slotIterator >= (m_slots.size() - 1) || slot->index > m_slotIterator) - { - // Yes we can - SlotPtr& newSlot = m_slots[slot->index]; - newSlot = std::move(m_slots.back()); - newSlot->index = slot->index; //< Update the moved slot index before resizing (in case it's the last one) - } - else - { - // Nope, let's be tricky - SlotPtr& current = m_slots[m_slotIterator]; - SlotPtr& newSlot = m_slots[slot->index]; - - newSlot = std::move(current); - newSlot->index = slot->index; //< Update the moved slot index - - current = std::move(m_slots.back()); - current->index = m_slotIterator; //< Update the moved slot index - - --m_slotIterator; - } - - // Pop the last entry (from where we moved our slot) - m_slots.pop_back(); - } - - /*! - * \class Nz::Signal::Connection - * \brief Core class that represents a connection attached to a signal - */ - - /*! - * \brief Constructs a Signal::Connection object with by move semantic - * - * \param connection Connection object to move - */ - template - Signal::Connection::Connection(Connection&& connection) noexcept : - m_ptr(std::move(connection.m_ptr)) - { - connection.m_ptr.reset(); //< Fuck you GCC 4.9 - } - - /*! - * \brief Constructs a Signal::Connection object with a slot - * - * \param slot Slot of the listener - */ - - template - Signal::Connection::Connection(const SlotPtr& slot) : - m_ptr(slot) - { - } - - /*! - * \brief Connects to a signal with arguments - * - * \param signal New signal to listen - * \param args Arguments for the signal - */ - - template - template - void Signal::Connection::Connect(BaseClass& signal, ConnectArgs&&... args) - { - operator=(signal.Connect(std::forward(args)...)); - } - - /*! - * \brief Disconnects the connection from the signal - */ - - template - void Signal::Connection::Disconnect() noexcept - { - if (SlotPtr ptr = m_ptr.lock()) - ptr->signal->Disconnect(ptr); - } - - /*! - * \brief Checks whether the connection is still active with the signal - * \return true if signal is still active - */ - - template - bool Signal::Connection::IsConnected() const - { - return !m_ptr.expired(); - } - - /*! - * \brief Constructs a Signal::ConnectionGuard object by move semantic - * - * \param connection Connection to move - */ - template - typename Signal::Connection& Signal::Connection::operator=(Connection&& connection) noexcept - { - m_ptr = std::move(connection.m_ptr); - connection.m_ptr.reset(); //< Fuck you GCC 4.9 - - return *this; - } - - /*! - * \class Nz::Signal::ConnectionGuard - * \brief Core class that represents a RAII for a connection attached to a signal - */ - - /*! - * \brief Constructs a Signal::ConnectionGuard object with a connection - * - * \param connection Connection for the scope - */ - - template - Signal::ConnectionGuard::ConnectionGuard(const Connection& connection) : - m_connection(connection) - { - } - - /*! - * \brief Constructs a Signal::ConnectionGuard object with a connection by move semantic - * - * \param connection Connection for the scope - */ - - template - Signal::ConnectionGuard::ConnectionGuard(Connection&& connection) : - m_connection(std::move(connection)) - { - } - - /*! - * \brief Destructs the object and disconnects the connection - */ - - template - Signal::ConnectionGuard::~ConnectionGuard() - { - m_connection.Disconnect(); - } - - /*! - * \brief Connects to a signal with arguments - * - * \param signal New signal to listen - * \param args Arguments for the signal - */ - - template - template - void Signal::ConnectionGuard::Connect(BaseClass& signal, ConnectArgs&&... args) - { - m_connection.Disconnect(); - m_connection.Connect(signal, std::forward(args)...); - } - - /*! - * \brief Disconnects the connection from the signal - */ - - template - void Signal::ConnectionGuard::Disconnect() noexcept - { - m_connection.Disconnect(); - } - - /*! - * \brief Gets the connection attached to the signal - * \return Connection of the signal - */ - - template - typename Signal::Connection& Signal::ConnectionGuard::GetConnection() - { - return m_connection; - } - - /*! - * \brief Checks whether the connection is still active with the signal - * \return true if signal is still active - */ - - template - bool Signal::ConnectionGuard::IsConnected() const - { - return m_connection.IsConnected(); - } - - /*! - * \brief Assigns the connection into this - * \return A reference to this - * - * \param connection Connection to assign into this - */ - - template - typename Signal::ConnectionGuard& Signal::ConnectionGuard::operator=(const Connection& connection) - { - m_connection.Disconnect(); - m_connection = connection; - - return *this; - } - - /*! - * \brief Moves the Connection into this - * \return A reference to this - * - * \param connection Connection to move in this - */ - - template - typename Signal::ConnectionGuard& Signal::ConnectionGuard::operator=(Connection&& connection) - { - if (&connection != this) - { - m_connection.Disconnect(); - m_connection = std::move(connection); - } - - return *this; - } - - /*! - * \brief Moves the ConnectionGuard into this - * \return A reference to this - * - * \param connection ConnectionGuard to move in this - */ - - template - typename Signal::ConnectionGuard& Signal::ConnectionGuard::operator=(ConnectionGuard&& connection) noexcept - { - if (&connection != this) - { - m_connection.Disconnect(); - m_connection = std::move(connection.m_connection); - } - - return *this; - } -} - -#include diff --git a/include/Nazara/Core/SparsePtr.hpp b/include/Nazara/Core/SparsePtr.hpp deleted file mode 100644 index 2977cd9bc..000000000 --- a/include/Nazara/Core/SparsePtr.hpp +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_SPARSEPTR_HPP -#define NAZARA_CORE_SPARSEPTR_HPP - -///FIXME: Is SparsePtr a really good name for this class ? - -#include -#include -#include - -namespace Nz -{ - template - class SparsePtr - { - public: - using BytePtr = std::conditional_t::value, const UInt8*, UInt8*>; - using VoidPtr = std::conditional_t::value, const void*, void*>; - - SparsePtr(); - SparsePtr(T* ptr); - SparsePtr(VoidPtr ptr, int stride); - SparsePtr(VoidPtr ptr, std::size_t stride); - template SparsePtr(const SparsePtr& ptr); - SparsePtr(const SparsePtr& ptr) = default; - ~SparsePtr() = default; - - VoidPtr GetPtr() const; - int GetStride() const; - - void Reset(); - void Reset(T* ptr); - void Reset(VoidPtr ptr, int stride); - void Reset(const SparsePtr& ptr); - template void Reset(const SparsePtr& ptr); - - void SetPtr(VoidPtr ptr); - void SetStride(int stride); - - explicit operator bool() const; - explicit operator T*() const; - T& operator*() const; - T* operator->() const; - template T& operator[](U index) const; - - SparsePtr& operator=(const SparsePtr& ptr) = default; - - template SparsePtr operator+(U count) const; - template SparsePtr operator-(U count) const; - std::ptrdiff_t operator-(const SparsePtr& ptr) const; - - template SparsePtr& operator+=(U count); - template SparsePtr& operator-=(U count); - - SparsePtr& operator++(); - SparsePtr operator++(int); - - SparsePtr& operator--(); - SparsePtr operator--(int); - - bool operator==(const SparsePtr& ptr) const; - bool operator!=(const SparsePtr& ptr) const; - bool operator<(const SparsePtr& ptr) const; - bool operator>(const SparsePtr& ptr) const; - bool operator<=(const SparsePtr& ptr) const; - bool operator>=(const SparsePtr& ptr) const; - - private: - BytePtr m_ptr; - int m_stride; - }; -} - -#include - -#endif // NAZARA_CORE_SPARSEPTR_HPP diff --git a/include/Nazara/Core/SparsePtr.inl b/include/Nazara/Core/SparsePtr.inl deleted file mode 100644 index d153413a9..000000000 --- a/include/Nazara/Core/SparsePtr.inl +++ /dev/null @@ -1,483 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::SparsePtr - * \brief Core class that represents a pointer and the step between two elements - */ - - /*! - * \brief Constructs a SparsePtr object by default - */ - - template - SparsePtr::SparsePtr() - { - Reset(); - } - - /*! - * \brief Constructs a SparsePtr object with a pointer - * - * \param ptr Pointer to data - */ - - template - SparsePtr::SparsePtr(T* ptr) - { - Reset(ptr); - } - - /*! - * \brief Constructs a SparsePtr object with a pointer and a step - * - * \param ptr Pointer to data - * \param stride Step between two elements - */ - - template - SparsePtr::SparsePtr(VoidPtr ptr, int stride) - { - Reset(ptr, stride); - } - - /*! - * \brief Constructs a SparsePtr object with a pointer and a step - * - * \param ptr Pointer to data - * \param stride Step between two elements - * - * \remark This constructor only exists because std::size_t is a frequent type for constructing this object, but stride may not be higher than int max - */ - - template - SparsePtr::SparsePtr(VoidPtr ptr, std::size_t stride) - { - assert(stride <= static_cast(std::numeric_limits::max())); - Reset(ptr, static_cast(stride)); - } - - /*! - * \brief Constructs a SparsePtr object from another type of SparsePtr - * - * \param ptr Pointer to data of type U to convert to type T - */ - - template - template - SparsePtr::SparsePtr(const SparsePtr& ptr) - { - Reset(ptr); - } - - /*! - * \brief Gets the original pointer - * \return Pointer to the first data - */ - - template - typename SparsePtr::VoidPtr SparsePtr::GetPtr() const - { - return m_ptr; - } - - /*! - * \brief Gets the stride - * \return Step between two elements - */ - - template - int SparsePtr::GetStride() const - { - return m_stride; - } - - /*! - * \brief Resets the SparsePtr - */ - - template - void SparsePtr::Reset() - { - SetPtr(nullptr); - SetStride(0); - } - - /*! - * \brief Resets the SparsePtr with a pointer - * - * \param ptr Pointer to data - * - * \remark stride is set to sizeof(T) - */ - - template - void SparsePtr::Reset(T* ptr) - { - SetPtr(ptr); - SetStride(sizeof(T)); - } - - /*! - * \brief Resets the SparsePtr with a pointer and its stride - * - * \param ptr Pointer to data - * \param stride Step between two elements - */ - - template - void SparsePtr::Reset(VoidPtr ptr, int stride) - { - SetPtr(ptr); - SetStride(stride); - } - - /*! - * \brief Resets the SparsePtr with another SparsePtr - * - * \param ptr Another sparsePtr - */ - - template - void SparsePtr::Reset(const SparsePtr& ptr) - { - SetPtr(ptr.GetPtr()); - SetStride(ptr.GetStride()); - } - - /*! - * \brief Resets the SparsePtr with another type of SparsePtr - * - * \param ptr Another sparsePtr - */ - - template - template - void SparsePtr::Reset(const SparsePtr& ptr) - { - static_assert(std::is_convertible::value, "Source type pointer cannot be implicitly converted to target type pointer"); - - SetPtr(static_cast(ptr.GetPtr())); - SetStride(ptr.GetStride()); - } - - /*! - * \brief Sets the pointer - * - * \param ptr Pointer to data - */ - - template - void SparsePtr::SetPtr(VoidPtr ptr) - { - m_ptr = static_cast(ptr); - } - - /*! - * \brief Sets the stride - * - * \param stride Step between two elements - */ - - template - void SparsePtr::SetStride(int stride) - { - m_stride = stride; - } - - /*! - * \brief Converts the pointer to bool - * \return true if pointer is not nullptr - */ - - template - SparsePtr::operator bool() const - { - return m_ptr != nullptr; - } - - /*! - * \brief Converts the pointer to a pointer to the value - * \return The value of the pointer - */ - - template - SparsePtr::operator T*() const - { - return reinterpret_cast(m_ptr); - } - - /*! - * \brief Dereferences the pointer - * \return The dereferencing of the pointer - */ - - template - T& SparsePtr::operator*() const - { - return *reinterpret_cast(m_ptr); - } - - /*! - * \brief Dereferences the pointer - * \return The dereferencing of the pointer - */ - - template - T* SparsePtr::operator->() const - { - return reinterpret_cast(m_ptr); - } - - /*! - * \brief Gets the ith element of the stride pointer - * \return A reference to the ith value - * - * \param index Number of stride to do - */ - - template - template - T& SparsePtr::operator[](U index) const - { - static_assert(std::is_integral_v, "index must be an integral type"); - - return *reinterpret_cast(m_ptr + index * m_stride); - } - - /*! - * \brief Gets the SparsePtr with an offset - * \return A SparsePtr with the new stride - * - * \param count Number of stride to do - */ - - template - template - SparsePtr SparsePtr::operator+(U count) const - { - static_assert(std::is_integral_v, "count must be an integral type"); - - return SparsePtr(m_ptr + count * m_stride, m_stride); - } - - /*! - * \brief Gets the SparsePtr with an offset - * \return A SparsePtr with the new stride - * - * \param count Number of stride to do - */ - - template - template - SparsePtr SparsePtr::operator-(U count) const - { - static_assert(std::is_integral_v, "count must be an integral type"); - - return SparsePtr(m_ptr - count * m_stride, m_stride); - } - - /*! - * \brief Gets the difference between the two SparsePtr - * \return The difference of elements: ptr - this->ptr - * - * \param ptr Other ptr - */ - - template - std::ptrdiff_t SparsePtr::operator-(const SparsePtr& ptr) const - { - return (m_ptr - ptr.m_ptr) / m_stride; - } - - /*! - * \brief Gets the SparsePtr with an offset - * \return A reference to this pointer with the new stride - * - * \param count Number of stride to do - */ - - template - template - SparsePtr& SparsePtr::operator+=(U count) - { - static_assert(std::is_integral_v, "count must be an integral type"); - - m_ptr += count * m_stride; - return *this; - } - - template - template - SparsePtr& SparsePtr::operator-=(U count) - { - static_assert(std::is_integral_v, "count must be an integral type"); - - m_ptr -= count * m_stride; - return *this; - } - - /*! - * \brief Gets the SparsePtr with the next element - * \return A reference to this pointer updated - */ - - template - SparsePtr& SparsePtr::operator++() - { - m_ptr += m_stride; - - return *this; - } - - /*! - * \brief Gets the SparsePtr with the next element - * \return A SparsePtr not updated - */ - - template - SparsePtr SparsePtr::operator++(int) - { - // We copy the object - SparsePtr tmp(*this); - - // We modify it - operator++(); - - // We return the copy - return tmp; - } - - /*! - * \brief Gets the SparsePtr with the previous element - * \return A reference to this pointer updated - */ - - template - SparsePtr& SparsePtr::operator--() - { - m_ptr -= m_stride; - return *this; - } - - /*! - * \brief Gets the SparsePtr with the previous element - * \return A SparsePtr not updated - */ - - template - SparsePtr SparsePtr::operator--(int) - { - // We copy the object - SparsePtr tmp(*this); - - // We modify it - operator--(); - - // We return the copy - return tmp; - } - - /*! - * \brief Compares the SparsePtr to another one - * \return true if the two SparsePtr are pointing to the same memory - * - * \param ptr Other SparsePtr to compare with - */ - - template - bool SparsePtr::operator==(const SparsePtr& ptr) const - { - return m_ptr == ptr.m_ptr; - } - - /*! - * \brief Compares the SparsePtr to another one - * \return false if the two SparsePtr are pointing to the same memory - * - * \param ptr Other SparsePtr to compare with - */ - - template - bool SparsePtr::operator!=(const SparsePtr& ptr) const - { - return m_ptr != ptr.m_ptr; - } - - /*! - * \brief Compares the SparsePtr to another one - * \return true if the first SparsePtr is pointing to memory inferior to the second one - * - * \param ptr Other SparsePtr to compare with - */ - - template - bool SparsePtr::operator<(const SparsePtr& ptr) const - { - return m_ptr < ptr.m_ptr; - } - - /*! - * \brief Compares the SparsePtr to another one - * \return true if the first SparsePtr is pointing to memory superior to the second one - * - * \param ptr Other SparsePtr to compare with - */ - - template - bool SparsePtr::operator>(const SparsePtr& ptr) const - { - return m_ptr > ptr.m_ptr; - } - - /*! - * \brief Compares the SparsePtr to another one - * \return true if the first SparsePtr is pointing to memory inferior or equal to the second one - * - * \param ptr Other SparsePtr to compare with - */ - - template - bool SparsePtr::operator<=(const SparsePtr& ptr) const - { - return m_ptr <= ptr.m_ptr; - } - - /*! - * \brief Compares the SparsePtr to another one - * \return true if the first SparsePtr is pointing to memory superior or equal to the second one - * - * \param ptr Other SparsePtr to compare with - */ - - template - bool SparsePtr::operator>=(const SparsePtr& ptr) const - { - return m_ptr >= ptr.m_ptr; - } -} - -namespace std -{ - template - struct iterator_traits> - { - using difference_type = ptrdiff_t; - using iterator_category = random_access_iterator_tag; - using reference = const T&; - using pointer = const T*; - using value_type = T; - }; -} - -#include diff --git a/include/Nazara/Core/StackArray.hpp b/include/Nazara/Core/StackArray.hpp deleted file mode 100644 index 49db9bf3a..000000000 --- a/include/Nazara/Core/StackArray.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_STACKARRAY_HPP -#define NAZARA_CORE_STACKARRAY_HPP - -#include -#include - -#ifdef NAZARA_ALLOCA_SUPPORT - #define NazaraStackArray(T, size) Nz::StackArray(static_cast(NAZARA_ALLOCA((size) * sizeof(T))), size) - #define NazaraStackArrayNoInit(T, size) Nz::StackArray(static_cast(NAZARA_ALLOCA((size) * sizeof(T))), size, typename Nz::StackArray::NoInitTag()) -#else - #define NazaraStackArray(T, size) Nz::StackArray(static_cast(Nz::OperatorNew((size) * sizeof(T))), size) - #define NazaraStackArrayNoInit(T, size) Nz::StackArray(static_cast(Nz::OperatorNew((size) * sizeof(T))), size, typename Nz::StackArray::NoInitTag()) -#endif - -#include -#include - -namespace Nz -{ - template - class StackArray - { - public: - struct NoInitTag {}; - - using value_type = T; - using const_iterator = const value_type*; - using const_pointer = const value_type*; - using const_reference = const value_type&; - using const_reverse_iterator = std::reverse_iterator; - using difference_type = std::ptrdiff_t; - using iterator = value_type*; - using pointer = value_type*; - using reference = value_type&; - using reverse_iterator = std::reverse_iterator; - using size_type = std::size_t; - - StackArray(); - StackArray(T* stackMemory, std::size_t size); - StackArray(T* stackMemory, std::size_t size, NoInitTag); - StackArray(const StackArray&) = delete; - StackArray(StackArray&&) = default; - ~StackArray(); - - reference back(); - const_reference back() const; - - iterator begin() noexcept; - const_iterator begin() const noexcept; - - const_iterator cbegin() const noexcept; - const_iterator cend() const noexcept; - const_reverse_iterator crbegin() const noexcept; - const_reverse_iterator crend() const noexcept; - - T* data() noexcept; - const T* data() const noexcept; - - bool empty() const noexcept; - - iterator end() noexcept; - const_iterator end() const noexcept; - - void fill(const T& value); - - reference front() noexcept; - const_reference front() const noexcept; - - size_type max_size() const noexcept; - - reverse_iterator rbegin() noexcept; - const_reverse_iterator rbegin() const noexcept; - - reverse_iterator rend() noexcept; - const_reverse_iterator rend() const noexcept; - - size_type size() const noexcept; - - reference operator[](size_type pos); - const_reference operator[](size_type pos) const; - - StackArray& operator=(const StackArray&) = delete; - StackArray& operator=(StackArray&&) = default; - - private: - std::size_t m_size; - MovablePtr m_ptr; - }; - -} - -#include - -#endif // NAZARA_CORE_STACKARRAY_HPP diff --git a/include/Nazara/Core/StackArray.inl b/include/Nazara/Core/StackArray.inl deleted file mode 100644 index 54fae4327..000000000 --- a/include/Nazara/Core/StackArray.inl +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// I'm not proud of those five following lines but ti's hard to do with another way now -#ifdef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION - #define NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION_DEFINED -#else - #define NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION -#endif - -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::StackArray - * \brief Core class that represents a stack-allocated (if alloca is present) array - */ - - template - StackArray::StackArray() : - m_size(0), - m_ptr(nullptr) - { - } - - template - StackArray::StackArray(T* stackMemory, std::size_t size) : - m_size(size), - m_ptr(stackMemory) - { - for (std::size_t i = 0; i < m_size; ++i) - PlacementNew(&m_ptr[i]); - } - - template - StackArray::StackArray(T* stackMemory, std::size_t size, NoInitTag) : - m_size(size), - m_ptr(stackMemory) - { - } - - template - StackArray::~StackArray() - { - for (std::size_t i = 0; i < m_size; ++i) - PlacementDestroy(&m_ptr[i]); - - #ifndef NAZARA_ALLOCA_SUPPORT - OperatorDelete(m_ptr); - #endif - } - - template - typename StackArray::reference StackArray::back() - { - assert(m_size != 0); - return m_ptr[m_size - 1]; - } - - template - typename StackArray::const_reference StackArray::back() const - { - assert(m_size != 0); - return m_ptr[m_size - 1]; - } - - template - typename StackArray::iterator StackArray::begin() noexcept - { - return iterator(&m_ptr[0]); - } - - template - typename StackArray::const_iterator StackArray::begin() const noexcept - { - return const_iterator(&m_ptr[0]); - } - - template - typename StackArray::const_iterator StackArray::cbegin() const noexcept - { - return const_iterator(&m_ptr[0]); - } - - template - typename StackArray::const_iterator StackArray::cend() const noexcept - { - return const_iterator(&m_ptr[m_size]); - } - - template - typename StackArray::const_reverse_iterator StackArray::crbegin() const noexcept - { - return const_reverse_iterator(&m_ptr[m_size]); - } - - template - typename StackArray::const_reverse_iterator StackArray::crend() const noexcept - { - return const_reverse_iterator(&m_ptr[0]); - } - - template - T* StackArray::data() noexcept - { - return m_ptr; - } - - template - const T* StackArray::data() const noexcept - { - return m_ptr; - } - - template - bool StackArray::empty() const noexcept - { - return m_size == 0; - } - - template - typename StackArray::iterator StackArray::end() noexcept - { - return iterator(&m_ptr[m_size]); - } - - template - typename StackArray::const_iterator StackArray::end() const noexcept - { - return const_iterator(&m_ptr[m_size]); - } - - template - void StackArray::fill(const T& value) - { - std::fill(begin(), end(), value); - } - - template - typename StackArray::reference StackArray::front() noexcept - { - return m_ptr[0]; - } - - template - typename StackArray::const_reference StackArray::front() const noexcept - { - return m_ptr[0]; - } - - template - typename StackArray::size_type StackArray::max_size() const noexcept - { - return size(); - } - - template - typename StackArray::reverse_iterator StackArray::rbegin() noexcept - { - return reverse_iterator(&m_ptr[m_size]); - } - - template - typename StackArray::const_reverse_iterator StackArray::rbegin() const noexcept - { - return reverse_iterator(&m_ptr[m_size]); - } - - template - typename StackArray::reverse_iterator StackArray::rend() noexcept - { - return reverse_iterator(&m_ptr[0]); - } - - template - typename StackArray::const_reverse_iterator StackArray::rend() const noexcept - { - return reverse_iterator(&m_ptr[0]); - } - - template - typename StackArray::size_type StackArray::size() const noexcept - { - return m_size; - } - - template - typename StackArray::reference StackArray::operator[](size_type pos) - { - assert(pos < m_size); - return m_ptr[pos]; - } - - template - typename StackArray::const_reference StackArray::operator[](size_type pos) const - { - assert(pos < m_size); - return m_ptr[pos]; - } -} - -#include - -// If we have defined the constant, then we have to undefine it (to avoid bloating in the engine) -#ifndef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION_DEFINED - #undef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION -#endif diff --git a/include/Nazara/Core/StackVector.hpp b/include/Nazara/Core/StackVector.hpp deleted file mode 100644 index 67bbd15ad..000000000 --- a/include/Nazara/Core/StackVector.hpp +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_STACKVECTOR_HPP -#define NAZARA_CORE_STACKVECTOR_HPP - -#include -#include - -#ifdef NAZARA_ALLOCA_SUPPORT - #define NazaraStackVector(T, capacity) Nz::StackVector(static_cast(NAZARA_ALLOCA((capacity) * sizeof(T))), capacity) -#else - #define NazaraStackVector(T, capacity) Nz::StackVector(static_cast(Nz::OperatorNew((capacity) * sizeof(T))), capacity) -#endif - -#include -#include -#include - -namespace Nz -{ - template - class StackVector - { - public: - using value_type = T; - using const_iterator = const value_type*; - using const_pointer = const value_type*; - using const_reference = const value_type&; - using const_reverse_iterator = std::reverse_iterator; - using difference_type = std::ptrdiff_t; - using iterator = value_type*; - using pointer = value_type*; - using reference = value_type&; - using reverse_iterator = std::reverse_iterator; - using size_type = std::size_t; - - StackVector(); - StackVector(T* stackMemory, std::size_t capacity); - StackVector(const StackVector&) = delete; - StackVector(StackVector&&) = default; - ~StackVector(); - - reference back(); - const_reference back() const; - - iterator begin() noexcept; - const_iterator begin() const noexcept; - - size_type capacity() const noexcept; - - void clear() noexcept; - - const_iterator cbegin() const noexcept; - const_iterator cend() const noexcept; - const_reverse_iterator crbegin() const noexcept; - const_reverse_iterator crend() const noexcept; - - T* data() noexcept; - const T* data() const noexcept; - - template - iterator emplace(const_iterator pos, Args&&... args); - - template - reference emplace_back(Args&&... args); - - bool empty() const noexcept; - - iterator end() noexcept; - const_iterator end() const noexcept; - - iterator erase(const_iterator pos); - iterator erase(const_iterator first, const_iterator last); - - reference front() noexcept; - const_reference front() const noexcept; - - iterator insert(const_iterator pos, const T& value); - iterator insert(const_iterator pos, T&& value); - - size_type max_size() const noexcept; - - reference push_back(const T& value) noexcept(std::is_nothrow_copy_constructible::value); - reference push_back(T&& value) noexcept(std::is_nothrow_move_constructible::value); - - void pop_back(); - - void resize(size_type count); - void resize(size_type count, const value_type& value); - - reverse_iterator rbegin() noexcept; - const_reverse_iterator rbegin() const noexcept; - - reverse_iterator rend() noexcept; - const_reverse_iterator rend() const noexcept; - - size_type size() const noexcept; - - reference operator[](size_type pos); - const_reference operator[](size_type pos) const; - - StackVector& operator=(const StackVector&) = delete; - StackVector& operator=(StackVector&&) = default; - - private: - std::size_t m_capacity; - std::size_t m_size; - MovablePtr m_ptr; - }; - -} - -#include - -#endif // NAZARA_CORE_STACKVECTOR_HPP diff --git a/include/Nazara/Core/StackVector.inl b/include/Nazara/Core/StackVector.inl deleted file mode 100644 index 8ba7a7195..000000000 --- a/include/Nazara/Core/StackVector.inl +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// I'm not proud of those five following lines but ti's hard to do with another way now -#ifdef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION - #define NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION_DEFINED -#else - #define NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION -#endif - -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::StackVector - * \brief Core class that represents a stack-allocated (if alloca is present) vector, that is with a capacity different from its size - */ - template - StackVector::StackVector() : - m_capacity(0), - m_size(0), - m_ptr(nullptr) - { - } - - template - StackVector::StackVector(T* stackMemory, std::size_t capacity) : - m_capacity(capacity), - m_size(0), - m_ptr(stackMemory) - { - } - - template - StackVector::~StackVector() - { - clear(); - - #ifndef NAZARA_ALLOCA_SUPPORT - OperatorDelete(m_ptr); - #endif - } - - template - typename StackVector::reference StackVector::back() - { - assert(m_size != 0); - return m_ptr[m_size - 1]; - } - - template - typename StackVector::const_reference StackVector::back() const - { - assert(m_size != 0); - return m_ptr[m_size - 1]; - } - - template - typename StackVector::iterator StackVector::begin() noexcept - { - return iterator(&m_ptr[0]); - } - - template - typename StackVector::const_iterator StackVector::begin() const noexcept - { - return const_iterator(&m_ptr[0]); - } - - template - typename StackVector::size_type StackVector::capacity() const noexcept - { - return m_capacity; - } - - template - void StackVector::clear() noexcept - { - resize(0); - } - - template - typename StackVector::const_iterator StackVector::cbegin() const noexcept - { - return const_iterator(&m_ptr[0]); - } - - template - typename StackVector::const_iterator StackVector::cend() const noexcept - { - return const_iterator(&m_ptr[m_size]); - } - - template - typename StackVector::const_reverse_iterator StackVector::crbegin() const noexcept - { - return const_reverse_iterator(&m_ptr[m_size]); - } - - template - typename StackVector::const_reverse_iterator StackVector::crend() const noexcept - { - return const_reverse_iterator(&m_ptr[0]); - } - - template - T* StackVector::data() noexcept - { - return m_ptr; - } - - template - const T* StackVector::data() const noexcept - { - return m_ptr; - } - - template - template - typename StackVector::iterator StackVector::emplace(const_iterator pos, Args&& ...args) - { - assert(m_size < m_capacity); - assert(pos >= begin() && pos <= end()); - - std::size_t index = std::distance(cbegin(), pos); - if (pos < end()) - { - iterator lastElement = end() - 1; - PlacementNew(&m_ptr[m_size], std::move(*lastElement)); - - if (&m_ptr[index] < lastElement) - std::move_backward(&m_ptr[index], &m_ptr[m_size - 1], &m_ptr[m_size]); - - PlacementDestroy(&m_ptr[index]); - } - m_size++; - - return PlacementNew(&m_ptr[index], std::forward(args)...); - } - - template - template - typename StackVector::reference Nz::StackVector::emplace_back(Args&&... args) - { - assert(m_size < m_capacity); - return *PlacementNew(&m_ptr[m_size++], std::forward(args)...); - } - - template - bool StackVector::empty() const noexcept - { - return m_size == 0; - } - - template - typename StackVector::iterator StackVector::end() noexcept - { - return iterator(&m_ptr[m_size]); - } - - template - typename StackVector::const_iterator StackVector::end() const noexcept - { - return const_iterator(&m_ptr[m_size]); - } - - template - typename StackVector::iterator StackVector::erase(const_iterator pos) - { - assert(pos < end()); - std::size_t index = std::distance(cbegin(), pos); - std::move(begin() + index + 1, end(), begin() + index); - pop_back(); - - return iterator(&m_ptr[index]); - } - - template - typename StackVector::iterator StackVector::erase(const_iterator first, const_iterator last) - { - std::size_t index = std::distance(cbegin(), first); - - if (first == last) - return begin() + index; - - assert(first < last); - assert(first >= begin() && last <= end()); - - std::size_t count = std::distance(first, last); - - std::move(begin() + index + count, end(), begin() + index); - resize(size() - count); - - return iterator(&m_ptr[index]); - } - - template - typename StackVector::reference StackVector::front() noexcept - { - return m_ptr[0]; - } - - template - typename StackVector::const_reference StackVector::front() const noexcept - { - return m_ptr[0]; - } - - template - typename StackVector::iterator StackVector::insert(const_iterator pos, const T& value) - { - return emplace(pos, value); - } - - template - typename StackVector::iterator StackVector::insert(const_iterator pos, T&& value) - { - return emplace(pos, std::move(value)); - } - - template - typename StackVector::size_type StackVector::max_size() const noexcept - { - return capacity(); - } - - template - typename StackVector::reference StackVector::push_back(const T& value) noexcept(std::is_nothrow_copy_constructible::value) - { - assert(m_size < m_capacity); - return *PlacementNew(&m_ptr[m_size++], value); - } - - template - typename StackVector::reference StackVector::push_back(T&& value) noexcept(std::is_nothrow_move_constructible::value) - { - assert(m_size < m_capacity); - return *PlacementNew(&m_ptr[m_size++], std::move(value)); - } - - template - void StackVector::pop_back() - { - assert(!empty()); - PlacementDestroy(&m_ptr[--m_size]); - } - - template - void StackVector::resize(size_type count) - { - assert(count <= m_capacity); - if (count > m_size) - { - for (std::size_t i = m_size; i < count; ++i) - PlacementNew(&m_ptr[i]); - - m_size = count; - } - else if (count < m_size) - { - for (std::size_t i = count; i < m_size; ++i) - PlacementDestroy(&m_ptr[i]); - - m_size = count; - } - } - - template - void StackVector::resize(size_type count, const value_type& value) - { - assert(count <= m_capacity); - if (count > m_size) - { - for (std::size_t i = m_size; i < count; ++i) - PlacementNew(&m_ptr[i], value); - - m_size = count; - } - else if (count < m_size) - { - for (std::size_t i = count; i < m_size; ++i) - PlacementDestroy(&m_ptr[i]); - - m_size = count; - } - } - - template - typename StackVector::reverse_iterator StackVector::rbegin() noexcept - { - return reverse_iterator(&m_ptr[m_size]); - } - - template - typename StackVector::const_reverse_iterator StackVector::rbegin() const noexcept - { - return reverse_iterator(&m_ptr[m_size]); - } - - template - typename StackVector::reverse_iterator StackVector::rend() noexcept - { - return reverse_iterator(&m_ptr[0]); - } - - template - typename StackVector::const_reverse_iterator StackVector::rend() const noexcept - { - return reverse_iterator(&m_ptr[0]); - } - - template - typename StackVector::size_type StackVector::size() const noexcept - { - return m_size; - } - - template - typename StackVector::reference StackVector::operator[](size_type pos) - { - assert(pos < m_size); - return m_ptr[pos]; - } - - template - typename StackVector::const_reference StackVector::operator[](size_type pos) const - { - assert(pos < m_size); - return m_ptr[pos]; - } -} - -#include - -// If we have defined the constant, then we have to undefine it (to avoid bloating in the engine) -#ifndef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION_DEFINED - #undef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION -#endif diff --git a/include/Nazara/Core/Stream.hpp b/include/Nazara/Core/Stream.hpp index cbb3f1b95..821f44999 100644 --- a/include/Nazara/Core/Stream.hpp +++ b/include/Nazara/Core/Stream.hpp @@ -8,8 +8,9 @@ #define NAZARA_CORE_STREAM_HPP #include -#include +#include #include +#include #include #include #include diff --git a/include/Nazara/Core/TypeList.hpp b/include/Nazara/Core/TypeList.hpp deleted file mode 100644 index 860a0f556..000000000 --- a/include/Nazara/Core/TypeList.hpp +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_TYPELIST_HPP -#define NAZARA_CORE_TYPELIST_HPP - -#include - -namespace Nz -{ - template struct TypeList {}; - - namespace Detail - { - template - struct ListAppend; - - template typename> - struct ListApply; - - template - struct ListAt; - - template - struct ListConcat; - - template - struct ListFind; - - template typename> - struct ListInstantiate; - - template - struct ListPrepend; - - template - struct ListSize; - - template - struct ListUnique; - } - - template - using TypeListAppend = typename Detail::ListAppend::Result; - - template typename Functor, typename... Args> - void TypeListApply(Args&&... args); - - template - using TypeListAt = typename Detail::ListAt::Type; - - template - using TypeListConcat = typename Detail::ListConcat::Result; - - template - constexpr bool TypeListEmpty = Detail::ListSize::Size == 0; - - template - constexpr bool TypeListFind = Detail::ListFind::Find(); - - template typename Class> - using TypeListInstantiate = typename Detail::ListInstantiate::Result; - - template - using TypeListPrepend = typename Detail::ListPrepend::Result; - - template - constexpr std::size_t TypeListSize = Detail::ListSize::Size; - - template - using TypeListUnique = typename Detail::ListUnique, List>::Result; -} - -#include - -#endif // NAZARA_CORE_TYPELIST_HPP diff --git a/include/Nazara/Core/TypeList.inl b/include/Nazara/Core/TypeList.inl deleted file mode 100644 index b06441f87..000000000 --- a/include/Nazara/Core/TypeList.inl +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz -{ - namespace Detail - { - template - struct ListAppend, NewType> - { - using Result = TypeList; - }; - - - template typename Functor, typename T, typename... ListTypes> - struct ListApply, Functor> - { - template - static void Apply(Args&&... args) - { - Functor()(std::forward(args)...); - if constexpr (sizeof...(ListTypes) > 0) - ListApply, Functor>::Apply(std::forward(args)...); - } - }; - - template - struct ListAt, 0> - { - using Type = T; - }; - - template - struct ListAt, Index> - { - static_assert(Index <= sizeof...(ListTypes), "Index out of range"); - - using Type = typename ListAt, Index - 1>::Type; - }; - - - template - struct ListConcat, TypeList> - { - using Result = TypeList; - }; - - - struct ListFindHelper - { - template static constexpr bool Find() - { - if constexpr (std::is_same_v) - return true; - else - return Find(); - } - - template static constexpr bool Find() - { - return false; - } - }; - - template - struct ListFind, TypeToFind> - { - static constexpr bool Find() - { - return ListFindHelper::Find(); - } - }; - - - template typename Class, typename... ListTypes> - struct ListInstantiate, Class> - { - using Result = Class; - }; - - - template - struct ListPrepend, NewType> - { - using Result = TypeList; - }; - - - template - struct ListSize> - { - static constexpr std::size_t Size = sizeof...(ListTypes); - }; - - - template - struct ListUnique, TypeList> - { - static constexpr bool IsTypePresent = ListFind, T1>::Find(); - using Result = std::conditional_t, TypeList>; - }; - - template - struct ListUnique, TypeList> - { - using Result = typename ListUnique, TypeList>::Result, TypeList>::Result; - }; - } - - template typename Functor, typename... Args> - void TypeListApply(Args&&... args) - { - if constexpr (!TypeListEmpty) - Detail::ListApply::Apply(std::forward(args)...); - } -} - -#include diff --git a/include/Nazara/Core/TypeTag.hpp b/include/Nazara/Core/TypeTag.hpp deleted file mode 100644 index bf3add334..000000000 --- a/include/Nazara/Core/TypeTag.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CORE_TYPETAG_HPP -#define NAZARA_CORE_TYPETAG_HPP - -namespace Nz -{ - template - struct TypeTag - { - using Type = T; - }; -} - -#endif // NAZARA_CORE_TYPETAG_HPP diff --git a/include/Nazara/Core/Updatable.hpp b/include/Nazara/Core/Updatable.hpp index c6c2f42f3..1aafd081e 100644 --- a/include/Nazara/Core/Updatable.hpp +++ b/include/Nazara/Core/Updatable.hpp @@ -8,6 +8,7 @@ #define NAZARA_CORE_UPDATABLE_HPP #include +#include namespace Nz { diff --git a/include/Nazara/Graphics/BasicMaterial.hpp b/include/Nazara/Graphics/BasicMaterial.hpp index 830b3be19..a16601f50 100644 --- a/include/Nazara/Graphics/BasicMaterial.hpp +++ b/include/Nazara/Graphics/BasicMaterial.hpp @@ -10,10 +10,13 @@ #include #include -namespace Nz +namespace nzsl { class FieldOffsets; +} +namespace Nz +{ class NAZARA_GRAPHICS_API BasicMaterial { friend class MaterialPipeline; @@ -94,7 +97,7 @@ namespace Nz static MaterialSettings::Builder Build(BasicBuildOptions& options); static std::vector> BuildShaders(); - static std::pair BuildUniformOffsets(); + static std::pair BuildUniformOffsets(); std::size_t m_uniformBlockIndex; BasicOptionIndexes m_basicOptionIndexes; diff --git a/include/Nazara/Graphics/BasicMaterial.inl b/include/Nazara/Graphics/BasicMaterial.inl index 879c31347..8c7f3b742 100644 --- a/include/Nazara/Graphics/BasicMaterial.inl +++ b/include/Nazara/Graphics/BasicMaterial.inl @@ -62,7 +62,7 @@ namespace Nz { NazaraAssert(HasAlphaTest(), "Material has no alpha test option"); const auto& optionOpt = m_material.GetOptionValue(m_basicOptionIndexes.alphaTest); - if (std::holds_alternative(optionOpt)) + if (std::holds_alternative(optionOpt)) return false; return std::get(optionOpt); diff --git a/include/Nazara/Graphics/Enums.hpp b/include/Nazara/Graphics/Enums.hpp index 0ba6941ec..fb2be51f0 100644 --- a/include/Nazara/Graphics/Enums.hpp +++ b/include/Nazara/Graphics/Enums.hpp @@ -8,7 +8,7 @@ #define NAZARA_GRAPHICS_ENUMS_HPP #include -#include +#include namespace Nz { diff --git a/include/Nazara/Graphics/ForwardFramePipeline.hpp b/include/Nazara/Graphics/ForwardFramePipeline.hpp index d52df65fa..b1871348c 100644 --- a/include/Nazara/Graphics/ForwardFramePipeline.hpp +++ b/include/Nazara/Graphics/ForwardFramePipeline.hpp @@ -8,7 +8,6 @@ #define NAZARA_GRAPHICS_FORWARDFRAMEPIPELINE_HPP #include -#include #include #include #include @@ -22,6 +21,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Graphics/Graphics.hpp b/include/Nazara/Graphics/Graphics.hpp index 48e7de553..3a4eac097 100644 --- a/include/Nazara/Graphics/Graphics.hpp +++ b/include/Nazara/Graphics/Graphics.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include namespace Nz @@ -46,7 +46,7 @@ namespace Nz inline const std::shared_ptr& GetRenderDevice() const; inline const RenderPassCache& GetRenderPassCache() const; inline TextureSamplerCache& GetSamplerCache(); - inline const std::shared_ptr& GetShaderModuleResolver() const; + inline const std::shared_ptr& GetShaderModuleResolver() const; struct Config { @@ -70,7 +70,7 @@ namespace Nz std::optional m_renderPassCache; std::optional m_samplerCache; - std::shared_ptr m_shaderModuleResolver; + std::shared_ptr m_shaderModuleResolver; std::shared_ptr m_fullscreenVertexBuffer; std::shared_ptr m_renderDevice; std::shared_ptr m_blitPipeline; diff --git a/include/Nazara/Graphics/Graphics.inl b/include/Nazara/Graphics/Graphics.inl index d67184ee4..2241d19c4 100644 --- a/include/Nazara/Graphics/Graphics.inl +++ b/include/Nazara/Graphics/Graphics.inl @@ -63,7 +63,7 @@ namespace Nz return *m_samplerCache; } - inline const std::shared_ptr& Graphics::GetShaderModuleResolver() const + inline const std::shared_ptr& Graphics::GetShaderModuleResolver() const { return m_shaderModuleResolver; } diff --git a/include/Nazara/Graphics/InstancedRenderable.hpp b/include/Nazara/Graphics/InstancedRenderable.hpp index 5887ce40f..230e33944 100644 --- a/include/Nazara/Graphics/InstancedRenderable.hpp +++ b/include/Nazara/Graphics/InstancedRenderable.hpp @@ -8,9 +8,9 @@ #define NAZARA_GRAPHICS_INSTANCEDRENDERABLE_HPP #include -#include #include #include +#include #include namespace Nz diff --git a/include/Nazara/Graphics/Light.hpp b/include/Nazara/Graphics/Light.hpp index 74cf74319..817fa942e 100644 --- a/include/Nazara/Graphics/Light.hpp +++ b/include/Nazara/Graphics/Light.hpp @@ -8,11 +8,11 @@ #define NAZARA_GRAPHICS_LIGHT_HPP #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/include/Nazara/Graphics/MaterialPass.hpp b/include/Nazara/Graphics/MaterialPass.hpp index 2cd6b9179..b77944043 100644 --- a/include/Nazara/Graphics/MaterialPass.hpp +++ b/include/Nazara/Graphics/MaterialPass.hpp @@ -14,14 +14,14 @@ #include #include #include -#include #include #include #include #include #include -#include #include +#include +#include #include #include #include @@ -67,13 +67,13 @@ namespace Nz inline FaceFilling GetFaceFilling() const; inline MaterialPassFlags GetFlags() const; inline float GetLineWidth() const; - inline const ShaderAst::ConstantValue& GetOptionValue(std::size_t optionIndex) const; + inline const nzsl::Ast::ConstantValue& GetOptionValue(std::size_t optionIndex) const; inline const std::shared_ptr& GetPipeline() const; inline const MaterialPipelineInfo& GetPipelineInfo() const; inline float GetPointSize() const; inline PrimitiveMode GetPrimitiveMode() const; inline const std::shared_ptr& GetSettings() const; - inline const std::shared_ptr& GetShader(ShaderStageType shaderStage) const; + inline const std::shared_ptr& GetShader(nzsl::ShaderStageType shaderStage) const; inline const std::shared_ptr& GetTexture(std::size_t textureIndex) const; inline const TextureSamplerInfo& GetTextureSampler(std::size_t textureIndex) const; inline const std::shared_ptr& GetUniformBuffer(std::size_t bufferIndex) const; @@ -98,7 +98,7 @@ namespace Nz inline void SetFaceCulling(FaceSide faceSide); inline void SetFaceFilling(FaceFilling filling); inline void SetLineWidth(float lineWidth); - inline void SetOptionValue(std::size_t optionIndex, ShaderAst::ConstantValue value); + inline void SetOptionValue(std::size_t optionIndex, nzsl::Ast::ConstantValue value); inline void SetPointSize(float pointSize); inline void SetPrimitiveMode(PrimitiveMode mode); inline void SetTexture(std::size_t textureIndex, std::shared_ptr texture); @@ -142,7 +142,7 @@ namespace Nz bool dataInvalidated = true; }; - std::array m_optionValues; + std::array m_optionValues; std::shared_ptr m_settings; std::vector m_textures; std::vector m_shaders; diff --git a/include/Nazara/Graphics/MaterialPass.inl b/include/Nazara/Graphics/MaterialPass.inl index 8dbdd7379..0693fd9f7 100644 --- a/include/Nazara/Graphics/MaterialPass.inl +++ b/include/Nazara/Graphics/MaterialPass.inl @@ -319,7 +319,7 @@ namespace Nz return m_pipelineInfo.lineWidth; } - inline const ShaderAst::ConstantValue& MaterialPass::GetOptionValue(std::size_t optionIndex) const + inline const nzsl::Ast::ConstantValue& MaterialPass::GetOptionValue(std::size_t optionIndex) const { assert(optionIndex < m_optionValues.size()); return m_optionValues[optionIndex]; @@ -368,7 +368,7 @@ namespace Nz * \brief Gets the über-shader used by this material * \return Constant pointer to the über-shader used */ - inline const std::shared_ptr& MaterialPass::GetShader(ShaderStageType shaderStage) const + inline const std::shared_ptr& MaterialPass::GetShader(nzsl::ShaderStageType shaderStage) const { return m_pipelineInfo.shaders[UnderlyingCast(shaderStage)].uberShader; } @@ -566,7 +566,7 @@ namespace Nz InvalidatePipeline(); } - inline void MaterialPass::SetOptionValue(std::size_t optionIndex, ShaderAst::ConstantValue value) + inline void MaterialPass::SetOptionValue(std::size_t optionIndex, nzsl::Ast::ConstantValue value) { assert(optionIndex < m_optionValues.size()); if (m_optionValues[optionIndex] != value) diff --git a/include/Nazara/Graphics/MaterialPipeline.hpp b/include/Nazara/Graphics/MaterialPipeline.hpp index 34339b15e..b6c0cb1ec 100644 --- a/include/Nazara/Graphics/MaterialPipeline.hpp +++ b/include/Nazara/Graphics/MaterialPipeline.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include @@ -25,7 +25,7 @@ namespace Nz struct Option { UInt32 hash; - ShaderAst::ConstantValue value; + nzsl::Ast::ConstantValue value; }; struct Shader diff --git a/include/Nazara/Graphics/MaterialSettings.hpp b/include/Nazara/Graphics/MaterialSettings.hpp index 5b5f434cb..e7f1afee4 100644 --- a/include/Nazara/Graphics/MaterialSettings.hpp +++ b/include/Nazara/Graphics/MaterialSettings.hpp @@ -41,7 +41,7 @@ namespace Nz inline std::size_t GetOptionIndex(const std::string_view& name) const; inline std::size_t GetPredefinedBinding(PredefinedShaderBinding shaderBinding) const; inline const std::shared_ptr& GetRenderPipelineLayout() const; - inline const std::shared_ptr& GetShader(ShaderStageType stage) const; + inline const std::shared_ptr& GetShader(nzsl::ShaderStageType stage) const; inline const std::vector>& GetShaders() const; inline const std::vector& GetSharedUniformBlocks() const; inline std::size_t GetSharedUniformBlockIndex(const std::string_view& name) const; @@ -88,7 +88,7 @@ namespace Nz UInt32 bindingIndex; std::string name; std::vector uniforms; - ShaderStageTypeFlags shaderStages = ShaderStageType_All; + nzsl::ShaderStageTypeFlags shaderStages = nzsl::ShaderStageType_All; }; struct Texture @@ -96,7 +96,7 @@ namespace Nz UInt32 bindingIndex; std::string name; ImageType type; - ShaderStageTypeFlags shaderStages = ShaderStageType_All; + nzsl::ShaderStageTypeFlags shaderStages = nzsl::ShaderStageType_All; }; struct UniformBlock @@ -106,7 +106,7 @@ namespace Nz std::size_t blockSize; std::vector uniforms; std::vector defaultValues; - ShaderStageTypeFlags shaderStages = ShaderStageType_All; + nzsl::ShaderStageTypeFlags shaderStages = nzsl::ShaderStageType_All; }; private: diff --git a/include/Nazara/Graphics/MaterialSettings.inl b/include/Nazara/Graphics/MaterialSettings.inl index 4b31ccdf7..dd1e4c7a8 100644 --- a/include/Nazara/Graphics/MaterialSettings.inl +++ b/include/Nazara/Graphics/MaterialSettings.inl @@ -84,7 +84,7 @@ namespace Nz return m_pipelineLayout; } - inline const std::shared_ptr& MaterialSettings::GetShader(ShaderStageType stage) const + inline const std::shared_ptr& MaterialSettings::GetShader(nzsl::ShaderStageType stage) const { return m_data.shaders[UnderlyingCast(stage)]; } diff --git a/include/Nazara/Graphics/PhongLightingMaterial.hpp b/include/Nazara/Graphics/PhongLightingMaterial.hpp index c6d4b88f9..47ba40107 100644 --- a/include/Nazara/Graphics/PhongLightingMaterial.hpp +++ b/include/Nazara/Graphics/PhongLightingMaterial.hpp @@ -92,7 +92,7 @@ namespace Nz static MaterialSettings::Builder Build(PhongBuildOptions& options); static std::vector> BuildShaders(); - static std::pair BuildUniformOffsets(); + static std::pair BuildUniformOffsets(); private: static bool Initialize(); diff --git a/include/Nazara/Graphics/PredefinedShaderStructs.hpp b/include/Nazara/Graphics/PredefinedShaderStructs.hpp index 05b144988..43d4234c6 100644 --- a/include/Nazara/Graphics/PredefinedShaderStructs.hpp +++ b/include/Nazara/Graphics/PredefinedShaderStructs.hpp @@ -35,7 +35,7 @@ namespace Nz static constexpr std::size_t MaxLightCount = 3; static PredefinedLightData GetOffsets(); - static MaterialSettings::SharedUniformBlock GetUniformBlock(UInt32 bindingIndex, ShaderStageTypeFlags shaderStages); + static MaterialSettings::SharedUniformBlock GetUniformBlock(UInt32 bindingIndex, nzsl::ShaderStageTypeFlags shaderStages); }; struct NAZARA_GRAPHICS_API PredefinedInstanceData @@ -45,7 +45,7 @@ namespace Nz std::size_t worldMatrixOffset; static PredefinedInstanceData GetOffsets(); - static MaterialSettings::SharedUniformBlock GetUniformBlock(UInt32 bindingIndex, ShaderStageTypeFlags shaderStages); + static MaterialSettings::SharedUniformBlock GetUniformBlock(UInt32 bindingIndex, nzsl::ShaderStageTypeFlags shaderStages); }; struct NAZARA_GRAPHICS_API PredefinedViewerData @@ -62,7 +62,7 @@ namespace Nz std::size_t viewProjMatrixOffset; static PredefinedViewerData GetOffsets(); - static MaterialSettings::SharedUniformBlock GetUniformBlock(UInt32 bindingIndex, ShaderStageTypeFlags shaderStages); + static MaterialSettings::SharedUniformBlock GetUniformBlock(UInt32 bindingIndex, nzsl::ShaderStageTypeFlags shaderStages); }; } diff --git a/include/Nazara/Graphics/Systems/RenderSystem.hpp b/include/Nazara/Graphics/Systems/RenderSystem.hpp index 87cf0fd06..2c1ae8f3a 100644 --- a/include/Nazara/Graphics/Systems/RenderSystem.hpp +++ b/include/Nazara/Graphics/Systems/RenderSystem.hpp @@ -8,11 +8,11 @@ #define NAZARA_GRAPHICS_SYSTEMS_RENDERSYSTEM_HPP #include -#include #include #include #include #include +#include #include #include #include diff --git a/include/Nazara/Graphics/UberShader.hpp b/include/Nazara/Graphics/UberShader.hpp index 1205ece7c..2c8b16b0f 100644 --- a/include/Nazara/Graphics/UberShader.hpp +++ b/include/Nazara/Graphics/UberShader.hpp @@ -9,12 +9,11 @@ #include #include -#include -#include #include #include -#include -#include +#include +#include +#include #include namespace Nz @@ -28,12 +27,12 @@ namespace Nz struct Option; using ConfigCallback = std::function& vertexBuffers)>; - UberShader(ShaderStageTypeFlags shaderStages, std::string moduleName); - UberShader(ShaderStageTypeFlags shaderStages, ShaderModuleResolver& moduleResolver, std::string moduleName); - UberShader(ShaderStageTypeFlags shaderStages, ShaderAst::ModulePtr shaderModule); + UberShader(nzsl::ShaderStageTypeFlags shaderStages, std::string moduleName); + UberShader(nzsl::ShaderStageTypeFlags shaderStages, nzsl::ShaderModuleResolver& moduleResolver, std::string moduleName); + UberShader(nzsl::ShaderStageTypeFlags shaderStages, nzsl::Ast::ModulePtr shaderModule); ~UberShader() = default; - inline ShaderStageTypeFlags GetSupportedStages() const; + inline nzsl::ShaderStageTypeFlags GetSupportedStages() const; const std::shared_ptr& Get(const Config& config); @@ -44,7 +43,7 @@ namespace Nz struct Config { - std::unordered_map optionValues; + std::unordered_map optionValues; }; struct ConfigEqual @@ -65,15 +64,15 @@ namespace Nz NazaraSignal(OnShaderUpdated, UberShader* /*uberShader*/); private: - ShaderAst::ModulePtr Validate(const ShaderAst::Module& module, std::unordered_map* options); + nzsl::Ast::ModulePtr Validate(const nzsl::Ast::Module& module, std::unordered_map* options); - NazaraSlot(ShaderModuleResolver, OnModuleUpdated, m_onShaderModuleUpdated); + NazaraSlot(nzsl::ShaderModuleResolver, OnModuleUpdated, m_onShaderModuleUpdated); std::unordered_map, ConfigHasher, ConfigEqual> m_combinations; std::unordered_map m_optionIndexByName; - ShaderAst::ModulePtr m_shaderModule; + nzsl::Ast::ModulePtr m_shaderModule; ConfigCallback m_configCallback; - ShaderStageTypeFlags m_shaderStages; + nzsl::ShaderStageTypeFlags m_shaderStages; }; } diff --git a/include/Nazara/Graphics/UberShader.inl b/include/Nazara/Graphics/UberShader.inl index 41e98983e..1d16d5ec7 100644 --- a/include/Nazara/Graphics/UberShader.inl +++ b/include/Nazara/Graphics/UberShader.inl @@ -7,7 +7,7 @@ namespace Nz { - inline ShaderStageTypeFlags UberShader::GetSupportedStages() const + inline nzsl::ShaderStageTypeFlags UberShader::GetSupportedStages() const { return m_shaderStages; } diff --git a/include/Nazara/Math/Algorithm.hpp b/include/Nazara/Math/Algorithm.hpp index a4a2a1fa6..de6a1b1dd 100644 --- a/include/Nazara/Math/Algorithm.hpp +++ b/include/Nazara/Math/Algorithm.hpp @@ -9,27 +9,17 @@ #include #include +#include #include #include #include namespace Nz { - template constexpr T HalfPi = T(1.5707963267948966192313216916398); - template constexpr T Pi = T(3.1415926535897932384626433832795); - template constexpr T Sqrt2 = T(1.4142135623730950488016887242097); - template constexpr T Sqrt3 = T(1.7320508075688772935274463415059); - template constexpr T Sqrt5 = T(2.2360679774997896964091736687313); - template class Angle; - template constexpr T Approach(T value, T objective, T increment); - template constexpr T Clamp(T value, T min, T max); template constexpr Angle Clamp(Angle value, T min, T max); - template T ClearBit(T number, T bit); - template constexpr std::size_t CountBits(T value); - template constexpr T DegreeToRadian(T degrees); - template constexpr T GetNearestPowerOfTwo(T number); + constexpr unsigned int GetNumberLength(signed char number); constexpr unsigned int GetNumberLength(unsigned char number); unsigned int GetNumberLength(int number); @@ -39,19 +29,8 @@ namespace Nz unsigned int GetNumberLength(float number, UInt8 precision = NAZARA_CORE_DECIMAL_DIGITS); unsigned int GetNumberLength(double number, UInt8 precision = NAZARA_CORE_DECIMAL_DIGITS); unsigned int GetNumberLength(long double number, UInt8 precision = NAZARA_CORE_DECIMAL_DIGITS); - template constexpr unsigned int IntegralLog2(T number); - template constexpr unsigned int IntegralLog2Pot(T pot); - template constexpr T IntegralPow(T base, unsigned int exponent); - template constexpr T Lerp(const T& from, const T& to, const T2& interpolation); - template constexpr T MultiplyAdd(T x, T y, T z); - template constexpr bool NumberEquals(T a, T b); - template constexpr bool NumberEquals(T a, T b, T maxDifference); inline std::string NumberToString(long long number, UInt8 radix = 10); - template constexpr T RadianToDegree(T radians); - template T SetBit(T number, T bit); inline long long StringToNumber(const std::string_view& str, UInt8 radix = 10, bool* ok = nullptr); - template bool TestBit(T number, T bit); - template T ToggleBit(T number, T bit); } #include diff --git a/include/Nazara/Math/Algorithm.inl b/include/Nazara/Math/Algorithm.inl index 10cfe7681..e0cbd7c49 100644 --- a/include/Nazara/Math/Algorithm.inl +++ b/include/Nazara/Math/Algorithm.inl @@ -13,149 +13,6 @@ namespace Nz { - namespace Detail - { - namespace - { - // https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn - static constexpr unsigned int MultiplyDeBruijnBitPosition[32] = - { - 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, - 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 - }; - - static constexpr unsigned int MultiplyDeBruijnBitPosition2[32] = - { - 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, - 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 - }; - } - - template - constexpr std::enable_if_t IntegralLog2(T number) - { - // https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn - number |= number >> 1; // first round down to one less than a power of 2 - number |= number >> 2; - number |= number >> 4; - number |= number >> 8; - number |= number >> 16; - - return MultiplyDeBruijnBitPosition[static_cast(number * 0x07C4ACDDU) >> 27]; - } - - template - constexpr std::enable_if_t<(sizeof(T) > sizeof(UInt32)), unsigned int> IntegralLog2(T number) - { - static_assert(sizeof(T) % sizeof(UInt32) == 0, "Assertion failed"); - - // Masking and shifting bits to the right (to bring it back to 32 bits) - - // Call of the function with 32 bits number, if the result is non-null we have our answer - for (int i = sizeof(T)-sizeof(UInt32); i >= 0; i -= sizeof(UInt32)) - { - // The 32 bits mask on the part we are treating - T mask = T(std::numeric_limits::max()) << i*8; - T val = (number & mask) >> i*8; // Masking and shifting bits to the right (to bring it back to 32 bits) - - // Call of the function with 32 bits number, if the result is non-null we have our answer - unsigned int log2 = IntegralLog2(val); - if (log2) - return log2 + i*8; - } - - return 0; - } - - template - constexpr std::enable_if_t IntegralLog2Pot(T number) - { - // https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn - return MultiplyDeBruijnBitPosition2[static_cast(number * 0x077CB531U) >> 27]; - } - - template - constexpr std::enable_if_t<(sizeof(T) > sizeof(UInt32)), unsigned int> IntegralLog2Pot(T number) - { - static_assert(sizeof(T) % sizeof(UInt32) == 0, "Assertion failed"); - - // The algorithm for logarithm in base 2 only works with numbers greater than 32 bits - // This code subdivides the biggest number into 32 bits ones - for (int i = sizeof(T)-sizeof(UInt32); i >= 0; i -= sizeof(UInt32)) - { - // The 32 bits mask on the part we are treating - T mask = T(std::numeric_limits::max()) << i*8; - UInt32 val = UInt32((number & mask) >> i*8); // Masking and shifting bits to the right (to bring it back to 32 bits) - - // Call of the function with 32 bits number, if the result is non-null we have our answer - unsigned int log2 = IntegralLog2Pot(val); - if (log2 || val == 1) - return log2 + i*8; - } - - return 0; - } - - template constexpr std::enable_if_t::value, bool> NumberEquals(T a, T b, T maxDifference) - { - T diff = std::abs(a - b); - return diff <= maxDifference; - } - - template constexpr std::enable_if_t::value || (!std::is_integral::value && !std::is_floating_point::value), bool> NumberEquals(T a, T b, T maxDifference) - { - if (b > a) - std::swap(a, b); - - T diff = a - b; - return diff <= maxDifference; - } - - template constexpr std::enable_if_t::value && std::is_integral::value, bool> NumberEquals(T a, T b, T maxDifference) - { - if (b > a) - std::swap(a, b); - - using UnsignedT = std::make_unsigned_t; - return static_cast(a) - static_cast(b) <= static_cast(maxDifference); - } - } - - /*! - * \ingroup math - * \brief Approaches the objective, beginning with value and with increment - * \return The nearest value of the objective you can get with the value and the increment for one step - * - * \param value Initial value - * \param objective Target value - * \param increment One step value - */ - template - constexpr inline T Approach(T value, T objective, T increment) - { - if (value < objective) - return std::min(value + increment, objective); - else if (value > objective) - return std::max(value - increment, objective); - else - return value; - } - - /*! - * \ingroup math - * \brief Clamps value between min and max and returns the expected value - * \return If value is not in the interval of min..max, value obtained is the nearest limit of this interval - * - * \param value Value to clamp - * \param min Minimum of the interval - * \param max Maximum of the interval - */ - template - constexpr T Clamp(T value, T min, T max) - { - return std::max(std::min(value, max), min); - } - /*! * \ingroup math * \brief Clamps an angle value between min and max and returns the expected value @@ -171,64 +28,6 @@ namespace Nz return std::max(std::min(value.value, max), min); } - template - T ClearBit(T number, T bit) - { - NazaraAssert(bit < sizeof(number) * CHAR_BIT, "bit index out of range"); - return number &= ~(T(1) << bit); - } - - /*! - * \ingroup math - * \brief Gets number of bits set in the number - * \return The number of bits set to 1 - * - * \param value The value to count bits - */ - template - constexpr inline std::size_t CountBits(T value) - { - // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan - std::size_t count = 0; - while (value) - { - value &= value - 1; - count++; - } - - return count; - } - - /*! - * \ingroup math - * \brief Converts degree to radian - * \return The representation in radian of the angle in degree (0..2*pi) - * - * \param degrees Angle in degree (this is expected between 0..360) - */ - template - constexpr T DegreeToRadian(T degrees) - { - return degrees * T(Pi/180.0); - } - - /*! - * \ingroup math - * \brief Gets the nearest power of two for the number - * \return First power of two containing the number - * - * \param number Number to get nearest power - */ - template - constexpr inline T GetNearestPowerOfTwo(T number) - { - T x = 1; - while (x < number) - x <<= 1; // We multiply by 2 - - return x; - } - /*! * \ingroup math * \brief Gets the number of digits to represent the number in base 10 @@ -379,147 +178,6 @@ namespace Nz return GetNumberLength(static_cast(number)) + precision + 1; // Plus one for the dot } - /*! - * \ingroup math - * \brief Gets the log in base 2 of integral number - * \return Log of the number (floor) - * - * \param number To get log in base 2 - * - * \remark If number is 0, 0 is returned - */ - template - constexpr unsigned int IntegralLog2(T number) - { - // Proxy needed to avoid an overload problem - return Detail::IntegralLog2(number); - } - - /*! - * \ingroup math - * \brief Gets the log in base 2 of integral number, only works for power of two ! - * \return Log of the number - * - * \param pot To get log in base 2 - * - * \remark Only works for power of two - * \remark If number is 0, 0 is returned - */ - template - constexpr unsigned int IntegralLog2Pot(T pot) - { - return Detail::IntegralLog2Pot(pot); - } - - /*! - * \ingroup math - * \brief Gets the power of integrals - * \return base^exponent for integral - * - * \param base Base of the exponentation - * \param exponent Power for the base - */ - template - constexpr T IntegralPow(T base, unsigned int exponent) - { - T r = 1; - for (unsigned int i = 0; i < exponent; ++i) - r *= base; - - return r; - } - - /*! - * \ingroup math - * \brief Interpolates the value to other one with a factor of interpolation - * \return A new value which is the interpolation of two values - * - * \param from Initial value - * \param to Target value - * \param interpolation Factor of interpolation - * - * \remark interpolation is meant to be between 0 and 1, other values are potentially undefined behavior - * \remark With NAZARA_DEBUG, a NazaraWarning is produced - * - * \see Lerp - */ - template - constexpr T Lerp(const T& from, const T& to, const T2& interpolation) - { - return static_cast(from + interpolation * (to - from)); - } - - /*! - * \ingroup math - * \brief Multiplies X and Y, then add Z - * \return The result of X * Y + Z - * - * \param x is X - * \param y is Y - * \param z is Z - * - * \remark This function is meant to use a special faster instruction in CPU if possible - */ - - template - constexpr T MultiplyAdd(T x, T y, T z) - { - return x * y + z; - } - - #ifdef FP_FAST_FMAF - template<> - constexpr float MultiplyAdd(float x, float y, float z) - { - return std::fmaf(x, y, z); - } - #endif - - #ifdef FP_FAST_FMA - template<> - constexpr double MultiplyAdd(double x, double y, double z) - { - return std::fma(x, y, z); - } - #endif - - #ifdef FP_FAST_FMAL - template<> - constexpr long double MultiplyAdd(long double x, long double y, long double z) - { - return std::fmal(x, y, z); - } - #endif - - /*! - * \ingroup math - * \brief Checks whether two numbers are equal - * \return true if they are equal within a certain epsilon - * - * \param a First value - * \param b Second value - */ - template - constexpr inline bool NumberEquals(T a, T b) - { - return NumberEquals(a, b, std::numeric_limits::epsilon()); - } - - /*! - * \ingroup math - * \brief Checks whether two numbers are equal - * \return true if they are equal within the max difference - * - * \param a First value - * \param b Second value - * \param maxDifference Epsilon of comparison (expected to be positive) - */ - template - constexpr inline bool NumberEquals(T a, T b, T maxDifference) - { - return Detail::NumberEquals(a, b, maxDifference); - } - /*! * \ingroup math * \brief Converts the number to String @@ -572,26 +230,6 @@ namespace Nz return str; } - /*! - * \ingroup math - * \brief Converts radian to degree - * \return The representation in degree of the angle in radian (0..360) - * - * \param radians Angle in radian (this is expected between 0..2*pi) - */ - template - constexpr T RadianToDegree(T radians) - { - return radians * T(180.0/Pi); - } - - template - T SetBit(T number, T bit) - { - NazaraAssert(bit < sizeof(number) * CHAR_BIT, "bit index out of range"); - return number |= (T(1) << bit); - } - /*! * \ingroup math * \brief Converts the string to number @@ -656,20 +294,6 @@ namespace Nz return (negative) ? -static_cast(total) : total; } - - template - bool TestBit(T number, T bit) - { - NazaraAssert(bit < sizeof(number) * CHAR_BIT, "bit index out of range"); - return number & (T(1) << bit); - } - - template - T ToggleBit(T number, T bit) - { - NazaraAssert(bit < sizeof(number) * CHAR_BIT, "bit index out of range"); - return number ^= (T(1) << bit); - } } #include diff --git a/include/Nazara/Math/Angle.hpp b/include/Nazara/Math/Angle.hpp index ad0227d39..3f92bcf9d 100644 --- a/include/Nazara/Math/Angle.hpp +++ b/include/Nazara/Math/Angle.hpp @@ -7,9 +7,9 @@ #ifndef NAZARA_MATH_ANGLE_HPP #define NAZARA_MATH_ANGLE_HPP -#include #include #include +#include #include #include #include diff --git a/include/Nazara/Math/Matrix4.hpp b/include/Nazara/Math/Matrix4.hpp index c0356d886..f3659e0fd 100644 --- a/include/Nazara/Math/Matrix4.hpp +++ b/include/Nazara/Math/Matrix4.hpp @@ -9,9 +9,9 @@ ///FIXME: Matrices column-major, difficile de bosser avec (Tout passer en row-major et transposer dans les shaders ?) -#include #include #include +#include #include #include diff --git a/include/Nazara/Math/Vector2.hpp b/include/Nazara/Math/Vector2.hpp index 3582beb24..dca904618 100644 --- a/include/Nazara/Math/Vector2.hpp +++ b/include/Nazara/Math/Vector2.hpp @@ -8,8 +8,8 @@ #define NAZARA_MATH_VECTOR2_HPP #include -#include #include +#include #include #include diff --git a/include/Nazara/Math/Vector3.hpp b/include/Nazara/Math/Vector3.hpp index aab533c90..6e0db6665 100644 --- a/include/Nazara/Math/Vector3.hpp +++ b/include/Nazara/Math/Vector3.hpp @@ -8,8 +8,8 @@ #define NAZARA_MATH_VECTOR3_HPP #include -#include #include +#include #include #include diff --git a/include/Nazara/Math/Vector4.hpp b/include/Nazara/Math/Vector4.hpp index 947fb3dcf..945b062df 100644 --- a/include/Nazara/Math/Vector4.hpp +++ b/include/Nazara/Math/Vector4.hpp @@ -8,7 +8,7 @@ #define NAZARA_MATH_VECTOR4_HPP #include -#include +#include #include #include diff --git a/include/Nazara/Network/AbstractSocket.hpp b/include/Nazara/Network/AbstractSocket.hpp index 54791dbdf..1aabca705 100644 --- a/include/Nazara/Network/AbstractSocket.hpp +++ b/include/Nazara/Network/AbstractSocket.hpp @@ -8,10 +8,10 @@ #define NAZARA_NETWORK_ABSTRACTSOCKET_HPP #include -#include #include #include #include +#include namespace Nz { diff --git a/include/Nazara/Network/Algorithm.inl b/include/Nazara/Network/Algorithm.inl index 2c93e6794..74cf156d8 100644 --- a/include/Nazara/Network/Algorithm.inl +++ b/include/Nazara/Network/Algorithm.inl @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz diff --git a/include/Nazara/Network/ENetHost.hpp b/include/Nazara/Network/ENetHost.hpp index 32fcbeb73..55808d919 100644 --- a/include/Nazara/Network/ENetHost.hpp +++ b/include/Nazara/Network/ENetHost.hpp @@ -18,9 +18,7 @@ #define NAZARA_NETWORK_ENETHOST_HPP #include -#include #include -#include #include #include #include @@ -29,6 +27,8 @@ #include #include #include +#include +#include #include namespace Nz diff --git a/include/Nazara/Network/ENetPacket.hpp b/include/Nazara/Network/ENetPacket.hpp index 5c9bc2458..efef5e843 100644 --- a/include/Nazara/Network/ENetPacket.hpp +++ b/include/Nazara/Network/ENetPacket.hpp @@ -8,8 +8,8 @@ #define NAZARA_NETWORK_ENETPACKET_HPP #include -#include #include +#include namespace Nz { diff --git a/include/Nazara/Network/ENetPeer.hpp b/include/Nazara/Network/ENetPeer.hpp index e553bf266..953be1d1e 100644 --- a/include/Nazara/Network/ENetPeer.hpp +++ b/include/Nazara/Network/ENetPeer.hpp @@ -18,11 +18,11 @@ #define NAZARA_NETWORK_ENETPEER_HPP #include -#include -#include #include #include #include +#include +#include #include #include #include diff --git a/include/Nazara/Network/Enums.hpp b/include/Nazara/Network/Enums.hpp index 0bbda498a..af2b4c9e5 100644 --- a/include/Nazara/Network/Enums.hpp +++ b/include/Nazara/Network/Enums.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_NETWORK_ENUMS_HPP #define NAZARA_NETWORK_ENUMS_HPP -#include +#include namespace Nz { diff --git a/include/Nazara/Network/SocketPoller.hpp b/include/Nazara/Network/SocketPoller.hpp index b4ab16545..32d5ceec2 100644 --- a/include/Nazara/Network/SocketPoller.hpp +++ b/include/Nazara/Network/SocketPoller.hpp @@ -8,8 +8,8 @@ #define NAZARA_NETWORK_SOCKETPOLLER_HPP #include -#include #include +#include namespace Nz { diff --git a/include/Nazara/OpenGLRenderer/OpenGLCommandPool.hpp b/include/Nazara/OpenGLRenderer/OpenGLCommandPool.hpp index 9c656a09e..a9c0f55ca 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLCommandPool.hpp +++ b/include/Nazara/OpenGLRenderer/OpenGLCommandPool.hpp @@ -8,10 +8,10 @@ #define NAZARA_OPENGLRENDERER_OPENGLCOMMANDPOOL_HPP #include -#include #include #include #include +#include namespace Nz { diff --git a/include/Nazara/OpenGLRenderer/OpenGLDevice.hpp b/include/Nazara/OpenGLRenderer/OpenGLDevice.hpp index baf153e66..235ec9f71 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLDevice.hpp +++ b/include/Nazara/OpenGLRenderer/OpenGLDevice.hpp @@ -41,8 +41,8 @@ namespace Nz std::shared_ptr InstantiateRenderPass(std::vector attachments, std::vector subpassDescriptions, std::vector subpassDependencies) override; std::shared_ptr InstantiateRenderPipeline(RenderPipelineInfo pipelineInfo) override; std::shared_ptr InstantiateRenderPipelineLayout(RenderPipelineLayoutInfo pipelineLayoutInfo) override; - std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) override; - std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) override; + std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) override; + std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) override; std::shared_ptr InstantiateTexture(const TextureInfo& params) override; std::shared_ptr InstantiateTextureSampler(const TextureSamplerInfo& params) override; diff --git a/include/Nazara/OpenGLRenderer/OpenGLRenderPipeline.hpp b/include/Nazara/OpenGLRenderer/OpenGLRenderPipeline.hpp index cb970add7..15652f971 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLRenderPipeline.hpp +++ b/include/Nazara/OpenGLRenderer/OpenGLRenderPipeline.hpp @@ -8,10 +8,10 @@ #define NAZARA_OPENGLRENDERER_OPENGLRENDERPIPELINE_HPP #include -#include #include #include #include +#include #include namespace Nz diff --git a/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.hpp b/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.hpp index 2b313aec8..14c96bc3c 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.hpp +++ b/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.hpp @@ -8,13 +8,13 @@ #define NAZARA_OPENGLRENDERER_OPENGLRENDERPIPELINELAYOUT_HPP #include -#include #include #include #include #include #include -#include +#include +#include #include #include #include @@ -33,7 +33,7 @@ namespace Nz ShaderBindingPtr AllocateShaderBinding(UInt32 setIndex) override; - inline const GlslWriter::BindingMapping& GetBindingMapping() const; + inline const nzsl::GlslWriter::BindingMapping& GetBindingMapping() const; inline const RenderPipelineLayoutInfo& GetLayoutInfo() const; OpenGLRenderPipelineLayout& operator=(const OpenGLRenderPipelineLayout&) = delete; @@ -79,7 +79,7 @@ namespace Nz std::size_t m_maxDescriptorCount; std::vector m_descriptorPools; - GlslWriter::BindingMapping m_bindingMapping; + nzsl::GlslWriter::BindingMapping m_bindingMapping; RenderPipelineLayoutInfo m_layoutInfo; }; } diff --git a/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.inl b/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.inl index 6fd50708b..5a6ac03cd 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.inl +++ b/include/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.inl @@ -7,7 +7,7 @@ namespace Nz { - inline const GlslWriter::BindingMapping& OpenGLRenderPipelineLayout::GetBindingMapping() const + inline const nzsl::GlslWriter::BindingMapping& OpenGLRenderPipelineLayout::GetBindingMapping() const { return m_bindingMapping; } diff --git a/include/Nazara/OpenGLRenderer/OpenGLShaderModule.hpp b/include/Nazara/OpenGLRenderer/OpenGLShaderModule.hpp index 5811881c7..ca65fd2fe 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLShaderModule.hpp +++ b/include/Nazara/OpenGLRenderer/OpenGLShaderModule.hpp @@ -13,8 +13,8 @@ #include #include #include -#include -#include +#include +#include #include namespace Nz @@ -22,19 +22,19 @@ namespace Nz class NAZARA_OPENGLRENDERER_API OpenGLShaderModule : public ShaderModule { public: - OpenGLShaderModule(OpenGLDevice& device, ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states = {}); - OpenGLShaderModule(OpenGLDevice& device, ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states = {}); + OpenGLShaderModule(OpenGLDevice& device, nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states = {}); + OpenGLShaderModule(OpenGLDevice& device, nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states = {}); OpenGLShaderModule(const OpenGLShaderModule&) = delete; OpenGLShaderModule(OpenGLShaderModule&&) noexcept = default; ~OpenGLShaderModule() = default; - ShaderStageTypeFlags Attach(GL::Program& program, const GlslWriter::BindingMapping& bindingMapping) const; + nzsl::ShaderStageTypeFlags Attach(GL::Program& program, const nzsl::GlslWriter::BindingMapping& bindingMapping) const; OpenGLShaderModule& operator=(const OpenGLShaderModule&) = delete; OpenGLShaderModule& operator=(OpenGLShaderModule&&) noexcept = default; private: - void Create(OpenGLDevice& device, ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states); + void Create(OpenGLDevice& device, nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states); static void CheckCompilationStatus(GL::Shader& shader); @@ -45,17 +45,17 @@ namespace Nz struct ShaderStatement { - ShaderAst::ModulePtr ast; + nzsl::Ast::ModulePtr ast; }; struct Shader { - ShaderStageType stage; + nzsl::ShaderStageType stage; std::variant shader; }; OpenGLDevice& m_device; - ShaderWriter::States m_states; + nzsl::ShaderWriter::States m_states; std::vector m_shaders; }; } diff --git a/include/Nazara/OpenGLRenderer/OpenGLUploadPool.hpp b/include/Nazara/OpenGLRenderer/OpenGLUploadPool.hpp index e09b04e85..6b6aefb77 100644 --- a/include/Nazara/OpenGLRenderer/OpenGLUploadPool.hpp +++ b/include/Nazara/OpenGLRenderer/OpenGLUploadPool.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_OPENGLUPLOADPOOL_HPP #include -#include #include #include +#include #include #include #include diff --git a/include/Nazara/OpenGLRenderer/Utils.hpp b/include/Nazara/OpenGLRenderer/Utils.hpp index 591a9fa34..15b365480 100644 --- a/include/Nazara/OpenGLRenderer/Utils.hpp +++ b/include/Nazara/OpenGLRenderer/Utils.hpp @@ -10,8 +10,8 @@ #include #include #include -#include #include +#include #include #include @@ -40,7 +40,7 @@ namespace Nz inline GLenum ToOpenGL(SamplerFilter filter); inline GLenum ToOpenGL(SamplerFilter minFilter, SamplerMipmapMode mipmapFilter); inline GLenum ToOpenGL(SamplerWrap wrapMode); - inline GLenum ToOpenGL(ShaderStageType stageType); + inline GLenum ToOpenGL(nzsl::ShaderStageType stageType); inline GLenum ToOpenGL(StencilOperation stencilOp); inline GLenum ToOpenGL(GL::BufferTarget bufferTarget); inline GLenum ToOpenGL(GL::TextureTarget bufferTarget); diff --git a/include/Nazara/OpenGLRenderer/Utils.inl b/include/Nazara/OpenGLRenderer/Utils.inl index 178064730..576d12823 100644 --- a/include/Nazara/OpenGLRenderer/Utils.inl +++ b/include/Nazara/OpenGLRenderer/Utils.inl @@ -225,15 +225,15 @@ namespace Nz return {}; } - inline GLenum ToOpenGL(ShaderStageType stageType) + inline GLenum ToOpenGL(nzsl::ShaderStageType stageType) { switch (stageType) { - case ShaderStageType::Fragment: return GL_FRAGMENT_SHADER; - case ShaderStageType::Vertex: return GL_VERTEX_SHADER; + case nzsl::ShaderStageType::Fragment: return GL_FRAGMENT_SHADER; + case nzsl::ShaderStageType::Vertex: return GL_VERTEX_SHADER; } - NazaraError("Unhandled ShaderStageType 0x" + NumberToString(UnderlyingCast(stageType), 16)); + NazaraError("Unhandled nzsl::ShaderStageType 0x" + NumberToString(UnderlyingCast(stageType), 16)); return {}; } diff --git a/include/Nazara/OpenGLRenderer/Wrapper/Buffer.hpp b/include/Nazara/OpenGLRenderer/Wrapper/Buffer.hpp index 0a188cdcc..1b6401be5 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/Buffer.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/Buffer.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_BUFFER_HPP #include -#include #include #include +#include namespace Nz::GL { diff --git a/include/Nazara/OpenGLRenderer/Wrapper/ContextObject.hpp b/include/Nazara/OpenGLRenderer/Wrapper/ContextObject.hpp index 024dc7788..df4e55054 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/ContextObject.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/ContextObject.hpp @@ -8,8 +8,8 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_CONTEXTOBJECT_HPP #include -#include #include +#include #include namespace Nz::GL diff --git a/include/Nazara/OpenGLRenderer/Wrapper/DeviceObject.hpp b/include/Nazara/OpenGLRenderer/Wrapper/DeviceObject.hpp index a3c2d97d8..5e9376b12 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/DeviceObject.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/DeviceObject.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_DEVICEOBJECT_HPP #include -#include -#include #include +#include +#include #include namespace Nz::GL diff --git a/include/Nazara/OpenGLRenderer/Wrapper/Program.hpp b/include/Nazara/OpenGLRenderer/Wrapper/Program.hpp index 84c46fdbc..aba5003d7 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/Program.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/Program.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_PROGRAM_HPP #include -#include #include #include +#include namespace Nz::GL { diff --git a/include/Nazara/OpenGLRenderer/Wrapper/Sampler.hpp b/include/Nazara/OpenGLRenderer/Wrapper/Sampler.hpp index c5a46aef4..afb9a9ac1 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/Sampler.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/Sampler.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_SAMPLER_HPP #include -#include #include #include +#include namespace Nz::GL { diff --git a/include/Nazara/OpenGLRenderer/Wrapper/Shader.hpp b/include/Nazara/OpenGLRenderer/Wrapper/Shader.hpp index fef467050..003a69cb3 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/Shader.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/Shader.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_SHADER_HPP #include -#include #include #include +#include namespace Nz::GL { diff --git a/include/Nazara/OpenGLRenderer/Wrapper/Texture.hpp b/include/Nazara/OpenGLRenderer/Wrapper/Texture.hpp index 4b6dfa993..ccebcd2bb 100644 --- a/include/Nazara/OpenGLRenderer/Wrapper/Texture.hpp +++ b/include/Nazara/OpenGLRenderer/Wrapper/Texture.hpp @@ -8,9 +8,9 @@ #define NAZARA_OPENGLRENDERER_WRAPPER_TEXTURE_HPP #include -#include #include #include +#include namespace Nz::GL { diff --git a/include/Nazara/Physics2D/Arbiter2D.hpp b/include/Nazara/Physics2D/Arbiter2D.hpp index e6bcca4b1..b62d25cd2 100644 --- a/include/Nazara/Physics2D/Arbiter2D.hpp +++ b/include/Nazara/Physics2D/Arbiter2D.hpp @@ -8,9 +8,9 @@ #define NAZARA_PHYSICS2D_ARBITER2D_HPP #include -#include #include #include +#include struct cpArbiter; diff --git a/include/Nazara/Physics2D/Collider2D.hpp b/include/Nazara/Physics2D/Collider2D.hpp index 468122713..f5a4ec4cc 100644 --- a/include/Nazara/Physics2D/Collider2D.hpp +++ b/include/Nazara/Physics2D/Collider2D.hpp @@ -9,12 +9,12 @@ #include #include -#include -#include #include #include #include #include +#include +#include #include struct cpBody; diff --git a/include/Nazara/Physics2D/Constraint2D.hpp b/include/Nazara/Physics2D/Constraint2D.hpp index 7ad4cf144..8890a9891 100644 --- a/include/Nazara/Physics2D/Constraint2D.hpp +++ b/include/Nazara/Physics2D/Constraint2D.hpp @@ -9,12 +9,12 @@ #include #include -#include #include #include #include #include #include +#include #include struct cpConstraint; diff --git a/include/Nazara/Physics2D/PhysWorld2D.hpp b/include/Nazara/Physics2D/PhysWorld2D.hpp index d652d482c..952593b0d 100644 --- a/include/Nazara/Physics2D/PhysWorld2D.hpp +++ b/include/Nazara/Physics2D/PhysWorld2D.hpp @@ -9,11 +9,11 @@ #include #include -#include #include #include #include #include +#include #include #include #include diff --git a/include/Nazara/Physics2D/RigidBody2D.hpp b/include/Nazara/Physics2D/RigidBody2D.hpp index 183fa6b1d..a05f0d190 100644 --- a/include/Nazara/Physics2D/RigidBody2D.hpp +++ b/include/Nazara/Physics2D/RigidBody2D.hpp @@ -9,11 +9,11 @@ #include #include -#include #include #include #include #include +#include #include #include diff --git a/include/Nazara/Physics3D/Collider3D.hpp b/include/Nazara/Physics3D/Collider3D.hpp index 9924a2d09..7aaf17357 100644 --- a/include/Nazara/Physics3D/Collider3D.hpp +++ b/include/Nazara/Physics3D/Collider3D.hpp @@ -9,13 +9,13 @@ #include #include -#include -#include #include #include #include #include #include +#include +#include #include class NewtonCollision; diff --git a/include/Nazara/Physics3D/PhysWorld3D.hpp b/include/Nazara/Physics3D/PhysWorld3D.hpp index 5de247a8b..2c49c5ece 100644 --- a/include/Nazara/Physics3D/PhysWorld3D.hpp +++ b/include/Nazara/Physics3D/PhysWorld3D.hpp @@ -8,10 +8,10 @@ #define NAZARA_PHYSICS3D_PHYSWORLD3D_HPP #include -#include #include #include #include +#include #include #include diff --git a/include/Nazara/Physics3D/RigidBody3D.hpp b/include/Nazara/Physics3D/RigidBody3D.hpp index 939bda0ad..e775d651f 100644 --- a/include/Nazara/Physics3D/RigidBody3D.hpp +++ b/include/Nazara/Physics3D/RigidBody3D.hpp @@ -9,12 +9,12 @@ #include #include -#include #include #include #include #include #include +#include class NewtonBody; diff --git a/include/Nazara/Platform/CursorController.hpp b/include/Nazara/Platform/CursorController.hpp index 93d32cfc3..702b95ef1 100644 --- a/include/Nazara/Platform/CursorController.hpp +++ b/include/Nazara/Platform/CursorController.hpp @@ -10,9 +10,9 @@ #include #include #include -#include #include #include +#include namespace Nz { diff --git a/include/Nazara/Platform/Enums.hpp b/include/Nazara/Platform/Enums.hpp index 86f82aef1..ed8531ae1 100644 --- a/include/Nazara/Platform/Enums.hpp +++ b/include/Nazara/Platform/Enums.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_PLATFORM_ENUMS_HPP #define NAZARA_PLATFORM_ENUMS_HPP -#include +#include namespace Nz { diff --git a/include/Nazara/Platform/EventHandler.hpp b/include/Nazara/Platform/EventHandler.hpp index 710b2aa6f..d508b5b9f 100644 --- a/include/Nazara/Platform/EventHandler.hpp +++ b/include/Nazara/Platform/EventHandler.hpp @@ -10,9 +10,9 @@ #include #include #include -#include #include #include +#include namespace Nz { diff --git a/include/Nazara/Platform/Window.hpp b/include/Nazara/Platform/Window.hpp index 82af2cace..49ddcd4a2 100644 --- a/include/Nazara/Platform/Window.hpp +++ b/include/Nazara/Platform/Window.hpp @@ -10,7 +10,6 @@ #define NAZARA_PLATFORM_WINDOW_HPP #include -#include #include #include #include @@ -20,6 +19,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Prerequisites.hpp b/include/Nazara/Prerequisites.hpp deleted file mode 100644 index cb7b38f68..000000000 --- a/include/Nazara/Prerequisites.hpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - Nazara Engine - - Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) - - 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. -*/ - -#ifndef NAZARA_PREREQUISITES_HPP -#define NAZARA_PREREQUISITES_HPP - -// Try to identify the compiler -#if defined(__BORLANDC__) - #define NAZARA_COMPILER_BORDLAND - #define NAZARA_DEPRECATED(txt) - #define NAZARA_FUNCTION __FUNC__ -#elif defined(__clang__) - #define NAZARA_COMPILER_CLANG - #define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt))) - #define NAZARA_FUNCTION __PRETTY_FUNCTION__ - - #ifdef __MINGW32__ - #define NAZARA_COMPILER_MINGW - #ifdef __MINGW64_VERSION_MAJOR - #define NAZARA_COMPILER_MINGW_W64 - #endif - #endif -#elif defined(__GNUC__) || defined(__MINGW32__) - #define NAZARA_COMPILER_GCC - #define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt))) - #define NAZARA_FUNCTION __PRETTY_FUNCTION__ - - #ifdef __MINGW32__ - #define NAZARA_COMPILER_MINGW - #ifdef __MINGW64_VERSION_MAJOR - #define NAZARA_COMPILER_MINGW_W64 - #endif - #endif -#elif defined(__INTEL_COMPILER) || defined(__ICL) - #define NAZARA_COMPILER_INTEL - #define NAZARA_DEPRECATED(txt) - #define NAZARA_FUNCTION __FUNCTION__ -#elif defined(_MSC_VER) - #define NAZARA_COMPILER_MSVC - #define NAZARA_DEPRECATED(txt) __declspec(deprecated(txt)) - #define NAZARA_FUNCTION __FUNCSIG__ - - #if _MSC_VER >= 1900 - #define NAZARA_COMPILER_SUPPORTS_CPP11 - #endif - - #pragma warning(disable: 4251) -#else - #define NAZARA_COMPILER_UNKNOWN - #define NAZARA_DEPRECATED(txt) - #define NAZARA_FUNCTION __func__ // __func__ has been standardized in C++ 2011 - - #pragma message This compiler is not fully supported -#endif - -#if !defined(NAZARA_COMPILER_SUPPORTS_CPP11) && defined(__cplusplus) && __cplusplus >= 201103L - #define NAZARA_COMPILER_SUPPORTS_CPP11 -#endif - -#ifndef NAZARA_COMPILER_SUPPORTS_CPP11 - #error Nazara requires a C++11 compliant compiler -#endif - -// Nazara version macro -#define NAZARA_VERSION_MAJOR 0 -#define NAZARA_VERSION_MINOR 4 -#define NAZARA_VERSION_PATCH 0 - -#include - -// Try to identify target platform via defines -#if defined(_WIN32) - #define NAZARA_PLATFORM_DESKTOP - #define NAZARA_PLATFORM_WINDOWS - - #define NAZARA_EXPORT __declspec(dllexport) - #define NAZARA_IMPORT __declspec(dllimport) - - // Somes defines for windows.h include.. - #if defined(NAZARA_BUILD) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - - #ifndef NOMINMAX - #define NOMINMAX - #endif - - #if NAZARA_CORE_WINDOWS_NT6 - #define NAZARA_WINNT 0x0600 - #else - #define NAZARA_WINNT 0x0501 - #endif - - // Keep the actual define if existing and greater than our requirement - #if defined(_WIN32_WINNT) - #if _WIN32_WINNT < NAZARA_WINNT - #undef _WIN32_WINNT - #define _WIN32_WINNT NAZARA_WINNT - #endif - #else - #define _WIN32_WINNT NAZARA_WINNT - #endif - #endif -#elif defined(__linux__) || defined(__unix__) - #define NAZARA_PLATFORM_DESKTOP - #define NAZARA_PLATFORM_LINUX - #define NAZARA_PLATFORM_POSIX - - #define NAZARA_EXPORT __attribute__((visibility ("default"))) - #define NAZARA_IMPORT __attribute__((visibility ("default"))) -#elif defined(__APPLE__) - #include - #if TARGET_OS_IPHONE - #define NAZARA_PLATFORM_IOS - #else - #define NAZARA_PLATFORM_DESKTOP - #define NAZARA_PLATFORM_MACOS - #endif - #define NAZARA_PLATFORM_POSIX - - #define NAZARA_EXPORT __attribute__((visibility ("default"))) - #define NAZARA_IMPORT __attribute__((visibility ("default"))) -#else - #error This operating system is not fully supported by the Nazara Engine - - #define NAZARA_PLATFORM_UNKNOWN -#endif - -// Detect 64 bits -#if !defined(NAZARA_PLATFORM_x64) && (defined(_WIN64) || defined(__amd64__) || defined(__x86_64__) || defined(__ia64__) || defined(__ia64) || \ - defined(_M_IA64) || defined(__itanium__) || defined(__MINGW64__) || defined(_M_AMD64) || defined (_M_X64)) - #define NAZARA_PLATFORM_x64 -#endif - -#ifdef NAZARA_UNITY_BUILD - #define NAZARA_ANONYMOUS_NAMESPACE NAZARA_UNITY_ID - #define NAZARA_USE_ANONYMOUS_NAMESPACE using namespace NAZARA_UNITY_ID; - #define NAZARA_ANONYMOUS_NAMESPACE_PREFIX(a) NAZARA_UNITY_ID::a -#else - #define NAZARA_ANONYMOUS_NAMESPACE - #define NAZARA_USE_ANONYMOUS_NAMESPACE - #define NAZARA_ANONYMOUS_NAMESPACE_PREFIX(a) a -#endif - -// A bunch of useful macros -#define NazaraPrefix(a, prefix) prefix ## a -#define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix) -#define NazaraSuffix(a, suffix) a ## suffix -#define NazaraSuffixMacro(a, suffix) NazaraSuffix(a, suffix) -#define NazaraStringify(s) #s -#define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification -#define NazaraUnused(a) (void) a - -#include -#include - -static_assert(CHAR_BIT == 8, "CHAR_BIT is expected to be 8"); - -static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" ); -static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size"); -static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size"); -static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size"); - -static_assert(sizeof(uint8_t) == 1, "uint8_t is not of the correct size" ); -static_assert(sizeof(uint16_t) == 2, "uint16_t is not of the correct size"); -static_assert(sizeof(uint32_t) == 4, "uint32_t is not of the correct size"); -static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size"); - -namespace Nz -{ - using Int8 = int8_t; - using UInt8 = uint8_t; - - using Int16 = int16_t; - using UInt16 = uint16_t; - - using Int32 = int32_t; - using UInt32 = uint32_t; - - using Int64 = int64_t; - using UInt64 = uint64_t; -} - -#endif // NAZARA_PREREQUISITES_HPP diff --git a/include/Nazara/Renderer/Enums.hpp b/include/Nazara/Renderer/Enums.hpp index 9e4a92993..d4bfcabbd 100644 --- a/include/Nazara/Renderer/Enums.hpp +++ b/include/Nazara/Renderer/Enums.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_RENDERER_ENUMS_HPP #define NAZARA_RENDERER_ENUMS_HPP -#include +#include namespace Nz { diff --git a/include/Nazara/Renderer/RenderBufferView.hpp b/include/Nazara/Renderer/RenderBufferView.hpp index 61b3b329a..7f465bb47 100644 --- a/include/Nazara/Renderer/RenderBufferView.hpp +++ b/include/Nazara/Renderer/RenderBufferView.hpp @@ -8,8 +8,8 @@ #define NAZARA_RENDERER_RENDERBUFFERVIEW_HPP #include -#include #include +#include namespace Nz { diff --git a/include/Nazara/Renderer/RenderDevice.hpp b/include/Nazara/Renderer/RenderDevice.hpp index 6b87d8469..86be80a1a 100644 --- a/include/Nazara/Renderer/RenderDevice.hpp +++ b/include/Nazara/Renderer/RenderDevice.hpp @@ -18,9 +18,9 @@ #include #include #include -#include -#include #include +#include +#include #include #include @@ -44,9 +44,9 @@ namespace Nz virtual std::shared_ptr InstantiateRenderPass(std::vector attachments, std::vector subpassDescriptions, std::vector subpassDependencies) = 0; virtual std::shared_ptr InstantiateRenderPipeline(RenderPipelineInfo pipelineInfo) = 0; virtual std::shared_ptr InstantiateRenderPipelineLayout(RenderPipelineLayoutInfo pipelineLayoutInfo) = 0; - virtual std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) = 0; - virtual std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) = 0; - std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const std::filesystem::path& sourcePath, const ShaderWriter::States& states); + virtual std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) = 0; + virtual std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) = 0; + std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const std::filesystem::path& sourcePath, const nzsl::ShaderWriter::States& states); virtual std::shared_ptr InstantiateTexture(const TextureInfo& params) = 0; virtual std::shared_ptr InstantiateTextureSampler(const TextureSamplerInfo& params) = 0; diff --git a/include/Nazara/Renderer/RenderImage.inl b/include/Nazara/Renderer/RenderImage.inl index ea9f8c774..fc81def80 100644 --- a/include/Nazara/Renderer/RenderImage.inl +++ b/include/Nazara/Renderer/RenderImage.inl @@ -4,7 +4,7 @@ #include #include -#include +#include #include namespace Nz diff --git a/include/Nazara/Renderer/RenderPipelineLayout.hpp b/include/Nazara/Renderer/RenderPipelineLayout.hpp index 23b7071aa..3b03cb69f 100644 --- a/include/Nazara/Renderer/RenderPipelineLayout.hpp +++ b/include/Nazara/Renderer/RenderPipelineLayout.hpp @@ -7,10 +7,10 @@ #ifndef NAZARA_RENDERER_RENDERPIPELINELAYOUT_HPP #define NAZARA_RENDERER_RENDERPIPELINELAYOUT_HPP -#include #include #include -#include +#include +#include #include #include #include @@ -24,7 +24,7 @@ namespace Nz UInt32 setIndex = 0; UInt32 bindingIndex; ShaderBindingType type; - ShaderStageTypeFlags shaderStageFlags; + nzsl::ShaderStageTypeFlags shaderStageFlags; }; std::vector bindings; diff --git a/include/Nazara/Renderer/RenderTarget.hpp b/include/Nazara/Renderer/RenderTarget.hpp index 7f4a2581a..7b5ff0a6e 100644 --- a/include/Nazara/Renderer/RenderTarget.hpp +++ b/include/Nazara/Renderer/RenderTarget.hpp @@ -8,9 +8,9 @@ #define NAZARA_RENDERER_RENDERTARGET_HPP #include -#include #include #include +#include namespace Nz { diff --git a/include/Nazara/Renderer/Renderer.hpp b/include/Nazara/Renderer/Renderer.hpp index 29cd17967..14e228118 100644 --- a/include/Nazara/Renderer/Renderer.hpp +++ b/include/Nazara/Renderer/Renderer.hpp @@ -13,7 +13,6 @@ #include #include #include -#include namespace Nz { @@ -24,7 +23,7 @@ namespace Nz friend ModuleBase; public: - using Dependencies = TypeList; + using Dependencies = TypeList; struct Config; diff --git a/include/Nazara/Shader.hpp b/include/Nazara/Shader.hpp deleted file mode 100644 index fd6294611..000000000 --- a/include/Nazara/Shader.hpp +++ /dev/null @@ -1,58 +0,0 @@ -// this file was automatically generated and should not be edited - -/* - Nazara Engine - Shader module - - Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) - - 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. -*/ - -#pragma once - -#ifndef NAZARA_GLOBAL_SHADER_HPP -#define NAZARA_GLOBAL_SHADER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif // NAZARA_GLOBAL_SHADER_HPP diff --git a/include/Nazara/Shader/Ast/AstCloner.hpp b/include/Nazara/Shader/Ast/AstCloner.hpp deleted file mode 100644 index e9a5aa6f8..000000000 --- a/include/Nazara/Shader/Ast/AstCloner.hpp +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTCLONER_HPP -#define NAZARA_SHADER_AST_ASTCLONER_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstCloner : public AstExpressionVisitor, public AstStatementVisitor - { - public: - AstCloner() = default; - AstCloner(const AstCloner&) = delete; - AstCloner(AstCloner&&) = delete; - ~AstCloner() = default; - - template ExpressionValue Clone(const ExpressionValue& expressionValue); - inline ExpressionValue Clone(const ExpressionValue& expressionValue); - ExpressionPtr Clone(Expression& statement); - StatementPtr Clone(Statement& statement); - - AstCloner& operator=(const AstCloner&) = delete; - AstCloner& operator=(AstCloner&&) = delete; - - protected: - inline ExpressionPtr CloneExpression(const ExpressionPtr& expr); - inline StatementPtr CloneStatement(const StatementPtr& statement); - - virtual ExpressionPtr CloneExpression(Expression& expr); - virtual StatementPtr CloneStatement(Statement& statement); - virtual ExpressionValue CloneType(const ExpressionValue& exprType); - - virtual ExpressionPtr Clone(AccessIdentifierExpression& node); - virtual ExpressionPtr Clone(AccessIndexExpression& node); - virtual ExpressionPtr Clone(AliasValueExpression& node); - virtual ExpressionPtr Clone(AssignExpression& node); - virtual ExpressionPtr Clone(BinaryExpression& node); - virtual ExpressionPtr Clone(CallFunctionExpression& node); - virtual ExpressionPtr Clone(CallMethodExpression& node); - virtual ExpressionPtr Clone(CastExpression& node); - virtual ExpressionPtr Clone(ConditionalExpression& node); - virtual ExpressionPtr Clone(ConstantExpression& node); - virtual ExpressionPtr Clone(ConstantValueExpression& node); - virtual ExpressionPtr Clone(FunctionExpression& node); - virtual ExpressionPtr Clone(IdentifierExpression& node); - virtual ExpressionPtr Clone(IntrinsicExpression& node); - virtual ExpressionPtr Clone(IntrinsicFunctionExpression& node); - virtual ExpressionPtr Clone(StructTypeExpression& node); - virtual ExpressionPtr Clone(SwizzleExpression& node); - virtual ExpressionPtr Clone(TypeExpression& node); - virtual ExpressionPtr Clone(VariableValueExpression& node); - virtual ExpressionPtr Clone(UnaryExpression& node); - - virtual StatementPtr Clone(BranchStatement& node); - virtual StatementPtr Clone(ConditionalStatement& node); - virtual StatementPtr Clone(DeclareAliasStatement& node); - virtual StatementPtr Clone(DeclareConstStatement& node); - virtual StatementPtr Clone(DeclareExternalStatement& node); - virtual StatementPtr Clone(DeclareFunctionStatement& node); - virtual StatementPtr Clone(DeclareOptionStatement& node); - virtual StatementPtr Clone(DeclareStructStatement& node); - virtual StatementPtr Clone(DeclareVariableStatement& node); - virtual StatementPtr Clone(DiscardStatement& node); - virtual StatementPtr Clone(ExpressionStatement& node); - virtual StatementPtr Clone(ForStatement& node); - virtual StatementPtr Clone(ForEachStatement& node); - virtual StatementPtr Clone(ImportStatement& node); - virtual StatementPtr Clone(MultiStatement& node); - virtual StatementPtr Clone(NoOpStatement& node); - virtual StatementPtr Clone(ReturnStatement& node); - virtual StatementPtr Clone(ScopedStatement& node); - virtual StatementPtr Clone(WhileStatement& node); - -#define NAZARA_SHADERAST_NODE(NodeType) void Visit(NodeType& node) override; -#include - - void PushExpression(ExpressionPtr expression); - void PushStatement(StatementPtr statement); - - ExpressionPtr PopExpression(); - StatementPtr PopStatement(); - - private: - std::vector m_expressionStack; - std::vector m_statementStack; - }; - - template ExpressionValue Clone(const ExpressionValue& attribute); - inline ExpressionPtr Clone(Expression& node); - inline StatementPtr Clone(Statement& node); -} - -#include - -#endif // NAZARA_SHADER_AST_ASTCLONER_HPP diff --git a/include/Nazara/Shader/Ast/AstCloner.inl b/include/Nazara/Shader/Ast/AstCloner.inl deleted file mode 100644 index 29bc685a3..000000000 --- a/include/Nazara/Shader/Ast/AstCloner.inl +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - template - ExpressionValue AstCloner::Clone(const ExpressionValue& expressionValue) - { - if (!expressionValue.HasValue()) - return {}; - - if (expressionValue.IsExpression()) - return CloneExpression(expressionValue.GetExpression()); - else - { - assert(expressionValue.IsResultingValue()); - return expressionValue.GetResultingValue(); - } - } - - inline ExpressionValue AstCloner::Clone(const ExpressionValue& expressionValue) - { - return CloneType(expressionValue); - } - - ExpressionPtr AstCloner::CloneExpression(const ExpressionPtr& expr) - { - if (!expr) - return nullptr; - - return CloneExpression(*expr); - } - - StatementPtr AstCloner::CloneStatement(const StatementPtr& statement) - { - if (!statement) - return nullptr; - - return CloneStatement(*statement); - } - - - template - ExpressionValue Clone(const ExpressionValue& attribute) - { - AstCloner cloner; - return cloner.Clone(attribute); - } - - inline ExpressionPtr Clone(Expression& node) - { - AstCloner cloner; - return cloner.Clone(node); - } - - inline StatementPtr Clone(Statement& node) - { - AstCloner cloner; - return cloner.Clone(node); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/AstCompare.hpp b/include/Nazara/Shader/Ast/AstCompare.hpp deleted file mode 100644 index 06d4fc307..000000000 --- a/include/Nazara/Shader/Ast/AstCompare.hpp +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTCOMPARE_HPP -#define NAZARA_SHADER_AST_ASTCOMPARE_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - inline bool Compare(const Expression& lhs, const Expression& rhs); - inline bool Compare(const Module& lhs, const Module& rhs); - inline bool Compare(const Module::ImportedModule& lhs, const Module::ImportedModule& rhs); - inline bool Compare(const Module::Metadata& lhs, const Module::Metadata& rhs); - inline bool Compare(const Statement& lhs, const Statement& rhs); - - template bool Compare(const T& lhs, const T& rhs); - template bool Compare(const std::array& lhs, const std::array& rhs); - template bool Compare(const std::shared_ptr& lhs, const std::shared_ptr& rhs); - template bool Compare(const std::vector& lhs, const std::vector& rhs); - template bool Compare(const std::unique_ptr& lhs, const std::unique_ptr& rhs); - template bool Compare(const ExpressionValue& lhs, const ExpressionValue& rhs); - inline bool Compare(const AccessIdentifierExpression::Identifier& lhs, const AccessIdentifierExpression::Identifier& rhs); - inline bool Compare(const BranchStatement::ConditionalStatement& lhs, const BranchStatement::ConditionalStatement& rhs); - inline bool Compare(const DeclareExternalStatement::ExternalVar& lhs, const DeclareExternalStatement::ExternalVar& rhs); - inline bool Compare(const DeclareFunctionStatement::Parameter& lhs, const DeclareFunctionStatement::Parameter& rhs); - inline bool Compare(const ShaderLang::SourceLocation& lhs, const ShaderLang::SourceLocation& rhs); - inline bool Compare(const StructDescription& lhs, const StructDescription& rhs); - inline bool Compare(const StructDescription::StructMember& lhs, const StructDescription::StructMember& rhs); - - inline bool Compare(const AccessIdentifierExpression& lhs, const AccessIdentifierExpression& rhs); - inline bool Compare(const AccessIndexExpression& lhs, const AccessIndexExpression& rhs); - inline bool Compare(const AliasValueExpression& lhs, const AliasValueExpression& rhs); - inline bool Compare(const AssignExpression& lhs, const AssignExpression& rhs); - inline bool Compare(const BinaryExpression& lhs, const BinaryExpression& rhs); - inline bool Compare(const CallFunctionExpression& lhs, const CallFunctionExpression& rhs); - inline bool Compare(const CallMethodExpression& lhs, const CallMethodExpression& rhs); - inline bool Compare(const CastExpression& lhs, const CastExpression& rhs); - inline bool Compare(const ConditionalExpression& lhs, const ConditionalExpression& rhs); - inline bool Compare(const ConstantExpression& lhs, const ConstantExpression& rhs); - inline bool Compare(const ConstantValueExpression& lhs, const ConstantValueExpression& rhs); - inline bool Compare(const FunctionExpression& lhs, const FunctionExpression& rhs); - inline bool Compare(const IdentifierExpression& lhs, const IdentifierExpression& rhs); - inline bool Compare(const IntrinsicExpression& lhs, const IntrinsicExpression& rhs); - inline bool Compare(const IntrinsicFunctionExpression& lhs, const IntrinsicFunctionExpression& rhs); - inline bool Compare(const StructTypeExpression& lhs, const StructTypeExpression& rhs); - inline bool Compare(const SwizzleExpression& lhs, const SwizzleExpression& rhs); - inline bool Compare(const TypeExpression& lhs, const TypeExpression& rhs); - inline bool Compare(const VariableValueExpression& lhs, const VariableValueExpression& rhs); - inline bool Compare(const UnaryExpression& lhs, const UnaryExpression& rhs); - - inline bool Compare(const BranchStatement& lhs, const BranchStatement& rhs); - inline bool Compare(const ConditionalStatement& lhs, const ConditionalStatement& rhs); - inline bool Compare(const DeclareAliasStatement& lhs, const DeclareAliasStatement& rhs); - inline bool Compare(const DeclareConstStatement& lhs, const DeclareConstStatement& rhs); - inline bool Compare(const DeclareExternalStatement& lhs, const DeclareExternalStatement& rhs); - inline bool Compare(const DeclareFunctionStatement& lhs, const DeclareFunctionStatement& rhs); - inline bool Compare(const DeclareOptionStatement& lhs, const DeclareOptionStatement& rhs); - inline bool Compare(const DeclareStructStatement& lhs, const DeclareStructStatement& rhs); - inline bool Compare(const DeclareVariableStatement& lhs, const DeclareVariableStatement& rhs); - inline bool Compare(const DiscardStatement& lhs, const DiscardStatement& rhs); - inline bool Compare(const ExpressionStatement& lhs, const ExpressionStatement& rhs); - inline bool Compare(const ForStatement& lhs, const ForStatement& rhs); - inline bool Compare(const ForEachStatement& lhs, const ForEachStatement& rhs); - inline bool Compare(const ImportStatement& lhs, const ImportStatement& rhs); - inline bool Compare(const MultiStatement& lhs, const MultiStatement& rhs); - inline bool Compare(const NoOpStatement& lhs, const NoOpStatement& rhs); - inline bool Compare(const ReturnStatement& lhs, const ReturnStatement& rhs); - inline bool Compare(const ScopedStatement& lhs, const ScopedStatement& rhs); - inline bool Compare(const WhileStatement& lhs, const WhileStatement& rhs); -} - -#include - -#endif // NAZARA_SHADER_AST_ASTCOMPARE_HPP diff --git a/include/Nazara/Shader/Ast/AstCompare.inl b/include/Nazara/Shader/Ast/AstCompare.inl deleted file mode 100644 index 517853a3d..000000000 --- a/include/Nazara/Shader/Ast/AstCompare.inl +++ /dev/null @@ -1,725 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - inline bool Compare(const Expression& lhs, const Expression& rhs) - { - if (lhs.GetType() != rhs.GetType()) - return false; - - if (!Compare(lhs.sourceLocation, rhs.sourceLocation)) - return false; - - switch (lhs.GetType()) - { - case NodeType::None: break; - -#define NAZARA_SHADERAST_EXPRESSION(Node) case NodeType::Node: return Compare(static_cast(lhs), static_cast(lhs)); -#include - - default: throw std::runtime_error("unexpected node type"); - } - - return true; - } - - bool Compare(const Module& lhs, const Module& rhs) - { - if (!Compare(*lhs.metadata, *rhs.metadata)) - return false; - - if (!Compare(lhs.importedModules, rhs.importedModules)) - return false; - - if (!Compare(*lhs.rootNode, *rhs.rootNode)) - return false; - - return true; - } - - bool Compare(const Module::ImportedModule& lhs, const Module::ImportedModule& rhs) - { - if (!Compare(lhs.identifier, rhs.identifier)) - return false; - - if (!Compare(*lhs.module, *rhs.module)) - return false; - - return false; - } - - bool Compare(const Module::Metadata& lhs, const Module::Metadata& rhs) - { - if (!Compare(lhs.moduleId, rhs.moduleId)) - return false; - - if (!Compare(lhs.moduleName, rhs.moduleName)) - return false; - - if (!Compare(lhs.shaderLangVersion, rhs.shaderLangVersion)) - return false; - - return true; - } - - inline bool Compare(const Statement& lhs, const Statement& rhs) - { - if (lhs.GetType() != rhs.GetType()) - return false; - - if (!Compare(lhs.sourceLocation, rhs.sourceLocation)) - return false; - - switch (lhs.GetType()) - { - case NodeType::None: break; - -#define NAZARA_SHADERAST_STATEMENT(Node) case NodeType::Node: return Compare(static_cast(lhs), static_cast(lhs)); -#include - - default: throw std::runtime_error("unexpected node type"); - } - - return false; - } - - template - bool Compare(const T& lhs, const T& rhs) - { - return lhs == rhs; - } - - template - bool Compare(const std::array& lhs, const std::array& rhs) - { - for (std::size_t i = 0; i < S; ++i) - { - if (!Compare(lhs[i], rhs[i])) - return false; - } - - return true; - } - - template - bool Compare(const std::shared_ptr& lhs, const std::shared_ptr& rhs) - { - if (lhs == nullptr) - return rhs == nullptr; - else if (rhs == nullptr) - return false; - - return Compare(*lhs, *rhs); - } - - template - bool Compare(const std::vector& lhs, const std::vector& rhs) - { - if (lhs.size() != rhs.size()) - return false; - - for (std::size_t i = 0; i < lhs.size(); ++i) - { - if (!Compare(lhs[i], rhs[i])) - return false; - } - - return true; - } - - template - bool Compare(const std::unique_ptr& lhs, const std::unique_ptr& rhs) - { - if (lhs == nullptr) - return rhs == nullptr; - else if (rhs == nullptr) - return false; - - return Compare(*lhs, *rhs); - } - - template - bool Compare(const ExpressionValue& lhs, const ExpressionValue& rhs) - { - if (!Compare(lhs.HasValue(), rhs.HasValue())) - return false; - - if (!Compare(lhs.IsResultingValue(), rhs.IsResultingValue())) - return false; - - if (!Compare(lhs.IsExpression(), rhs.IsExpression())) - return false; - - if (lhs.IsExpression()) - { - if (!Compare(lhs.GetExpression(), rhs.GetExpression())) - return false; - } - else if (lhs.IsResultingValue()) - { - if (!Compare(lhs.GetResultingValue(), rhs.GetResultingValue())) - return false; - } - - return true; - } - - bool Compare(const AccessIdentifierExpression::Identifier& lhs, const AccessIdentifierExpression::Identifier& rhs) - { - if (!Compare(lhs.identifier, rhs.identifier)) - return false; - - if (!Compare(lhs.sourceLocation, rhs.sourceLocation)) - return false; - - return true; - } - - inline bool Compare(const BranchStatement::ConditionalStatement& lhs, const BranchStatement::ConditionalStatement& rhs) - { - if (!Compare(lhs.condition, rhs.condition)) - return false; - - if (!Compare(lhs.statement, rhs.statement)) - return false; - - return true; - } - - inline bool Compare(const DeclareExternalStatement::ExternalVar& lhs, const DeclareExternalStatement::ExternalVar& rhs) - { - if (!Compare(lhs.bindingIndex, rhs.bindingIndex)) - return false; - - if (!Compare(lhs.bindingSet, rhs.bindingSet)) - return false; - - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.type, rhs.type)) - return false; - - if (!Compare(lhs.sourceLocation, rhs.sourceLocation)) - return false; - - return true; - } - - inline bool Compare(const DeclareFunctionStatement::Parameter& lhs, const DeclareFunctionStatement::Parameter& rhs) - { - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.type, rhs.type)) - return false; - - if (!Compare(lhs.sourceLocation, rhs.sourceLocation)) - return false; - - return true; - } - - bool Compare(const ShaderLang::SourceLocation& lhs, const ShaderLang::SourceLocation& rhs) - { - if (!Compare(lhs.endColumn, rhs.endColumn)) - return false; - - if (!Compare(lhs.endLine, rhs.endLine)) - return false; - - if (!Compare(lhs.startColumn, rhs.startColumn)) - return false; - - if (!Compare(lhs.startLine, rhs.startLine)) - return false; - - if (!Compare(lhs.file, rhs.file)) - return false; - - return true; - } - - inline bool Compare(const StructDescription& lhs, const StructDescription& rhs) - { - if (!Compare(lhs.layout, rhs.layout)) - return false; - - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.members, rhs.members)) - return false; - - return true; - } - - inline bool Compare(const StructDescription::StructMember& lhs, const StructDescription::StructMember& rhs) - { - if (!Compare(lhs.builtin, rhs.builtin)) - return false; - - if (!Compare(lhs.cond, rhs.cond)) - return false; - - if (!Compare(lhs.locationIndex, rhs.locationIndex)) - return false; - - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.type, rhs.type)) - return false; - - if (!Compare(lhs.sourceLocation, rhs.sourceLocation)) - return false; - - return true; - } - - inline bool Compare(const AccessIdentifierExpression& lhs, const AccessIdentifierExpression& rhs) - { - if (!Compare(*lhs.expr, *rhs.expr)) - return false; - - if (!Compare(lhs.identifiers, rhs.identifiers)) - return false; - - return true; - } - - inline bool Compare(const AccessIndexExpression& lhs, const AccessIndexExpression& rhs) - { - if (!Compare(*lhs.expr, *rhs.expr)) - return false; - - if (!Compare(lhs.indices, rhs.indices)) - return false; - - return true; - } - - bool Compare(const AliasValueExpression& lhs, const AliasValueExpression& rhs) - { - if (!Compare(lhs.aliasId, rhs.aliasId)) - return false; - - return true; - } - - inline bool Compare(const AssignExpression& lhs, const AssignExpression& rhs) - { - if (!Compare(lhs.op, rhs.op)) - return false; - - if (!Compare(lhs.left, rhs.left)) - return false; - - if (!Compare(lhs.right, rhs.right)) - return false; - - return true; - } - - inline bool Compare(const BinaryExpression& lhs, const BinaryExpression& rhs) - { - if (!Compare(lhs.op, rhs.op)) - return false; - - if (!Compare(lhs.left, rhs.left)) - return false; - - if (!Compare(lhs.right, rhs.right)) - return false; - - return true; - } - - inline bool Compare(const CallFunctionExpression& lhs, const CallFunctionExpression& rhs) - { - if (!Compare(lhs.targetFunction, rhs.targetFunction)) - return false; - - if (!Compare(lhs.parameters, rhs.parameters)) - return false; - - return true; - } - - inline bool Compare(const CallMethodExpression& lhs, const CallMethodExpression& rhs) - { - if (!Compare(lhs.methodName, rhs.methodName)) - return false; - - if (!Compare(lhs.object, rhs.object)) - return false; - - if (!Compare(lhs.parameters, rhs.parameters)) - return false; - - return true; - } - - inline bool Compare(const CastExpression& lhs, const CastExpression& rhs) - { - if (!Compare(lhs.targetType, rhs.targetType)) - return false; - - if (!Compare(lhs.expressions, rhs.expressions)) - return false; - - return true; - } - - inline bool Compare(const ConditionalExpression& lhs, const ConditionalExpression& rhs) - { - if (!Compare(lhs.condition, rhs.condition)) - return false; - - if (!Compare(lhs.truePath, rhs.truePath)) - return false; - - if (!Compare(lhs.falsePath, rhs.falsePath)) - return false; - - return true; - } - - inline bool Compare(const ConstantExpression& lhs, const ConstantExpression& rhs) - { - if (!Compare(lhs.constantId, rhs.constantId)) - return false; - - return true; - } - - inline bool Compare(const ConstantValueExpression& lhs, const ConstantValueExpression& rhs) - { - if (!Compare(lhs.value, rhs.value)) - return false; - - return true; - } - - inline bool Compare(const FunctionExpression& lhs, const FunctionExpression& rhs) - { - if (!Compare(lhs.funcId, rhs.funcId)) - return false; - - return true; - } - - inline bool Compare(const IdentifierExpression& lhs, const IdentifierExpression& rhs) - { - if (!Compare(lhs.identifier, rhs.identifier)) - return false; - - return true; - } - - inline bool Compare(const IntrinsicExpression& lhs, const IntrinsicExpression& rhs) - { - if (!Compare(lhs.intrinsic, rhs.intrinsic)) - return false; - - if (!Compare(lhs.parameters, rhs.parameters)) - return false; - - return true; - } - - inline bool Compare(const IntrinsicFunctionExpression& lhs, const IntrinsicFunctionExpression& rhs) - { - if (!Compare(lhs.intrinsicId, rhs.intrinsicId)) - return false; - - return true; - } - - inline bool Compare(const StructTypeExpression& lhs, const StructTypeExpression& rhs) - { - if (!Compare(lhs.structTypeId, rhs.structTypeId)) - return false; - - return true; - } - - inline bool Compare(const SwizzleExpression& lhs, const SwizzleExpression& rhs) - { - if (!Compare(lhs.componentCount, rhs.componentCount)) - return false; - - if (!Compare(lhs.expression, rhs.expression)) - return false; - - if (!Compare(lhs.components, rhs.components)) - return false; - - return true; - } - - bool Compare(const TypeExpression& lhs, const TypeExpression& rhs) - { - if (!Compare(lhs.typeId, rhs.typeId)) - return false; - - return true; - } - - inline bool Compare(const VariableValueExpression& lhs, const VariableValueExpression& rhs) - { - if (!Compare(lhs.variableId, rhs.variableId)) - return false; - - return true; - } - - inline bool Compare(const UnaryExpression& lhs, const UnaryExpression& rhs) - { - if (!Compare(lhs.op, rhs.op)) - return false; - - if (!Compare(lhs.expression, rhs.expression)) - return false; - - return true; - } - - inline bool Compare(const BranchStatement& lhs, const BranchStatement& rhs) - { - if (!Compare(lhs.isConst, rhs.isConst)) - return false; - - if (!Compare(lhs.elseStatement, rhs.elseStatement)) - return false; - - if (!Compare(lhs.condStatements, rhs.condStatements)) - return false; - - return true; - } - - inline bool Compare(const ConditionalStatement& lhs, const ConditionalStatement& rhs) - { - if (!Compare(lhs.condition, rhs.condition)) - return false; - - if (!Compare(lhs.statement, rhs.statement)) - return false; - - return true; - } - - bool Compare(const DeclareAliasStatement& lhs, const DeclareAliasStatement& rhs) - { - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.expression, rhs.expression)) - return false; - - return true; - } - - inline bool Compare(const DeclareConstStatement& lhs, const DeclareConstStatement& rhs) - { - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.type, rhs.type)) - return false; - - if (!Compare(lhs.expression, rhs.expression)) - return false; - - return true; - } - - inline bool Compare(const DeclareExternalStatement& lhs, const DeclareExternalStatement& rhs) - { - if (!Compare(lhs.bindingSet, rhs.bindingSet)) - return false; - - if (!Compare(lhs.externalVars, rhs.externalVars)) - return false; - - return true; - } - - inline bool Compare(const DeclareFunctionStatement& lhs, const DeclareFunctionStatement& rhs) - { - if (!Compare(lhs.depthWrite, rhs.depthWrite)) - return false; - - if (!Compare(lhs.earlyFragmentTests, rhs.earlyFragmentTests)) - return false; - - if (!Compare(lhs.entryStage, rhs.entryStage)) - return false; - - if (!Compare(lhs.isExported, rhs.isExported)) - return false; - - if (!Compare(lhs.name, rhs.name)) - return false; - - if (!Compare(lhs.parameters, rhs.parameters)) - return false; - - if (!Compare(lhs.returnType, rhs.returnType)) - return false; - - if (!Compare(lhs.statements, rhs.statements)) - return false; - - return true; - } - - inline bool Compare(const DeclareOptionStatement& lhs, const DeclareOptionStatement& rhs) - { - if (!Compare(lhs.optName, rhs.optName)) - return false; - - if (!Compare(lhs.optType, rhs.optType)) - return false; - - if (!Compare(lhs.defaultValue, rhs.defaultValue)) - return false; - - return true; - } - - inline bool Compare(const DeclareStructStatement& lhs, const DeclareStructStatement& rhs) - { - if (!Compare(lhs.description, rhs.description)) - return false; - - return true; - } - - inline bool Compare(const DeclareVariableStatement& lhs, const DeclareVariableStatement& rhs) - { - if (!Compare(lhs.varName, rhs.varName)) - return false; - - if (!Compare(lhs.varType, rhs.varType)) - return false; - - if (!Compare(lhs.initialExpression, rhs.initialExpression)) - return false; - - return true; - } - - inline bool Compare(const DiscardStatement& /*lhs*/, const DiscardStatement& /*rhs*/) - { - return true; - } - - inline bool Compare(const ExpressionStatement& lhs, const ExpressionStatement& rhs) - { - if (!Compare(lhs.expression, rhs.expression)) - return false; - - return true; - } - - bool Compare(const ForStatement& lhs, const ForStatement& rhs) - { - if (!Compare(lhs.varName, rhs.varName)) - return false; - - if (!Compare(lhs.unroll, rhs.unroll)) - return false; - - if (!Compare(lhs.fromExpr, rhs.fromExpr)) - return false; - - if (!Compare(lhs.toExpr, rhs.toExpr)) - return false; - - if (!Compare(lhs.stepExpr, rhs.stepExpr)) - return false; - - if (!Compare(lhs.statement, rhs.statement)) - return false; - - return true; - } - - bool Compare(const ForEachStatement& lhs, const ForEachStatement& rhs) - { - if (!Compare(lhs.varName, rhs.varName)) - return false; - - if (!Compare(lhs.unroll, rhs.unroll)) - return false; - - if (!Compare(lhs.expression, rhs.expression)) - return false; - - if (!Compare(lhs.statement, rhs.statement)) - return false; - - return true; - } - - bool Compare(const ImportStatement& lhs, const ImportStatement& rhs) - { - if (!Compare(lhs.moduleName, rhs.moduleName)) - return false; - - return true; - } - - inline bool Compare(const MultiStatement& lhs, const MultiStatement& rhs) - { - if (!Compare(lhs.statements, rhs.statements)) - return false; - - return true; - } - - inline bool Compare(const NoOpStatement& /*lhs*/, const NoOpStatement& /*rhs*/) - { - return true; - } - - inline bool Compare(const ReturnStatement& lhs, const ReturnStatement& rhs) - { - if (!Compare(lhs.returnExpr, rhs.returnExpr)) - return false; - - return true; - } - - bool Compare(const ScopedStatement& lhs, const ScopedStatement& rhs) - { - if (!Compare(lhs.statement, rhs.statement)) - return false; - - return true; - } - - inline bool Compare(const WhileStatement& lhs, const WhileStatement& rhs) - { - if (!Compare(lhs.unroll, rhs.unroll)) - return false; - - if (!Compare(lhs.condition, rhs.condition)) - return false; - - if (!Compare(lhs.body, rhs.body)) - return false; - - return true; - } -} - -#include diff --git a/include/Nazara/Shader/Ast/AstConstantPropagationVisitor.hpp b/include/Nazara/Shader/Ast/AstConstantPropagationVisitor.hpp deleted file mode 100644 index d6e3bbf42..000000000 --- a/include/Nazara/Shader/Ast/AstConstantPropagationVisitor.hpp +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTCONSTANTPROPAGATIONVISITOR_HPP -#define NAZARA_SHADER_AST_ASTCONSTANTPROPAGATIONVISITOR_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstConstantPropagationVisitor : public AstCloner - { - public: - struct Options; - - AstConstantPropagationVisitor() = default; - AstConstantPropagationVisitor(const AstConstantPropagationVisitor&) = delete; - AstConstantPropagationVisitor(AstConstantPropagationVisitor&&) = delete; - ~AstConstantPropagationVisitor() = default; - - inline ExpressionPtr Process(Expression& expression); - inline ExpressionPtr Process(Expression& expression, const Options& options); - ModulePtr Process(const Module& shaderModule); - ModulePtr Process(const Module& shaderModule, const Options& options); - inline StatementPtr Process(Statement& statement); - inline StatementPtr Process(Statement& statement, const Options& options); - - AstConstantPropagationVisitor& operator=(const AstConstantPropagationVisitor&) = delete; - AstConstantPropagationVisitor& operator=(AstConstantPropagationVisitor&&) = delete; - - struct Options - { - std::function constantQueryCallback; - }; - - protected: - ExpressionPtr Clone(BinaryExpression& node) override; - ExpressionPtr Clone(CastExpression& node) override; - ExpressionPtr Clone(ConditionalExpression& node) override; - ExpressionPtr Clone(ConstantExpression& node) override; - ExpressionPtr Clone(SwizzleExpression& node) override; - ExpressionPtr Clone(UnaryExpression& node) override; - StatementPtr Clone(BranchStatement& node) override; - StatementPtr Clone(ConditionalStatement& node) override; - - template ExpressionPtr PropagateBinaryConstant(const ConstantValueExpression& lhs, const ConstantValueExpression& rhs); - template ExpressionPtr PropagateSingleValueCast(const ConstantValueExpression& operand); - template ExpressionPtr PropagateConstantSwizzle(const std::array& components, const ConstantValueExpression& operand); - template ExpressionPtr PropagateUnaryConstant(const ConstantValueExpression& operand); - template ExpressionPtr PropagateVec2Cast(TargetType v1, TargetType v2); - template ExpressionPtr PropagateVec3Cast(TargetType v1, TargetType v2, TargetType v3); - template ExpressionPtr PropagateVec4Cast(TargetType v1, TargetType v2, TargetType v3, TargetType v4); - - StatementPtr Unscope(StatementPtr node); - - private: - Options m_options; - }; - - inline ExpressionPtr PropagateConstants(Expression& expr); - inline ExpressionPtr PropagateConstants(Expression& expr, const AstConstantPropagationVisitor::Options& options); - inline ModulePtr PropagateConstants(const Module& shaderModule); - inline ModulePtr PropagateConstants(const Module& shaderModule, const AstConstantPropagationVisitor::Options& options); - inline StatementPtr PropagateConstants(Statement& ast); - inline StatementPtr PropagateConstants(Statement& ast, const AstConstantPropagationVisitor::Options& options); -} - -#include - -#endif // NAZARA_SHADER_AST_ASTCONSTANTPROPAGATIONVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/AstConstantPropagationVisitor.inl b/include/Nazara/Shader/Ast/AstConstantPropagationVisitor.inl deleted file mode 100644 index f24278bc3..000000000 --- a/include/Nazara/Shader/Ast/AstConstantPropagationVisitor.inl +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - inline ExpressionPtr AstConstantPropagationVisitor::Process(Expression& expression) - { - m_options = {}; - return CloneExpression(expression); - } - - inline ExpressionPtr AstConstantPropagationVisitor::Process(Expression& expression, const Options& options) - { - m_options = options; - return CloneExpression(expression); - } - - inline StatementPtr AstConstantPropagationVisitor::Process(Statement& statement) - { - m_options = {}; - return CloneStatement(statement); - } - - inline StatementPtr AstConstantPropagationVisitor::Process(Statement& statement, const Options& options) - { - m_options = options; - return CloneStatement(statement); - } - - inline ExpressionPtr PropagateConstants(Expression& ast) - { - AstConstantPropagationVisitor optimize; - return optimize.Process(ast); - } - - inline ExpressionPtr PropagateConstants(Expression& ast, const AstConstantPropagationVisitor::Options& options) - { - AstConstantPropagationVisitor optimize; - return optimize.Process(ast, options); - } - - inline ModulePtr PropagateConstants(const Module& shaderModule) - { - AstConstantPropagationVisitor optimize; - return optimize.Process(shaderModule); - } - - inline ModulePtr PropagateConstants(const Module& shaderModule, const AstConstantPropagationVisitor::Options& options) - { - AstConstantPropagationVisitor optimize; - return optimize.Process(shaderModule, options); - } - - inline StatementPtr PropagateConstants(Statement& ast) - { - AstConstantPropagationVisitor optimize; - return optimize.Process(ast); - } - - inline StatementPtr PropagateConstants(Statement& ast, const AstConstantPropagationVisitor::Options& options) - { - AstConstantPropagationVisitor optimize; - return optimize.Process(ast, options); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/AstExportVisitor.hpp b/include/Nazara/Shader/Ast/AstExportVisitor.hpp deleted file mode 100644 index baeab0701..000000000 --- a/include/Nazara/Shader/Ast/AstExportVisitor.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTEXPORTVISITOR_HPP -#define NAZARA_SHADER_AST_ASTEXPORTVISITOR_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstExportVisitor : public AstRecursiveVisitor - { - public: - struct Callbacks; - - AstExportVisitor() = default; - AstExportVisitor(const AstExportVisitor&) = delete; - AstExportVisitor(AstExportVisitor&&) = delete; - ~AstExportVisitor() = default; - - void Visit(Statement& statement, const Callbacks& callbacks); - - AstExportVisitor& operator=(const AstExportVisitor&) = delete; - AstExportVisitor& operator=(AstExportVisitor&&) = delete; - - struct Callbacks - { - std::function onExportedFunc; - std::function onExportedStruct; - }; - - private: - void Visit(DeclareFunctionStatement& node) override; - void Visit(DeclareStructStatement& node) override; - - const Callbacks* m_callbacks; - }; -} - -#include - -#endif // NAZARA_SHADER_AST_ASTEXPORTVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/AstExportVisitor.inl b/include/Nazara/Shader/Ast/AstExportVisitor.inl deleted file mode 100644 index 84c3f06b6..000000000 --- a/include/Nazara/Shader/Ast/AstExportVisitor.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ -} - -#include diff --git a/include/Nazara/Shader/Ast/AstExpressionVisitor.hpp b/include/Nazara/Shader/Ast/AstExpressionVisitor.hpp deleted file mode 100644 index 86d69d83a..000000000 --- a/include/Nazara/Shader/Ast/AstExpressionVisitor.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTEXPRESSIONVISITOR_HPP -#define NAZARA_SHADER_AST_ASTEXPRESSIONVISITOR_HPP - -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstExpressionVisitor - { - public: - AstExpressionVisitor() = default; - AstExpressionVisitor(const AstExpressionVisitor&) = delete; - AstExpressionVisitor(AstExpressionVisitor&&) = delete; - virtual ~AstExpressionVisitor(); - -#define NAZARA_SHADERAST_EXPRESSION(Node) virtual void Visit(Node& node) = 0; -#include - - AstExpressionVisitor& operator=(const AstExpressionVisitor&) = delete; - AstExpressionVisitor& operator=(AstExpressionVisitor&&) = delete; - }; -} - -#endif // NAZARA_SHADER_AST_ASTEXPRESSIONVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/AstExpressionVisitorExcept.hpp b/include/Nazara/Shader/Ast/AstExpressionVisitorExcept.hpp deleted file mode 100644 index 568d1bb69..000000000 --- a/include/Nazara/Shader/Ast/AstExpressionVisitorExcept.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTEXPRESSIONVISITOREXCEPT_HPP -#define NAZARA_SHADER_AST_ASTEXPRESSIONVISITOREXCEPT_HPP - -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstExpressionVisitorExcept : public AstExpressionVisitor - { - public: - using AstExpressionVisitor::Visit; - -#define NAZARA_SHADERAST_EXPRESSION(Node) void Visit(ShaderAst::Node& node) override; -#include - }; -} - -#endif // NAZARA_SHADER_AST_ASTEXPRESSIONVISITOREXCEPT_HPP diff --git a/include/Nazara/Shader/Ast/AstNodeList.hpp b/include/Nazara/Shader/Ast/AstNodeList.hpp deleted file mode 100644 index 999aa6e67..000000000 --- a/include/Nazara/Shader/Ast/AstNodeList.hpp +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// no header guards - -#if !defined(NAZARA_SHADERAST_NODE) && !defined(NAZARA_SHADERAST_EXPRESSION) && !defined(NAZARA_SHADERAST_STATEMENT) -#error You must define NAZARA_SHADERAST_NODE or NAZARA_SHADERAST_EXPRESSION or NAZARA_SHADERAST_STATEMENT before including this file -#endif - -#ifndef NAZARA_SHADERAST_NODE -#define NAZARA_SHADERAST_NODE(X) -#endif - -#ifndef NAZARA_SHADERAST_NODE_LAST -#define NAZARA_SHADERAST_NODE_LAST(X) -#endif - -#ifndef NAZARA_SHADERAST_EXPRESSION -#define NAZARA_SHADERAST_EXPRESSION(X) NAZARA_SHADERAST_NODE(X) -#endif - -#ifndef NAZARA_SHADERAST_STATEMENT -#define NAZARA_SHADERAST_STATEMENT(X) NAZARA_SHADERAST_NODE(X) -#endif - -#ifndef NAZARA_SHADERAST_STATEMENT_LAST -#define NAZARA_SHADERAST_STATEMENT_LAST(X) NAZARA_SHADERAST_STATEMENT(X) -#endif - -NAZARA_SHADERAST_EXPRESSION(AccessIdentifierExpression) -NAZARA_SHADERAST_EXPRESSION(AccessIndexExpression) -NAZARA_SHADERAST_EXPRESSION(AliasValueExpression) -NAZARA_SHADERAST_EXPRESSION(AssignExpression) -NAZARA_SHADERAST_EXPRESSION(BinaryExpression) -NAZARA_SHADERAST_EXPRESSION(CallFunctionExpression) -NAZARA_SHADERAST_EXPRESSION(CallMethodExpression) -NAZARA_SHADERAST_EXPRESSION(CastExpression) -NAZARA_SHADERAST_EXPRESSION(ConditionalExpression) -NAZARA_SHADERAST_EXPRESSION(ConstantExpression) -NAZARA_SHADERAST_EXPRESSION(ConstantValueExpression) -NAZARA_SHADERAST_EXPRESSION(FunctionExpression) -NAZARA_SHADERAST_EXPRESSION(IdentifierExpression) -NAZARA_SHADERAST_EXPRESSION(IntrinsicExpression) -NAZARA_SHADERAST_EXPRESSION(IntrinsicFunctionExpression) -NAZARA_SHADERAST_EXPRESSION(StructTypeExpression) -NAZARA_SHADERAST_EXPRESSION(SwizzleExpression) -NAZARA_SHADERAST_EXPRESSION(TypeExpression) -NAZARA_SHADERAST_EXPRESSION(VariableValueExpression) -NAZARA_SHADERAST_EXPRESSION(UnaryExpression) -NAZARA_SHADERAST_STATEMENT(BranchStatement) -NAZARA_SHADERAST_STATEMENT(ConditionalStatement) -NAZARA_SHADERAST_STATEMENT(DeclareAliasStatement) -NAZARA_SHADERAST_STATEMENT(DeclareConstStatement) -NAZARA_SHADERAST_STATEMENT(DeclareExternalStatement) -NAZARA_SHADERAST_STATEMENT(DeclareFunctionStatement) -NAZARA_SHADERAST_STATEMENT(DeclareOptionStatement) -NAZARA_SHADERAST_STATEMENT(DeclareStructStatement) -NAZARA_SHADERAST_STATEMENT(DeclareVariableStatement) -NAZARA_SHADERAST_STATEMENT(DiscardStatement) -NAZARA_SHADERAST_STATEMENT(ForStatement) -NAZARA_SHADERAST_STATEMENT(ForEachStatement) -NAZARA_SHADERAST_STATEMENT(ExpressionStatement) -NAZARA_SHADERAST_STATEMENT(ImportStatement) -NAZARA_SHADERAST_STATEMENT(MultiStatement) -NAZARA_SHADERAST_STATEMENT(NoOpStatement) -NAZARA_SHADERAST_STATEMENT(ReturnStatement) -NAZARA_SHADERAST_STATEMENT(ScopedStatement) -NAZARA_SHADERAST_STATEMENT_LAST(WhileStatement) - -#undef NAZARA_SHADERAST_EXPRESSION -#undef NAZARA_SHADERAST_NODE -#undef NAZARA_SHADERAST_NODE_LAST -#undef NAZARA_SHADERAST_STATEMENT -#undef NAZARA_SHADERAST_STATEMENT_LAST diff --git a/include/Nazara/Shader/Ast/AstRecursiveVisitor.hpp b/include/Nazara/Shader/Ast/AstRecursiveVisitor.hpp deleted file mode 100644 index e297be085..000000000 --- a/include/Nazara/Shader/Ast/AstRecursiveVisitor.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTRECURSIVEVISITOR_HPP -#define NAZARA_SHADER_AST_ASTRECURSIVEVISITOR_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstRecursiveVisitor : public AstExpressionVisitor, public AstStatementVisitor - { - public: - AstRecursiveVisitor() = default; - ~AstRecursiveVisitor() = default; - - void Visit(AccessIdentifierExpression& node) override; - void Visit(AccessIndexExpression& node) override; - void Visit(AliasValueExpression& node) override; - void Visit(AssignExpression& node) override; - void Visit(BinaryExpression& node) override; - void Visit(CallFunctionExpression& node) override; - void Visit(CallMethodExpression& node) override; - void Visit(CastExpression& node) override; - void Visit(ConditionalExpression& node) override; - void Visit(ConstantValueExpression& node) override; - void Visit(ConstantExpression& node) override; - void Visit(FunctionExpression& node) override; - void Visit(IdentifierExpression& node) override; - void Visit(IntrinsicExpression& node) override; - void Visit(IntrinsicFunctionExpression& node) override; - void Visit(StructTypeExpression& node) override; - void Visit(SwizzleExpression& node) override; - void Visit(TypeExpression& node) override; - void Visit(VariableValueExpression& node) override; - void Visit(UnaryExpression& node) override; - - void Visit(BranchStatement& node) override; - void Visit(ConditionalStatement& node) override; - void Visit(DeclareAliasStatement& node) override; - void Visit(DeclareConstStatement& node) override; - void Visit(DeclareExternalStatement& node) override; - void Visit(DeclareFunctionStatement& node) override; - void Visit(DeclareOptionStatement& node) override; - void Visit(DeclareStructStatement& node) override; - void Visit(DeclareVariableStatement& node) override; - void Visit(DiscardStatement& node) override; - void Visit(ExpressionStatement& node) override; - void Visit(ForStatement& node) override; - void Visit(ForEachStatement& node) override; - void Visit(ImportStatement& node) override; - void Visit(MultiStatement& node) override; - void Visit(NoOpStatement& node) override; - void Visit(ReturnStatement& node) override; - void Visit(ScopedStatement& node) override; - void Visit(WhileStatement& node) override; - }; -} - -#include - -#endif // NAZARA_SHADER_AST_ASTRECURSIVEVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/AstRecursiveVisitor.inl b/include/Nazara/Shader/Ast/AstRecursiveVisitor.inl deleted file mode 100644 index cd91a745a..000000000 --- a/include/Nazara/Shader/Ast/AstRecursiveVisitor.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Shader/Ast/AstReflect.hpp b/include/Nazara/Shader/Ast/AstReflect.hpp deleted file mode 100644 index a52216fc4..000000000 --- a/include/Nazara/Shader/Ast/AstReflect.hpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTREFLECT_HPP -#define NAZARA_SHADER_AST_ASTREFLECT_HPP - -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstReflect : public AstRecursiveVisitor - { - public: - struct Callbacks; - - AstReflect() = default; - AstReflect(const AstReflect&) = delete; - AstReflect(AstReflect&&) = delete; - ~AstReflect() = default; - - void Reflect(Statement& statement, const Callbacks& callbacks); - - AstReflect& operator=(const AstReflect&) = delete; - AstReflect& operator=(AstReflect&&) = delete; - - struct Callbacks - { - std::function onEntryPointDeclaration; - - std::function onAliasDeclaration; - std::function onConstDeclaration; - std::function onExternalDeclaration; - std::function onFunctionDeclaration; - std::function onOptionDeclaration; - std::function onStructDeclaration; - std::function onVariableDeclaration; - - std::function onAliasIndex; - std::function onConstIndex; - std::function onFunctionIndex; - std::function onOptionIndex; - std::function onStructIndex; - std::function onVariableIndex; - }; - - private: - void Visit(DeclareAliasStatement& node) override; - void Visit(DeclareConstStatement& node) override; - void Visit(DeclareExternalStatement& node) override; - void Visit(DeclareFunctionStatement& node) override; - void Visit(DeclareOptionStatement& node) override; - void Visit(DeclareStructStatement& node) override; - void Visit(DeclareVariableStatement& node) override; - void Visit(ForStatement& node) override; - void Visit(ForEachStatement& node) override; - - const Callbacks* m_callbacks; - }; -} - -#include - -#endif // NAZARA_SHADER_AST_ASTREFLECT_HPP diff --git a/include/Nazara/Shader/Ast/AstReflect.inl b/include/Nazara/Shader/Ast/AstReflect.inl deleted file mode 100644 index 222aef3ac..000000000 --- a/include/Nazara/Shader/Ast/AstReflect.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ -} - -#include diff --git a/include/Nazara/Shader/Ast/AstSerializer.hpp b/include/Nazara/Shader/Ast/AstSerializer.hpp deleted file mode 100644 index 15dee98a7..000000000 --- a/include/Nazara/Shader/Ast/AstSerializer.hpp +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTSERIALIZER_HPP -#define NAZARA_SHADER_AST_ASTSERIALIZER_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstSerializerBase - { - public: - AstSerializerBase() = default; - AstSerializerBase(const AstSerializerBase&) = delete; - AstSerializerBase(AstSerializerBase&&) = delete; - ~AstSerializerBase() = default; - - void Serialize(AccessIdentifierExpression& node); - void Serialize(AccessIndexExpression& node); - void Serialize(AliasValueExpression& node); - void Serialize(AssignExpression& node); - void Serialize(BinaryExpression& node); - void Serialize(CallFunctionExpression& node); - void Serialize(CallMethodExpression& node); - void Serialize(CastExpression& node); - void Serialize(ConstantExpression& node); - void Serialize(ConditionalExpression& node); - void Serialize(ConstantValueExpression& node); - void Serialize(FunctionExpression& node); - void Serialize(IdentifierExpression& node); - void Serialize(IntrinsicExpression& node); - void Serialize(IntrinsicFunctionExpression& node); - void Serialize(StructTypeExpression& node); - void Serialize(SwizzleExpression& node); - void Serialize(TypeExpression& node); - void Serialize(VariableValueExpression& node); - void Serialize(UnaryExpression& node); - - void Serialize(BranchStatement& node); - void Serialize(ConditionalStatement& node); - void Serialize(DeclareAliasStatement& node); - void Serialize(DeclareConstStatement& node); - void Serialize(DeclareExternalStatement& node); - void Serialize(DeclareFunctionStatement& node); - void Serialize(DeclareOptionStatement& node); - void Serialize(DeclareStructStatement& node); - void Serialize(DeclareVariableStatement& node); - void Serialize(DiscardStatement& node); - void Serialize(ExpressionStatement& node); - void Serialize(ForStatement& node); - void Serialize(ForEachStatement& node); - void Serialize(ImportStatement& node); - void Serialize(MultiStatement& node); - void Serialize(NoOpStatement& node); - void Serialize(ReturnStatement& node); - void Serialize(ScopedStatement& node); - void Serialize(WhileStatement& node); - - void SerializeExpressionCommon(Expression& expr); - void SerializeNodeCommon(ShaderAst::Node& node); - - protected: - template void Container(T& container); - template void Enum(T& enumVal); - template void ExprValue(ExpressionValue& attribute); - template void OptEnum(std::optional& optVal); - inline void OptType(std::optional& optType); - template void OptVal(std::optional& optVal); - - virtual bool IsWriting() const = 0; - - virtual void Node(ExpressionPtr& node) = 0; - virtual void Node(StatementPtr& node) = 0; - - virtual void SerializeModule(ModulePtr& module) = 0; - virtual void SharedString(std::shared_ptr& val) = 0; - - inline void SourceLoc(ShaderLang::SourceLocation& sourceLoc); - - virtual void Type(ExpressionType& type) = 0; - - virtual void Value(bool& val) = 0; - virtual void Value(float& val) = 0; - virtual void Value(std::string& val) = 0; - virtual void Value(Int32& val) = 0; - virtual void Value(Vector2f& val) = 0; - virtual void Value(Vector3f& val) = 0; - virtual void Value(Vector4f& val) = 0; - virtual void Value(Vector2i32& val) = 0; - virtual void Value(Vector3i32& val) = 0; - virtual void Value(Vector4i32& val) = 0; - virtual void Value(UInt8& val) = 0; - virtual void Value(UInt16& val) = 0; - virtual void Value(UInt32& val) = 0; - virtual void Value(UInt64& val) = 0; - inline void SizeT(std::size_t& val); - }; - - class NAZARA_SHADER_API ShaderAstSerializer final : public AstSerializerBase - { - public: - inline ShaderAstSerializer(ByteStream& stream); - ~ShaderAstSerializer() = default; - - void Serialize(ModulePtr& shader); - - private: - using AstSerializerBase::Serialize; - - bool IsWriting() const override; - void Node(ExpressionPtr& node) override; - void Node(StatementPtr& node) override; - void SerializeModule(ModulePtr& module) override; - void SharedString(std::shared_ptr& val) override; - void Type(ExpressionType& type) override; - void Value(bool& val) override; - void Value(float& val) override; - void Value(std::string& val) override; - void Value(Int32& val) override; - void Value(Vector2f& val) override; - void Value(Vector3f& val) override; - void Value(Vector4f& val) override; - void Value(Vector2i32& val) override; - void Value(Vector3i32& val) override; - void Value(Vector4i32& val) override; - void Value(UInt8& val) override; - void Value(UInt16& val) override; - void Value(UInt32& val) override; - void Value(UInt64& val) override; - - std::unordered_map m_stringIndices; - ByteStream& m_stream; - }; - - class NAZARA_SHADER_API ShaderAstUnserializer final : public AstSerializerBase - { - public: - ShaderAstUnserializer(ByteStream& stream); - ~ShaderAstUnserializer() = default; - - ModulePtr Unserialize(); - - private: - using AstSerializerBase::Serialize; - - bool IsWriting() const override; - void Node(ExpressionPtr& node) override; - void Node(StatementPtr& node) override; - void SerializeModule(ModulePtr& module) override; - void SharedString(std::shared_ptr& val) override; - void Type(ExpressionType& type) override; - void Value(bool& val) override; - void Value(float& val) override; - void Value(std::string& val) override; - void Value(Int32& val) override; - void Value(Vector2f& val) override; - void Value(Vector3f& val) override; - void Value(Vector4f& val) override; - void Value(Vector2i32& val) override; - void Value(Vector3i32& val) override; - void Value(Vector4i32& val) override; - void Value(UInt8& val) override; - void Value(UInt16& val) override; - void Value(UInt32& val) override; - void Value(UInt64& val) override; - - std::vector> m_strings; - ByteStream& m_stream; - }; - - NAZARA_SHADER_API ByteArray SerializeShader(ModulePtr& shader); - inline ModulePtr UnserializeShader(const void* data, std::size_t size); - NAZARA_SHADER_API ModulePtr UnserializeShader(ByteStream& stream); -} - -#include - -#endif // NAZARA_SHADER_AST_ASTSERIALIZER_HPP diff --git a/include/Nazara/Shader/Ast/AstSerializer.inl b/include/Nazara/Shader/Ast/AstSerializer.inl deleted file mode 100644 index 655cce786..000000000 --- a/include/Nazara/Shader/Ast/AstSerializer.inl +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - template - void AstSerializerBase::Container(T& container) - { - bool isWriting = IsWriting(); - - UInt32 size; - if (isWriting) - size = SafeCast(container.size()); - - Value(size); - if (!isWriting) - container.resize(size); - } - - - template - void AstSerializerBase::Enum(T& enumVal) - { - bool isWriting = IsWriting(); - - UInt32 value; - if (isWriting) - value = SafeCast(enumVal); - - Value(value); - if (!isWriting) - enumVal = static_cast(value); - } - - template - void AstSerializerBase::ExprValue(ExpressionValue& attribute) - { - UInt32 valueType; - if (IsWriting()) - { - if (!attribute.HasValue()) - valueType = 0; - else if (attribute.IsExpression()) - valueType = 1; - else if (attribute.IsResultingValue()) - valueType = 2; - else - throw std::runtime_error("unexpected attribute"); - } - - Value(valueType); - - switch (valueType) - { - case 0: - if (!IsWriting()) - attribute = {}; - - break; - - case 1: - { - if (!IsWriting()) - { - ExpressionPtr expr; - Node(expr); - - attribute = std::move(expr); - } - else - Node(const_cast(attribute.GetExpression())); //< not used for writing - - break; - } - - case 2: - { - if (!IsWriting()) - { - T value; - if constexpr (std::is_enum_v) - Enum(value); - else if constexpr (std::is_same_v) - Type(value); - else - Value(value); - - attribute = std::move(value); - } - else - { - T& value = const_cast(attribute.GetResultingValue()); //< not used for writing - if constexpr (std::is_enum_v) - Enum(value); - else if constexpr (std::is_same_v) - Type(value); - else - Value(value); - } - - break; - } - } - } - - template - void AstSerializerBase::OptEnum(std::optional& optVal) - { - bool isWriting = IsWriting(); - - bool hasValue; - if (isWriting) - hasValue = optVal.has_value(); - - Value(hasValue); - - if (!isWriting && hasValue) - optVal.emplace(); - - if (optVal.has_value()) - Enum(optVal.value()); - } - - inline void AstSerializerBase::OptType(std::optional& optType) - { - bool isWriting = IsWriting(); - - bool hasValue; - if (isWriting) - hasValue = optType.has_value(); - - Value(hasValue); - - if (!isWriting && hasValue) - optType.emplace(); - - if (optType.has_value()) - Type(optType.value()); - } - - template - void AstSerializerBase::OptVal(std::optional& optVal) - { - bool isWriting = IsWriting(); - - bool hasValue; - if (isWriting) - hasValue = optVal.has_value(); - - Value(hasValue); - - if (!isWriting && hasValue) - optVal.emplace(); - - if (optVal.has_value()) - { - if constexpr (std::is_same_v) - SizeT(optVal.value()); - else - Value(optVal.value()); - } - } - - inline void AstSerializerBase::SourceLoc(ShaderLang::SourceLocation& sourceLoc) - { - SharedString(sourceLoc.file); - Value(sourceLoc.endColumn); - Value(sourceLoc.endLine); - Value(sourceLoc.startColumn); - Value(sourceLoc.startLine); - } - - inline void AstSerializerBase::SizeT(std::size_t& val) - { - bool isWriting = IsWriting(); - - UInt32 fixedVal; - if (isWriting) - fixedVal = SafeCast(val); - - Value(fixedVal); - - if (!isWriting) - val = SafeCast(fixedVal); - } - - inline ShaderAstSerializer::ShaderAstSerializer(ByteStream& stream) : - m_stream(stream) - { - } - - inline ShaderAstUnserializer::ShaderAstUnserializer(ByteStream& stream) : - m_stream(stream) - { - } - - inline ModulePtr UnserializeShader(const void* data, std::size_t size) - { - ByteStream byteStream(data, size); - return UnserializeShader(byteStream); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/AstStatementVisitor.hpp b/include/Nazara/Shader/Ast/AstStatementVisitor.hpp deleted file mode 100644 index 00f1173c8..000000000 --- a/include/Nazara/Shader/Ast/AstStatementVisitor.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTSTATEMENTVISITOR_HPP -#define NAZARA_SHADER_AST_ASTSTATEMENTVISITOR_HPP - -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstStatementVisitor - { - public: - AstStatementVisitor() = default; - AstStatementVisitor(const AstStatementVisitor&) = delete; - AstStatementVisitor(AstStatementVisitor&&) = delete; - virtual ~AstStatementVisitor(); - -#define NAZARA_SHADERAST_STATEMENT(NodeType) virtual void Visit(ShaderAst::NodeType& node) = 0; -#include - - AstStatementVisitor& operator=(const AstStatementVisitor&) = delete; - AstStatementVisitor& operator=(AstStatementVisitor&&) = delete; - }; -} - -#endif // NAZARA_SHADER_AST_ASTSTATEMENTVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/AstStatementVisitorExcept.hpp b/include/Nazara/Shader/Ast/AstStatementVisitorExcept.hpp deleted file mode 100644 index ab10dffe7..000000000 --- a/include/Nazara/Shader/Ast/AstStatementVisitorExcept.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTSTATEMENTVISITOREXCEPT_HPP -#define NAZARA_SHADER_AST_ASTSTATEMENTVISITOREXCEPT_HPP - -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API AstStatementVisitorExcept : public AstStatementVisitor - { - public: - using AstStatementVisitor::Visit; - -#define NAZARA_SHADERAST_STATEMENT(Node) void Visit(ShaderAst::Node& node) override; -#include - }; -} - -#endif // NAZARA_SHADER_AST_ASTSTATEMENTVISITOREXCEPT_HPP diff --git a/include/Nazara/Shader/Ast/AstTypes.hpp b/include/Nazara/Shader/Ast/AstTypes.hpp deleted file mode 100644 index c940a8d63..000000000 --- a/include/Nazara/Shader/Ast/AstTypes.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTTYPES_HPP -#define NAZARA_SHADER_AST_ASTTYPES_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - enum class TypeParameterCategory - { - ConstantValue, - FullType, - PrimitiveType, - StructType - }; - - struct PartialType; - - using TypeParameter = std::variant; - - struct PartialType - { - std::vector parameters; - std::function buildFunc; - }; - -} - -#endif // NAZARA_SHADER_AST_ASTTYPES_HPP diff --git a/include/Nazara/Shader/Ast/AstUtils.hpp b/include/Nazara/Shader/Ast/AstUtils.hpp deleted file mode 100644 index f92b192e1..000000000 --- a/include/Nazara/Shader/Ast/AstUtils.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ASTUTILS_HPP -#define NAZARA_SHADER_AST_ASTUTILS_HPP - -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API ShaderAstValueCategory final : public AstExpressionVisitor - { - public: - ShaderAstValueCategory() = default; - ShaderAstValueCategory(const ShaderAstValueCategory&) = delete; - ShaderAstValueCategory(ShaderAstValueCategory&&) = delete; - ~ShaderAstValueCategory() = default; - - ExpressionCategory GetExpressionCategory(Expression& expression); - - ShaderAstValueCategory& operator=(const ShaderAstValueCategory&) = delete; - ShaderAstValueCategory& operator=(ShaderAstValueCategory&&) = delete; - - private: - using AstExpressionVisitor::Visit; - - void Visit(AccessIdentifierExpression& node) override; - void Visit(AccessIndexExpression& node) override; - void Visit(AliasValueExpression& node) override; - void Visit(AssignExpression& node) override; - void Visit(BinaryExpression& node) override; - void Visit(CallFunctionExpression& node) override; - void Visit(CallMethodExpression& node) override; - void Visit(CastExpression& node) override; - void Visit(ConditionalExpression& node) override; - void Visit(ConstantValueExpression& node) override; - void Visit(ConstantExpression& node) override; - void Visit(FunctionExpression& node) override; - void Visit(IdentifierExpression& node) override; - void Visit(IntrinsicExpression& node) override; - void Visit(IntrinsicFunctionExpression& node) override; - void Visit(StructTypeExpression& node) override; - void Visit(SwizzleExpression& node) override; - void Visit(TypeExpression& node) override; - void Visit(VariableValueExpression& node) override; - void Visit(UnaryExpression& node) override; - - ExpressionCategory m_expressionCategory; - }; - - inline ExpressionCategory GetExpressionCategory(Expression& expression); -} - -#include - -#endif // NAZARA_SHADER_AST_ASTUTILS_HPP diff --git a/include/Nazara/Shader/Ast/AstUtils.inl b/include/Nazara/Shader/Ast/AstUtils.inl deleted file mode 100644 index 339572b82..000000000 --- a/include/Nazara/Shader/Ast/AstUtils.inl +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - ExpressionCategory GetExpressionCategory(Expression& expression) - { - ShaderAstValueCategory visitor; - return visitor.GetExpressionCategory(expression); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/ConstantValue.hpp b/include/Nazara/Shader/Ast/ConstantValue.hpp deleted file mode 100644 index cdf30b8f9..000000000 --- a/include/Nazara/Shader/Ast/ConstantValue.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_CONSTANTVALUE_HPP -#define NAZARA_SHADER_AST_CONSTANTVALUE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - using NoValue = std::monostate; - - using ConstantTypes = TypeList< - NoValue, - bool, - float, - Int32, - UInt32, - Vector2f, - Vector3f, - Vector4f, - Vector2i32, - Vector3i32, - Vector4i32, - std::string - >; - - using ConstantValue = TypeListInstantiate; - - NAZARA_SHADER_API ExpressionType GetConstantType(const ConstantValue& constant); -} - -#endif // NAZARA_SHADER_AST_CONSTANTVALUE_HPP diff --git a/include/Nazara/Shader/Ast/DependencyCheckerVisitor.hpp b/include/Nazara/Shader/Ast/DependencyCheckerVisitor.hpp deleted file mode 100644 index 72a0f3f81..000000000 --- a/include/Nazara/Shader/Ast/DependencyCheckerVisitor.hpp +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_DEPENDENCYCHECKERVISITOR_HPP -#define NAZARA_SHADER_AST_DEPENDENCYCHECKERVISITOR_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API DependencyCheckerVisitor : public AstRecursiveVisitor - { - public: - struct Config; - struct UsageSet; - - DependencyCheckerVisitor() = default; - DependencyCheckerVisitor(const DependencyCheckerVisitor&) = delete; - DependencyCheckerVisitor(DependencyCheckerVisitor&&) = delete; - ~DependencyCheckerVisitor() = default; - - inline const UsageSet& GetUsage() const; - - inline void MarkFunctionAsUsed(std::size_t funcIndex); - inline void MarkStructAsUsed(std::size_t structIndex); - - inline void Register(Statement& statement); - void Register(Statement& statement, const Config& config); - - inline void Resolve(bool allowUnknownId = false); - - DependencyCheckerVisitor& operator=(const DependencyCheckerVisitor&) = delete; - DependencyCheckerVisitor& operator=(DependencyCheckerVisitor&&) = delete; - - struct Config - { - ShaderStageTypeFlags usedShaderStages; - }; - - struct UsageSet - { - Bitset<> usedAliases; - Bitset<> usedFunctions; - Bitset<> usedStructs; - Bitset<> usedVariables; - }; - - private: - UsageSet& GetContextUsageSet(); - void RegisterType(UsageSet& usageSet, const ExpressionType& exprType); - void Resolve(const UsageSet& usageSet, bool allowUnknownId); - - using AstRecursiveVisitor::Visit; - - void Visit(AliasValueExpression& node) override; - void Visit(FunctionExpression& node) override; - void Visit(StructTypeExpression& node) override; - void Visit(VariableValueExpression& node) override; - - void Visit(DeclareAliasStatement& node) override; - void Visit(DeclareExternalStatement& node) override; - void Visit(DeclareFunctionStatement& node) override; - void Visit(DeclareStructStatement& node) override; - void Visit(DeclareVariableStatement& node) override; - - std::optional m_currentAliasDeclIndex; - std::optional m_currentFunctionIndex; - std::optional m_currentVariableDeclIndex; - std::unordered_map m_aliasUsages; - std::unordered_map m_functionUsages; - std::unordered_map m_structUsages; - std::unordered_map m_variableUsages; - Config m_config; - UsageSet m_globalUsage; - UsageSet m_resolvedUsage; - }; -} - -#include - -#endif // NAZARA_SHADER_AST_DEPENDENCYCHECKERVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/DependencyCheckerVisitor.inl b/include/Nazara/Shader/Ast/DependencyCheckerVisitor.inl deleted file mode 100644 index b420d4ea0..000000000 --- a/include/Nazara/Shader/Ast/DependencyCheckerVisitor.inl +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - inline auto DependencyCheckerVisitor::GetUsage() const -> const UsageSet& - { - return m_resolvedUsage; - } - - inline void DependencyCheckerVisitor::MarkFunctionAsUsed(std::size_t funcIndex) - { - m_globalUsage.usedFunctions.UnboundedSet(funcIndex); - } - - inline void DependencyCheckerVisitor::MarkStructAsUsed(std::size_t structIndex) - { - m_globalUsage.usedStructs.UnboundedSet(structIndex); - } - - inline void DependencyCheckerVisitor::Register(Statement& statement) - { - Config defaultConfig; - return Register(statement, defaultConfig); - } - - inline void DependencyCheckerVisitor::Resolve(bool allowUnknownId) - { - Resolve(m_globalUsage, allowUnknownId); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/EliminateUnusedPassVisitor.hpp b/include/Nazara/Shader/Ast/EliminateUnusedPassVisitor.hpp deleted file mode 100644 index 09443582d..000000000 --- a/include/Nazara/Shader/Ast/EliminateUnusedPassVisitor.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ELIMINATEUNUSEDPASSVISITOR_HPP -#define NAZARA_SHADER_AST_ELIMINATEUNUSEDPASSVISITOR_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API EliminateUnusedPassVisitor : AstCloner - { - public: - EliminateUnusedPassVisitor() = default; - EliminateUnusedPassVisitor(const EliminateUnusedPassVisitor&) = delete; - EliminateUnusedPassVisitor(EliminateUnusedPassVisitor&&) = delete; - ~EliminateUnusedPassVisitor() = default; - - ModulePtr Process(const Module& shaderModule, const DependencyCheckerVisitor::UsageSet& usageSet); - StatementPtr Process(Statement& statement, const DependencyCheckerVisitor::UsageSet& usageSet); - - EliminateUnusedPassVisitor& operator=(const EliminateUnusedPassVisitor&) = delete; - EliminateUnusedPassVisitor& operator=(EliminateUnusedPassVisitor&&) = delete; - - private: - using AstCloner::Clone; - StatementPtr Clone(DeclareAliasStatement& node) override; - StatementPtr Clone(DeclareExternalStatement& node) override; - StatementPtr Clone(DeclareFunctionStatement& node) override; - StatementPtr Clone(DeclareStructStatement& node) override; - StatementPtr Clone(DeclareVariableStatement& node) override; - - bool IsAliasUsed(std::size_t aliasIndex) const; - bool IsFunctionUsed(std::size_t funcIndex) const; - bool IsStructUsed(std::size_t structIndex) const; - bool IsVariableUsed(std::size_t varIndex) const; - - struct Context; - Context* m_context; - }; - - inline ModulePtr EliminateUnusedPass(const Module& shaderModule); - inline ModulePtr EliminateUnusedPass(const Module& shaderModule, const DependencyCheckerVisitor::Config& config); - inline ModulePtr EliminateUnusedPass(const Module& shaderModule, const DependencyCheckerVisitor::UsageSet& usageSet); - - inline StatementPtr EliminateUnusedPass(Statement& ast); - inline StatementPtr EliminateUnusedPass(Statement& ast, const DependencyCheckerVisitor::Config& config); - inline StatementPtr EliminateUnusedPass(Statement& ast, const DependencyCheckerVisitor::UsageSet& usageSet); -} - -#include - -#endif // NAZARA_SHADER_AST_ELIMINATEUNUSEDPASSVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/EliminateUnusedPassVisitor.inl b/include/Nazara/Shader/Ast/EliminateUnusedPassVisitor.inl deleted file mode 100644 index 775990e67..000000000 --- a/include/Nazara/Shader/Ast/EliminateUnusedPassVisitor.inl +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - inline ModulePtr EliminateUnusedPass(const Module& shaderModule) - { - DependencyCheckerVisitor::Config defaultConfig; - return EliminateUnusedPass(shaderModule, defaultConfig); - } - - inline ModulePtr EliminateUnusedPass(const Module& shaderModule, const DependencyCheckerVisitor::Config& config) - { - DependencyCheckerVisitor dependencyVisitor; - for (const auto& importedModule : shaderModule.importedModules) - dependencyVisitor.Register(*importedModule.module->rootNode, config); - - dependencyVisitor.Register(*shaderModule.rootNode, config); - dependencyVisitor.Resolve(); - - return EliminateUnusedPass(shaderModule, dependencyVisitor.GetUsage()); - } - - ModulePtr EliminateUnusedPass(const Module& shaderModule, const DependencyCheckerVisitor::UsageSet& usageSet) - { - EliminateUnusedPassVisitor visitor; - return visitor.Process(shaderModule, usageSet); - } - - inline StatementPtr EliminateUnusedPass(Statement& ast) - { - DependencyCheckerVisitor::Config defaultConfig; - return EliminateUnusedPass(ast, defaultConfig); - } - - inline StatementPtr EliminateUnusedPass(Statement& ast, const DependencyCheckerVisitor::Config& config) - { - DependencyCheckerVisitor dependencyVisitor; - dependencyVisitor.Register(ast, config); - dependencyVisitor.Resolve(); - - return EliminateUnusedPass(ast, dependencyVisitor.GetUsage()); - } - - StatementPtr EliminateUnusedPass(Statement& ast, const DependencyCheckerVisitor::UsageSet& usageSet) - { - EliminateUnusedPassVisitor visitor; - return visitor.Process(ast, usageSet); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/Enums.hpp b/include/Nazara/Shader/Ast/Enums.hpp deleted file mode 100644 index ff6939ae8..000000000 --- a/include/Nazara/Shader/Ast/Enums.hpp +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_ENUMS_HPP -#define NAZARA_SHADER_AST_ENUMS_HPP - -#include -#include - -namespace Nz -{ - namespace ShaderAst - { - enum class AssignType - { - Simple, //< a = b - CompoundAdd, //< a += b - CompoundDivide, //< a /= b - CompoundMultiply, //< a *= b - CompoundLogicalAnd, //< a &&= b - CompoundLogicalOr, //< a ||= b - CompoundSubtract, //< a -= b - }; - - enum class AttributeType - { - Binding, //< Binding (external var only) - has argument index - Builtin, //< Builtin (struct member only) - has argument type - Cond, //< Conditional compilation option - has argument expr - DepthWrite, //< Depth write mode (function only) - has argument type - EarlyFragmentTests, //< Entry point (function only) - has argument on/off - Entry, //< Entry point (function only) - has argument type - Export, //< Exported (external block, function and struct only) - Layout, //< Struct layout (struct only) - has argument style - Location, //< Location (struct member only) - has argument index - LangVersion, //< NZSL version - has argument version string - Set, //< Binding set (external var only) - has argument index - Unroll, //< Unroll (for/for each only) - has argument mode - Uuid, //< Uuid (module only) - has argument string - }; - - enum class BinaryType - { - Add, //< + - CompEq, //< == - CompGe, //< >= - CompGt, //< > - CompLe, //< <= - CompLt, //< < - CompNe, //< <= - Divide, //< / - Multiply, //< * - LogicalAnd, //< && - LogicalOr, //< || - Subtract, //< - - }; - - enum class BuiltinEntry - { - FragCoord = 1, // gl_FragCoord - FragDepth = 2, // gl_FragDepth - VertexPosition = 0, // gl_Position - }; - - enum class DepthWriteMode - { - Greater, - Less, - Replace, - Unchanged, - }; - - enum class ExpressionCategory - { - LValue, - RValue - }; - - enum class FunctionFlag - { - DoesDiscard, - DoesWriteFragDepth, - - Max = DoesWriteFragDepth - }; - } - - template<> - struct EnumAsFlags - { - static constexpr ShaderAst::FunctionFlag max = ShaderAst::FunctionFlag::Max; - }; - - namespace ShaderAst - { - using FunctionFlags = Flags; - - enum class IntrinsicType - { - CrossProduct = 0, - DotProduct = 1, - Exp = 7, - Length = 3, - Max = 4, - Min = 5, - Normalize = 9, - Pow = 6, - Reflect = 8, - SampleTexture = 2, - }; - - enum class LoopUnroll - { - Always, - Hint, - Never - }; - - enum class MemoryLayout - { - Std140 - }; - - enum class NodeType - { - None = -1, - -#define NAZARA_SHADERAST_NODE(Node) Node, -#define NAZARA_SHADERAST_STATEMENT_LAST(Node) Node, Max = Node -#include - }; - - enum class PrimitiveType - { - Boolean, //< bool - Float32, //< f32 - Int32, //< i32 - UInt32, //< ui32 - String //< str - }; - - enum class UnaryType - { - LogicalNot, //< !v - Minus, //< -v - Plus, //< +v - }; - } -} - -#endif // NAZARA_SHADER_AST_ENUMS_HPP diff --git a/include/Nazara/Shader/Ast/ExpressionType.hpp b/include/Nazara/Shader/Ast/ExpressionType.hpp deleted file mode 100644 index 7944e2415..000000000 --- a/include/Nazara/Shader/Ast/ExpressionType.hpp +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_EXPRESSIONTYPE_HPP -#define NAZARA_SHADER_AST_EXPRESSIONTYPE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - struct ContainedType; - - struct NAZARA_SHADER_API AliasType - { - AliasType() = default; - AliasType(const AliasType& alias); - AliasType(AliasType&&) noexcept = default; - - AliasType& operator=(const AliasType& alias); - AliasType& operator=(AliasType&&) noexcept = default; - - std::size_t aliasIndex; - std::unique_ptr targetType; - - bool operator==(const AliasType& rhs) const; - inline bool operator!=(const AliasType& rhs) const; - }; - - struct NAZARA_SHADER_API ArrayType - { - ArrayType() = default; - ArrayType(const ArrayType& array); - ArrayType(ArrayType&&) noexcept = default; - - ArrayType& operator=(const ArrayType& array); - ArrayType& operator=(ArrayType&&) noexcept = default; - - UInt32 length; - std::unique_ptr containedType; - - bool operator==(const ArrayType& rhs) const; - inline bool operator!=(const ArrayType& rhs) const; - }; - - struct FunctionType - { - std::size_t funcIndex; - - inline bool operator==(const FunctionType& rhs) const; - inline bool operator!=(const FunctionType& rhs) const; - }; - - struct IntrinsicFunctionType - { - IntrinsicType intrinsic; - - inline bool operator==(const IntrinsicFunctionType& rhs) const; - inline bool operator!=(const IntrinsicFunctionType& rhs) const; - }; - - struct MatrixType - { - std::size_t columnCount; - std::size_t rowCount; - PrimitiveType type; - - inline bool operator==(const MatrixType& rhs) const; - inline bool operator!=(const MatrixType& rhs) const; - }; - - struct NAZARA_SHADER_API MethodType - { - MethodType() = default; - MethodType(const MethodType& methodType); - MethodType(MethodType&&) noexcept = default; - - MethodType& operator=(const MethodType& methodType); - MethodType& operator=(MethodType&&) noexcept = default; - - std::unique_ptr objectType; - std::size_t methodIndex; - - bool operator==(const MethodType& rhs) const; - inline bool operator!=(const MethodType& rhs) const; - }; - - struct NoType - { - inline bool operator==(const NoType& rhs) const; - inline bool operator!=(const NoType& rhs) const; - }; - - struct SamplerType - { - ImageType dim; - PrimitiveType sampledType; - - inline bool operator==(const SamplerType& rhs) const; - inline bool operator!=(const SamplerType& rhs) const; - }; - - struct StructType - { - std::size_t structIndex; - - inline bool operator==(const StructType& rhs) const; - inline bool operator!=(const StructType& rhs) const; - }; - - struct Type - { - std::size_t typeIndex; - - inline bool operator==(const Type& rhs) const; - inline bool operator!=(const Type& rhs) const; - }; - - struct UniformType - { - StructType containedType; - - inline bool operator==(const UniformType& rhs) const; - inline bool operator!=(const UniformType& rhs) const; - }; - - struct VectorType - { - std::size_t componentCount; - PrimitiveType type; - - inline bool operator==(const VectorType& rhs) const; - inline bool operator!=(const VectorType& rhs) const; - }; - - using ExpressionType = std::variant; - - struct ContainedType - { - ExpressionType type; - }; - - struct StructDescription - { - struct StructMember - { - ExpressionValue builtin; - ExpressionValue cond; - ExpressionValue locationIndex; - ExpressionValue type; - std::string name; - ShaderLang::SourceLocation sourceLocation; - }; - - ExpressionValue layout; - std::string name; - std::vector members; - bool isConditional; - }; - - inline bool IsAliasType(const ExpressionType& type); - inline bool IsArrayType(const ExpressionType& type); - inline bool IsFunctionType(const ExpressionType& type); - inline bool IsIntrinsicFunctionType(const ExpressionType& type); - inline bool IsMatrixType(const ExpressionType& type); - inline bool IsMethodType(const ExpressionType& type); - inline bool IsNoType(const ExpressionType& type); - inline bool IsPrimitiveType(const ExpressionType& type); - inline bool IsSamplerType(const ExpressionType& type); - inline bool IsStructType(const ExpressionType& type); - inline bool IsTypeExpression(const ExpressionType& type); - inline bool IsUniformType(const ExpressionType& type); - inline bool IsVectorType(const ExpressionType& type); - - struct Stringifier - { - std::function aliasStringifier; - std::function structStringifier; - std::function typeStringifier; - }; - - std::string ToString(const AliasType& type, const Stringifier& stringifier = {}); - std::string ToString(const ArrayType& type, const Stringifier& stringifier = {}); - std::string ToString(const ExpressionType& type, const Stringifier& stringifier = {}); - std::string ToString(const FunctionType& type, const Stringifier& stringifier = {}); - std::string ToString(const IntrinsicFunctionType& type, const Stringifier& stringifier = {}); - std::string ToString(const MatrixType& type, const Stringifier& stringifier = {}); - std::string ToString(const MethodType& type, const Stringifier& stringifier = {}); - std::string ToString(NoType type, const Stringifier& stringifier = {}); - std::string ToString(PrimitiveType type, const Stringifier& stringifier = {}); - std::string ToString(const SamplerType& type, const Stringifier& stringifier = {}); - std::string ToString(const StructType& type, const Stringifier& stringifier = {}); - std::string ToString(const Type& type, const Stringifier& stringifier = {}); - std::string ToString(const UniformType& type, const Stringifier& stringifier = {}); - std::string ToString(const VectorType& type, const Stringifier& stringifier = {}); -} - -#include - -#endif // NAZARA_SHADER_AST_EXPRESSIONTYPE_HPP diff --git a/include/Nazara/Shader/Ast/ExpressionType.inl b/include/Nazara/Shader/Ast/ExpressionType.inl deleted file mode 100644 index eae3d624e..000000000 --- a/include/Nazara/Shader/Ast/ExpressionType.inl +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - inline bool AliasType::operator!=(const AliasType& rhs) const - { - return !operator==(rhs); - } - - inline bool ArrayType::operator!=(const ArrayType& rhs) const - { - return !operator==(rhs); - } - - - inline bool FunctionType::operator==(const FunctionType& rhs) const - { - return funcIndex == rhs.funcIndex; - } - - inline bool FunctionType::operator!=(const FunctionType& rhs) const - { - return !operator==(rhs); - } - - - inline bool IntrinsicFunctionType::operator==(const IntrinsicFunctionType& rhs) const - { - return intrinsic == rhs.intrinsic; - } - - inline bool IntrinsicFunctionType::operator!=(const IntrinsicFunctionType& rhs) const - { - return !operator==(rhs); - } - - - inline bool MatrixType::operator==(const MatrixType& rhs) const - { - return columnCount == rhs.columnCount && rowCount == rhs.rowCount && type == rhs.type; - } - - inline bool MatrixType::operator!=(const MatrixType& rhs) const - { - return !operator==(rhs); - } - - - inline bool MethodType::operator!=(const MethodType& rhs) const - { - return !operator==(rhs); - } - - - inline bool NoType::operator==(const NoType& /*rhs*/) const - { - return true; - } - - inline bool NoType::operator!=(const NoType& /*rhs*/) const - { - return false; - } - - - inline bool SamplerType::operator==(const SamplerType& rhs) const - { - return dim == rhs.dim && sampledType == rhs.sampledType; - } - - inline bool SamplerType::operator!=(const SamplerType& rhs) const - { - return !operator==(rhs); - } - - - inline bool StructType::operator==(const StructType& rhs) const - { - return structIndex == rhs.structIndex; - } - - inline bool StructType::operator!=(const StructType& rhs) const - { - return !operator==(rhs); - } - - - inline bool Type::operator==(const Type& rhs) const - { - return typeIndex == rhs.typeIndex; - } - - inline bool Type::operator!=(const Type& rhs) const - { - return !operator==(rhs); - } - - - inline bool UniformType::operator==(const UniformType& rhs) const - { - return containedType == rhs.containedType; - } - - inline bool UniformType::operator!=(const UniformType& rhs) const - { - return !operator==(rhs); - } - - - inline bool VectorType::operator==(const VectorType& rhs) const - { - return componentCount == rhs.componentCount && type == rhs.type; - } - - inline bool VectorType::operator!=(const VectorType& rhs) const - { - return !operator==(rhs); - } - - - inline bool IsAliasType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsArrayType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsFunctionType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsIntrinsicFunctionType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsMatrixType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsMethodType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsNoType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsPrimitiveType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - inline bool IsSamplerType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - bool IsStructType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - bool IsTypeExpression(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - bool IsUniformType(const ExpressionType& type) - { - return std::holds_alternative(type); - } - - bool IsVectorType(const ExpressionType& type) - { - return std::holds_alternative(type); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/ExpressionValue.hpp b/include/Nazara/Shader/Ast/ExpressionValue.hpp deleted file mode 100644 index 38c087dd1..000000000 --- a/include/Nazara/Shader/Ast/ExpressionValue.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_EXPRESSIONVALUE_HPP -#define NAZARA_SHADER_AST_EXPRESSIONVALUE_HPP - -#include -#include -#include - -namespace Nz::ShaderAst -{ - struct Expression; - - using ExpressionPtr = std::unique_ptr; - - template - class ExpressionValue - { - public: - ExpressionValue() = default; - ExpressionValue(T value); - ExpressionValue(ExpressionPtr expr); - ExpressionValue(const ExpressionValue&) = default; - ExpressionValue(ExpressionValue&&) noexcept = default; - ~ExpressionValue() = default; - - ExpressionPtr&& GetExpression() &&; - const ExpressionPtr& GetExpression() const &; - const T& GetResultingValue() const; - - bool IsExpression() const; - bool IsResultingValue() const; - - bool HasValue() const; - - void Reset(); - - ExpressionValue& operator=(const ExpressionValue&) = default; - ExpressionValue& operator=(ExpressionValue&&) noexcept = default; - - private: - std::variant m_value; - }; -} - -#include - -#endif // NAZARA_SHADER_AST_EXPRESSIONVALUE_HPP diff --git a/include/Nazara/Shader/Ast/ExpressionValue.inl b/include/Nazara/Shader/Ast/ExpressionValue.inl deleted file mode 100644 index 672905611..000000000 --- a/include/Nazara/Shader/Ast/ExpressionValue.inl +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - template - ExpressionValue::ExpressionValue(T value) : - m_value(std::move(value)) - { - } - - template - ExpressionValue::ExpressionValue(ExpressionPtr expr) - { - assert(expr); - m_value = std::move(expr); - } - - template - ExpressionPtr&& ExpressionValue::GetExpression() && - { - if (!IsExpression()) - throw std::runtime_error("excepted expression"); - - return std::get(std::move(m_value)); - } - - template - const ExpressionPtr& ExpressionValue::GetExpression() const & - { - if (!IsExpression()) - throw std::runtime_error("excepted expression"); - - assert(std::get(m_value)); - return std::get(m_value); - } - - template - const T& ExpressionValue::GetResultingValue() const - { - if (!IsResultingValue()) - throw std::runtime_error("excepted resulting value"); - - return std::get(m_value); - } - - template - bool ExpressionValue::IsExpression() const - { - return std::holds_alternative(m_value); - } - - template - bool ExpressionValue::IsResultingValue() const - { - return std::holds_alternative(m_value); - } - - template - bool ExpressionValue::HasValue() const - { - return !std::holds_alternative(m_value); - } - - template - void ExpressionValue::Reset() - { - m_value = {}; - } -} - -#include diff --git a/include/Nazara/Shader/Ast/IndexRemapperVisitor.hpp b/include/Nazara/Shader/Ast/IndexRemapperVisitor.hpp deleted file mode 100644 index d57d6834c..000000000 --- a/include/Nazara/Shader/Ast/IndexRemapperVisitor.hpp +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_INDEXREMAPPERVISITOR_HPP -#define NAZARA_SHADER_AST_INDEXREMAPPERVISITOR_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API IndexRemapperVisitor : public AstCloner - { - public: - struct Options; - - IndexRemapperVisitor() = default; - IndexRemapperVisitor(const IndexRemapperVisitor&) = delete; - IndexRemapperVisitor(IndexRemapperVisitor&&) = delete; - ~IndexRemapperVisitor() = default; - - StatementPtr Clone(Statement& statement, const Options& options); - - IndexRemapperVisitor& operator=(const IndexRemapperVisitor&) = delete; - IndexRemapperVisitor& operator=(IndexRemapperVisitor&&) = delete; - - struct Options - { - std::function aliasIndexGenerator; - std::function constIndexGenerator; - std::function funcIndexGenerator; - std::function structIndexGenerator; - //std::function typeIndexGenerator; - std::function varIndexGenerator; - bool forceIndexGeneration = false; - }; - - private: - StatementPtr Clone(DeclareAliasStatement& node) override; - StatementPtr Clone(DeclareConstStatement& node) override; - StatementPtr Clone(DeclareExternalStatement& node) override; - StatementPtr Clone(DeclareFunctionStatement& node) override; - StatementPtr Clone(DeclareStructStatement& node) override; - StatementPtr Clone(DeclareVariableStatement& node) override; - - ExpressionPtr Clone(AliasValueExpression& node) override; - ExpressionPtr Clone(ConstantExpression& node) override; - ExpressionPtr Clone(FunctionExpression& node) override; - ExpressionPtr Clone(StructTypeExpression& node) override; - ExpressionPtr Clone(VariableValueExpression& node) override; - - void HandleType(ExpressionValue& exprType); - ExpressionType RemapType(const ExpressionType& exprType); - - struct Context; - Context* m_context; - }; - - inline StatementPtr RemapIndices(Statement& statement, const IndexRemapperVisitor::Options& options); -} - -#include - -#endif // NAZARA_SHADER_AST_INDEXREMAPPERVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/IndexRemapperVisitor.inl b/include/Nazara/Shader/Ast/IndexRemapperVisitor.inl deleted file mode 100644 index fcc23e3a6..000000000 --- a/include/Nazara/Shader/Ast/IndexRemapperVisitor.inl +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - StatementPtr RemapIndices(Statement& statement, const IndexRemapperVisitor::Options& options) - { - IndexRemapperVisitor visitor; - return visitor.Clone(statement, options); - } -} - -#include diff --git a/include/Nazara/Shader/Ast/Module.hpp b/include/Nazara/Shader/Ast/Module.hpp deleted file mode 100644 index 2d225c5bd..000000000 --- a/include/Nazara/Shader/Ast/Module.hpp +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_MODULE_HPP -#define NAZARA_SHADER_AST_MODULE_HPP - -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class Module; - - using ModulePtr = std::shared_ptr; - - class Module - { - public: - struct ImportedModule; - struct Metadata; - - inline Module(UInt32 shaderLangVersion, std::string moduleName = std::string(), const Uuid& moduleId = Uuid::Generate()); - inline Module(std::shared_ptr metadata, std::vector importedModules = {}); - inline Module(std::shared_ptr metadata, MultiStatementPtr rootNode, std::vector importedModules = {}); - Module(const Module&) = delete; - Module(Module&&) noexcept = default; - ~Module() = default; - - Module& operator=(const Module&) = delete; - Module& operator=(Module&&) noexcept = default; - - struct ImportedModule - { - std::string identifier; - ModulePtr module; - }; - - struct Metadata - { - std::string moduleName; - UInt32 shaderLangVersion; - Uuid moduleId; - }; - - std::shared_ptr metadata; - std::vector importedModules; - MultiStatementPtr rootNode; - }; -} - -#include - -#endif // NAZARA_SHADER_AST_MODULE_HPP diff --git a/include/Nazara/Shader/Ast/Module.inl b/include/Nazara/Shader/Ast/Module.inl deleted file mode 100644 index 2f5578496..000000000 --- a/include/Nazara/Shader/Ast/Module.inl +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - inline Module::Module(UInt32 shaderLangVersion, std::string moduleName, const Uuid& uuid) - { - auto mutMetadata = std::make_shared(); - mutMetadata->moduleId = uuid; - mutMetadata->moduleName = std::move(moduleName); - mutMetadata->shaderLangVersion = shaderLangVersion; - - metadata = std::move(mutMetadata); - rootNode = ShaderBuilder::MultiStatement(); - } - - inline Module::Module(std::shared_ptr metadata, std::vector importedModules) : - Module(std::move(metadata), ShaderBuilder::MultiStatement(), std::move(importedModules)) - { - } - - inline Module::Module(std::shared_ptr Metadata, MultiStatementPtr RootNode, std::vector ImportedModules) : - metadata(std::move(Metadata)), - importedModules(std::move(ImportedModules)), - rootNode(std::move(RootNode)) - { - } -} - -#include diff --git a/include/Nazara/Shader/Ast/Nodes.hpp b/include/Nazara/Shader/Ast/Nodes.hpp deleted file mode 100644 index 115dd5501..000000000 --- a/include/Nazara/Shader/Ast/Nodes.hpp +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_NODES_HPP -#define NAZARA_SHADER_AST_NODES_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class AstExpressionVisitor; - class AstStatementVisitor; - - struct Node; - - using NodePtr = std::unique_ptr; - - struct NAZARA_SHADER_API Node - { - Node() = default; - Node(const Node&) = delete; - Node(Node&&) noexcept = default; - virtual ~Node(); - - virtual NodeType GetType() const = 0; - - Node& operator=(const Node&) = delete; - Node& operator=(Node&&) noexcept = default; - - ShaderLang::SourceLocation sourceLocation; - }; - - // Expressions - - struct Expression; - - using ExpressionPtr = std::unique_ptr; - - struct NAZARA_SHADER_API Expression : Node - { - Expression() = default; - Expression(const Expression&) = delete; - Expression(Expression&&) noexcept = default; - ~Expression() = default; - - virtual void Visit(AstExpressionVisitor& visitor) = 0; - - Expression& operator=(const Expression&) = delete; - Expression& operator=(Expression&&) noexcept = default; - - std::optional cachedExpressionType; - }; - - struct NAZARA_SHADER_API AccessIdentifierExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - struct Identifier - { - std::string identifier; - ShaderLang::SourceLocation sourceLocation; - }; - - std::vector identifiers; - ExpressionPtr expr; - }; - - struct NAZARA_SHADER_API AccessIndexExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::vector indices; - ExpressionPtr expr; - }; - - struct NAZARA_SHADER_API AliasValueExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t aliasId; - }; - - struct NAZARA_SHADER_API AssignExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - AssignType op; - ExpressionPtr left; - ExpressionPtr right; - }; - - struct NAZARA_SHADER_API BinaryExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - BinaryType op; - ExpressionPtr left; - ExpressionPtr right; - }; - - struct NAZARA_SHADER_API CallFunctionExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::vector parameters; - ExpressionPtr targetFunction; - }; - - struct NAZARA_SHADER_API CallMethodExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::string methodName; - std::vector parameters; - ExpressionPtr object; - }; - - struct NAZARA_SHADER_API CastExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::array expressions; - ExpressionValue targetType; - }; - - struct NAZARA_SHADER_API ConditionalExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - ExpressionPtr condition; - ExpressionPtr falsePath; - ExpressionPtr truePath; - }; - - struct NAZARA_SHADER_API ConstantExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t constantId; - }; - - struct NAZARA_SHADER_API ConstantValueExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - ConstantValue value; - }; - - struct NAZARA_SHADER_API FunctionExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t funcId; - }; - - struct NAZARA_SHADER_API IdentifierExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::string identifier; - }; - - struct NAZARA_SHADER_API IntrinsicExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::vector parameters; - IntrinsicType intrinsic; - }; - - struct NAZARA_SHADER_API IntrinsicFunctionExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t intrinsicId; - }; - - struct NAZARA_SHADER_API StructTypeExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t structTypeId; - }; - - struct NAZARA_SHADER_API SwizzleExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::array components; - std::size_t componentCount; - ExpressionPtr expression; - }; - - struct NAZARA_SHADER_API TypeExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t typeId; - }; - - struct NAZARA_SHADER_API VariableValueExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - std::size_t variableId; - }; - - struct NAZARA_SHADER_API UnaryExpression : Expression - { - NodeType GetType() const override; - void Visit(AstExpressionVisitor& visitor) override; - - ExpressionPtr expression; - UnaryType op; - }; - - // Statements - - struct Statement; - - using StatementPtr = std::unique_ptr; - - struct NAZARA_SHADER_API Statement : Node - { - Statement() = default; - Statement(const Statement&) = delete; - Statement(Statement&&) noexcept = default; - ~Statement() = default; - - virtual void Visit(AstStatementVisitor& visitor) = 0; - - Statement& operator=(const Statement&) = delete; - Statement& operator=(Statement&&) noexcept = default; - }; - - struct NAZARA_SHADER_API BranchStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - struct ConditionalStatement - { - ExpressionPtr condition; - StatementPtr statement; - }; - - std::vector condStatements; - StatementPtr elseStatement; - bool isConst = false; - }; - - struct NAZARA_SHADER_API ConditionalStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - ExpressionPtr condition; - StatementPtr statement; - }; - - struct NAZARA_SHADER_API DeclareAliasStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional aliasIndex; - std::string name; - ExpressionPtr expression; - }; - - struct NAZARA_SHADER_API DeclareConstStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional constIndex; - std::string name; - ExpressionPtr expression; - ExpressionValue type; - }; - - struct NAZARA_SHADER_API DeclareExternalStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - struct ExternalVar - { - std::optional varIndex; - std::string name; - ExpressionValue bindingIndex; - ExpressionValue bindingSet; - ExpressionValue type; - ShaderLang::SourceLocation sourceLocation; - }; - - std::vector externalVars; - ExpressionValue bindingSet; - }; - - struct NAZARA_SHADER_API DeclareFunctionStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - struct Parameter - { - std::optional varIndex; - std::string name; - ExpressionValue type; - ShaderLang::SourceLocation sourceLocation; - }; - - std::optional funcIndex; - std::string name; - std::vector parameters; - std::vector statements; - ExpressionValue depthWrite; - ExpressionValue entryStage; - ExpressionValue returnType; - ExpressionValue earlyFragmentTests; - ExpressionValue isExported; - }; - - struct NAZARA_SHADER_API DeclareOptionStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional optIndex; - std::string optName; - ExpressionPtr defaultValue; - ExpressionValue optType; - }; - - struct NAZARA_SHADER_API DeclareStructStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional structIndex; - ExpressionValue isExported; - StructDescription description; - }; - - struct NAZARA_SHADER_API DeclareVariableStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional varIndex; - std::string varName; - ExpressionPtr initialExpression; - ExpressionValue varType; - }; - - struct NAZARA_SHADER_API DiscardStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - }; - - struct NAZARA_SHADER_API ExpressionStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - ExpressionPtr expression; - }; - - struct NAZARA_SHADER_API ForStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional varIndex; - std::string varName; - ExpressionPtr fromExpr; - ExpressionPtr stepExpr; - ExpressionPtr toExpr; - ExpressionValue unroll; - StatementPtr statement; - }; - - struct NAZARA_SHADER_API ForEachStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::optional varIndex; - std::string varName; - ExpressionPtr expression; - ExpressionValue unroll; - StatementPtr statement; - }; - - struct NAZARA_SHADER_API ImportStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::string moduleName; - }; - - struct NAZARA_SHADER_API MultiStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - std::vector statements; - }; - - struct NAZARA_SHADER_API NoOpStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - }; - - struct NAZARA_SHADER_API ReturnStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - ExpressionPtr returnExpr; - }; - - struct NAZARA_SHADER_API ScopedStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - StatementPtr statement; - }; - - struct NAZARA_SHADER_API WhileStatement : Statement - { - NodeType GetType() const override; - void Visit(AstStatementVisitor& visitor) override; - - ExpressionPtr condition; - ExpressionValue unroll; - StatementPtr body; - }; - -#define NAZARA_SHADERAST_NODE(X) using X##Ptr = std::unique_ptr; - -#include - - inline const ExpressionType* GetExpressionType(Expression& expr); - inline ExpressionType* GetExpressionTypeMut(Expression& expr); - inline bool IsExpression(NodeType nodeType); - inline bool IsStatement(NodeType nodeType); - - inline const ExpressionType& ResolveAlias(const ExpressionType& exprType); -} - -#include - -#endif // NAZARA_SHADER_AST_NODES_HPP diff --git a/include/Nazara/Shader/Ast/Nodes.inl b/include/Nazara/Shader/Ast/Nodes.inl deleted file mode 100644 index a14ecc4f4..000000000 --- a/include/Nazara/Shader/Ast/Nodes.inl +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - inline const ExpressionType* GetExpressionType(Expression& expr) - { - return (expr.cachedExpressionType) ? &expr.cachedExpressionType.value() : nullptr; - } - - inline ExpressionType* GetExpressionTypeMut(Expression& expr) - { - return (expr.cachedExpressionType) ? &expr.cachedExpressionType.value() : nullptr; - } - - inline const ExpressionType& ResolveAlias(const ExpressionType& exprType) - { - if (IsAliasType(exprType)) - { - const AliasType& alias = std::get(exprType); - return alias.targetType->type; - } - else - return exprType; - } - - inline bool IsExpression(NodeType nodeType) - { - switch (nodeType) - { -#define NAZARA_SHADERAST_EXPRESSION(Node) case NodeType::Node: return true; -#include - - default: - return false; - } - } - - inline bool IsStatement(NodeType nodeType) - { - switch (nodeType) - { -#define NAZARA_SHADERAST_STATEMENT(Node) case NodeType::Node: return true; -#include - - default: - return false; - } - } -} - -#include diff --git a/include/Nazara/Shader/Ast/SanitizeVisitor.hpp b/include/Nazara/Shader/Ast/SanitizeVisitor.hpp deleted file mode 100644 index 2812642e8..000000000 --- a/include/Nazara/Shader/Ast/SanitizeVisitor.hpp +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_AST_SANITIZEVISITOR_HPP -#define NAZARA_SHADER_AST_SANITIZEVISITOR_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - class NAZARA_SHADER_API SanitizeVisitor final : AstCloner - { - friend class AstTypeExpressionVisitor; - - public: - struct Options; - - SanitizeVisitor() = default; - SanitizeVisitor(const SanitizeVisitor&) = delete; - SanitizeVisitor(SanitizeVisitor&&) = delete; - ~SanitizeVisitor() = default; - - inline ModulePtr Sanitize(const Module& module, std::string* error = nullptr); - ModulePtr Sanitize(const Module& module, const Options& options, std::string* error = nullptr); - - SanitizeVisitor& operator=(const SanitizeVisitor&) = delete; - SanitizeVisitor& operator=(SanitizeVisitor&&) = delete; - - struct Options - { - std::shared_ptr moduleResolver; - std::unordered_set reservedIdentifiers; - std::unordered_map optionValues; - bool allowPartialSanitization = false; - bool makeVariableNameUnique = false; - bool reduceLoopsToWhile = false; - bool removeAliases = false; - bool removeConstDeclaration = false; - bool removeCompoundAssignments = false; - bool removeMatrixCast = false; - bool removeOptionDeclaration = false; - bool removeScalarSwizzling = false; - bool splitMultipleBranches = false; - bool useIdentifierAccessesForStructs = true; - }; - - private: - enum class IdentifierCategory; - enum class ValidationResult; - struct CurrentFunctionData; - struct Environment; - struct FunctionData; - struct Identifier; - struct IdentifierData; - template struct IdentifierList; - struct NamedPartialType; - struct Scope; - - using AstCloner::CloneExpression; - ExpressionValue CloneType(const ExpressionValue& exprType) override; - - ExpressionPtr Clone(AccessIdentifierExpression& node) override; - ExpressionPtr Clone(AccessIndexExpression& node) override; - ExpressionPtr Clone(AliasValueExpression& node) override; - ExpressionPtr Clone(AssignExpression& node) override; - ExpressionPtr Clone(BinaryExpression& node) override; - ExpressionPtr Clone(CallFunctionExpression& node) override; - ExpressionPtr Clone(CastExpression& node) override; - ExpressionPtr Clone(ConditionalExpression& node) override; - ExpressionPtr Clone(ConstantValueExpression& node) override; - ExpressionPtr Clone(ConstantExpression& node) override; - ExpressionPtr Clone(IdentifierExpression& node) override; - ExpressionPtr Clone(IntrinsicExpression& node) override; - ExpressionPtr Clone(SwizzleExpression& node) override; - ExpressionPtr Clone(UnaryExpression& node) override; - ExpressionPtr Clone(VariableValueExpression& node) override; - - StatementPtr Clone(BranchStatement& node) override; - StatementPtr Clone(ConditionalStatement& node) override; - StatementPtr Clone(DeclareAliasStatement& node) override; - StatementPtr Clone(DeclareConstStatement& node) override; - StatementPtr Clone(DeclareExternalStatement& node) override; - StatementPtr Clone(DeclareFunctionStatement& node) override; - StatementPtr Clone(DeclareOptionStatement& node) override; - StatementPtr Clone(DeclareStructStatement& node) override; - StatementPtr Clone(DeclareVariableStatement& node) override; - StatementPtr Clone(DiscardStatement& node) override; - StatementPtr Clone(ExpressionStatement& node) override; - StatementPtr Clone(ForStatement& node) override; - StatementPtr Clone(ForEachStatement& node) override; - StatementPtr Clone(ImportStatement& node) override; - StatementPtr Clone(MultiStatement& node) override; - StatementPtr Clone(ScopedStatement& node) override; - StatementPtr Clone(WhileStatement& node) override; - - const IdentifierData* FindIdentifier(const std::string_view& identifierName) const; - template const IdentifierData* FindIdentifier(const std::string_view& identifierName, F&& functor) const; - const IdentifierData* FindIdentifier(const Environment& environment, const std::string_view& identifierName) const; - template const IdentifierData* FindIdentifier(const Environment& environment, const std::string_view& identifierName, F&& functor) const; - - const ExpressionType* GetExpressionType(Expression& expr) const; - const ExpressionType& GetExpressionTypeSecure(Expression& expr) const; - - ExpressionPtr HandleIdentifier(const IdentifierData* identifierData, const ShaderLang::SourceLocation& sourceLocation); - - void PushScope(); - void PopScope(); - - ExpressionPtr CacheResult(ExpressionPtr expression); - - std::optional ComputeConstantValue(Expression& expr) const; - template ValidationResult ComputeExprValue(ExpressionValue& attribute, const ShaderLang::SourceLocation& sourceLocation) const; - template ValidationResult ComputeExprValue(const ExpressionValue& attribute, ExpressionValue& targetAttribute, const ShaderLang::SourceLocation& sourceLocation); - template std::unique_ptr PropagateConstants(T& node) const; - - void PreregisterIndices(const Module& module); - void PropagateFunctionFlags(std::size_t funcIndex, FunctionFlags flags, Bitset<>& seen); - - void RegisterBuiltin(); - - std::size_t RegisterAlias(std::string name, std::optional aliasData, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - std::size_t RegisterConstant(std::string name, std::optional value, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - std::size_t RegisterFunction(std::string name, std::optional funcData, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - std::size_t RegisterIntrinsic(std::string name, IntrinsicType type); - std::size_t RegisterModule(std::string moduleIdentifier, std::size_t moduleIndex); - std::size_t RegisterStruct(std::string name, std::optional description, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - std::size_t RegisterType(std::string name, std::optional expressionType, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - std::size_t RegisterType(std::string name, std::optional partialType, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - void RegisterUnresolved(std::string name); - std::size_t RegisterVariable(std::string name, std::optional type, std::optional index, const ShaderLang::SourceLocation& sourceLocation); - - const Identifier* ResolveAliasIdentifier(const Identifier* identifier, const ShaderLang::SourceLocation& sourceLocation) const; - void ResolveFunctions(); - std::size_t ResolveStruct(const AliasType& aliasType, const ShaderLang::SourceLocation& sourceLocation); - std::size_t ResolveStruct(const ExpressionType& exprType, const ShaderLang::SourceLocation& sourceLocation); - std::size_t ResolveStruct(const StructType& structType, const ShaderLang::SourceLocation& sourceLocation); - std::size_t ResolveStruct(const UniformType& uniformType, const ShaderLang::SourceLocation& sourceLocation); - ExpressionType ResolveType(const ExpressionType& exprType, bool resolveAlias, const ShaderLang::SourceLocation& sourceLocation); - std::optional ResolveTypeExpr(const ExpressionValue& exprTypeValue, bool resolveAlias, const ShaderLang::SourceLocation& sourceLocation); - - void SanitizeIdentifier(std::string& identifier); - MultiStatementPtr SanitizeInternal(MultiStatement& rootNode, std::string* error); - - std::string ToString(const ExpressionType& exprType, const ShaderLang::SourceLocation& sourceLocation) const; - std::string ToString(const NamedPartialType& partialType, const ShaderLang::SourceLocation& sourceLocation) const; - template std::string ToString(const std::variant& value, const ShaderLang::SourceLocation& sourceLocation) const; - - void TypeMustMatch(const ExpressionType& left, const ExpressionType& right, const ShaderLang::SourceLocation& sourceLocation) const; - ValidationResult TypeMustMatch(const ExpressionPtr& left, const ExpressionPtr& right, const ShaderLang::SourceLocation& sourceLocation); - - ValidationResult Validate(DeclareAliasStatement& node); - ValidationResult Validate(WhileStatement& node); - - ValidationResult Validate(AccessIndexExpression& node); - ValidationResult Validate(AssignExpression& node); - ValidationResult Validate(BinaryExpression& node); - ValidationResult Validate(CallFunctionExpression& node); - ValidationResult Validate(CastExpression& node); - ValidationResult Validate(DeclareVariableStatement& node); - ValidationResult Validate(IntrinsicExpression& node); - ValidationResult Validate(SwizzleExpression& node); - ValidationResult Validate(UnaryExpression& node); - ValidationResult Validate(VariableValueExpression& node); - ExpressionType ValidateBinaryOp(BinaryType op, const ExpressionType& leftExprType, const ExpressionType& rightExprType, const ShaderLang::SourceLocation& sourceLocation); - - template ValidationResult ValidateIntrinsicParamCount(IntrinsicExpression& node); - ValidationResult ValidateIntrinsicParamMatchingType(IntrinsicExpression& node); - template ValidationResult ValidateIntrinsicParameter(IntrinsicExpression& node, F&& func); - template ValidationResult ValidateIntrinsicParameterType(IntrinsicExpression& node, F&& func, const char* typeStr); - - static Expression& MandatoryExpr(const ExpressionPtr& node, const ShaderLang::SourceLocation& sourceLocation); - static Statement& MandatoryStatement(const StatementPtr& node, const ShaderLang::SourceLocation& sourceLocation); - - static StatementPtr Unscope(StatementPtr node); - - static UInt32 ToSwizzleIndex(char c, const ShaderLang::SourceLocation& sourceLocation); - - enum class IdentifierCategory - { - Alias, - Constant, - Function, - Intrinsic, - Module, - Struct, - Type, - Unresolved, - Variable - }; - - enum class ValidationResult - { - Validated, - Unresolved - }; - - struct FunctionData - { - Bitset<> calledByFunctions; - DeclareFunctionStatement* node; - FunctionFlags flags; - }; - - struct IdentifierData - { - std::size_t index; - IdentifierCategory category; - bool isConditional = false; - }; - - struct Identifier - { - std::string name; - IdentifierData target; - }; - - struct Context; - Context* m_context; - }; - - inline ModulePtr Sanitize(const Module& module, std::string* error = nullptr); - inline ModulePtr Sanitize(const Module& module, const SanitizeVisitor::Options& options, std::string* error = nullptr); -} - -#include - -#endif // NAZARA_SHADER_AST_SANITIZEVISITOR_HPP diff --git a/include/Nazara/Shader/Ast/SanitizeVisitor.inl b/include/Nazara/Shader/Ast/SanitizeVisitor.inl deleted file mode 100644 index 10dbf7eb6..000000000 --- a/include/Nazara/Shader/Ast/SanitizeVisitor.inl +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - inline ModulePtr SanitizeVisitor::Sanitize(const Module& module, std::string* error) - { - return Sanitize(module, {}, error); - } - - inline ModulePtr Sanitize(const Module& module, std::string* error) - { - SanitizeVisitor sanitizer; - return sanitizer.Sanitize(module, error); - } - - inline ModulePtr Sanitize(const Module& module, const SanitizeVisitor::Options& options, std::string* error) - { - SanitizeVisitor sanitizer; - return sanitizer.Sanitize(module, options, error); - } -} - -#include diff --git a/include/Nazara/Shader/Config.hpp b/include/Nazara/Shader/Config.hpp deleted file mode 100644 index ead635831..000000000 --- a/include/Nazara/Shader/Config.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - Nazara Engine - Shader module - - Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) - - 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. -*/ - -#pragma once - -#ifndef NAZARA_SHADER_CONFIG_HPP -#define NAZARA_SHADER_CONFIG_HPP - -/// Each modification of a parameter needs a recompilation of the module - -// Use the MemoryManager to manage dynamic allocations (can detect memory leak but allocations/frees are slower) -#define NAZARA_SHADER_MANAGE_MEMORY 0 - -// Activate the security tests based on the code (Advised for development) -#define NAZARA_SHADER_SAFE 1 - -/// Each modification of a parameter following implies a modification (often minor) of the code - -/// Checking the values and types of certain constants -#include - -#if !defined(NAZARA_STATIC) - #ifdef NAZARA_SHADER_BUILD - #define NAZARA_SHADER_API NAZARA_EXPORT - #else - #define NAZARA_SHADER_API NAZARA_IMPORT - #endif -#else - #define NAZARA_SHADER_API -#endif - -#endif // NAZARA_SHADER_CONFIG_HPP diff --git a/include/Nazara/Shader/ConfigCheck.hpp b/include/Nazara/Shader/ConfigCheck.hpp deleted file mode 100644 index a79337f89..000000000 --- a/include/Nazara/Shader/ConfigCheck.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_CONFIGCHECK_HPP -#define NAZARA_SHADER_CONFIGCHECK_HPP - -/// This file is used to check the constant values defined in Config.hpp - -#include -#define CheckType(name, type, err) static_assert(std::is_ ##type ::value, #type err) -#define CheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type ::value && name op val, #type err) - -// We force the value of MANAGE_MEMORY in debug -#if defined(NAZARA_DEBUG) && !NAZARA_SHADER_MANAGE_MEMORY - #undef NAZARA_SHADER_MANAGE_MEMORY - #define NAZARA_SHADER_MANAGE_MEMORY 0 -#endif - -#endif // NAZARA_SHADER_CONFIGCHECK_HPP diff --git a/include/Nazara/Shader/Debug.hpp b/include/Nazara/Shader/Debug.hpp deleted file mode 100644 index 9fafbb360..000000000 --- a/include/Nazara/Shader/Debug.hpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// no header guards - -#include -#if NAZARA_SHADER_MANAGE_MEMORY - #include -#endif diff --git a/include/Nazara/Shader/DebugOff.hpp b/include/Nazara/Shader/DebugOff.hpp deleted file mode 100644 index 333f56c17..000000000 --- a/include/Nazara/Shader/DebugOff.hpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// no header guards - -// We suppose that Debug.hpp is already included, same goes for Config.hpp -#if NAZARA_SHADER_MANAGE_MEMORY - #undef delete - #undef new -#endif diff --git a/include/Nazara/Shader/Enums.hpp b/include/Nazara/Shader/Enums.hpp deleted file mode 100644 index b08565eb8..000000000 --- a/include/Nazara/Shader/Enums.hpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_ENUMS_HPP -#define NAZARA_SHADER_ENUMS_HPP - -#include - -namespace Nz -{ - enum class ShaderStageType - { - Fragment, - Vertex, - - Max = Vertex - }; - - constexpr std::size_t ShaderStageTypeCount = static_cast(ShaderStageType::Max) + 1; - - template<> - struct EnumAsFlags - { - static constexpr ShaderStageType max = ShaderStageType::Max; - }; - - using ShaderStageTypeFlags = Flags; - - constexpr ShaderStageTypeFlags ShaderStageType_All = ShaderStageType::Fragment | ShaderStageType::Vertex; - - enum class StructFieldType - { - Bool1, - Bool2, - Bool3, - Bool4, - Float1, - Float2, - Float3, - Float4, - Double1, - Double2, - Double3, - Double4, - Int1, - Int2, - Int3, - Int4, - UInt1, - UInt2, - UInt3, - UInt4, - - Max = UInt4 - }; - - enum class StructLayout - { - Packed, - Std140, - - Max = Std140 - }; - -} - -#endif // NAZARA_SHADER_ENUMS_HPP diff --git a/include/Nazara/Shader/FieldOffsets.hpp b/include/Nazara/Shader/FieldOffsets.hpp deleted file mode 100644 index 7008ebf23..000000000 --- a/include/Nazara/Shader/FieldOffsets.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_FIELDOFFSETS_HPP -#define NAZARA_SHADER_FIELDOFFSETS_HPP - -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API FieldOffsets - { - public: - inline FieldOffsets(StructLayout layout); - FieldOffsets(const FieldOffsets&) = default; - FieldOffsets(FieldOffsets&&) = default; - ~FieldOffsets() = default; - - std::size_t AddField(StructFieldType type); - std::size_t AddFieldArray(StructFieldType type, std::size_t arraySize); - std::size_t AddMatrix(StructFieldType cellType, unsigned int columns, unsigned int rows, bool columnMajor); - std::size_t AddMatrixArray(StructFieldType cellType, unsigned int columns, unsigned int rows, bool columnMajor, std::size_t arraySize); - std::size_t AddStruct(const FieldOffsets& fieldStruct); - std::size_t AddStructArray(const FieldOffsets& fieldStruct, std::size_t arraySize); - - inline std::size_t GetAlignedSize() const; - inline std::size_t GetLargestFieldAlignement() const; - inline StructLayout GetLayout() const; - inline std::size_t GetSize() const; - - FieldOffsets& operator=(const FieldOffsets&) = default; - FieldOffsets& operator=(FieldOffsets&&) = default; - - static std::size_t GetAlignement(StructLayout layout, StructFieldType fieldType); - static std::size_t GetCount(StructFieldType fieldType); - static std::size_t GetSize(StructFieldType fieldType); - - private: - std::size_t m_largestFieldAlignment; - std::size_t m_offsetRounding; - std::size_t m_size; - StructLayout m_layout; - }; -} - -#include - -#endif // NAZARA_SHADER_FIELDOFFSETS_HPP diff --git a/include/Nazara/Shader/FieldOffsets.inl b/include/Nazara/Shader/FieldOffsets.inl deleted file mode 100644 index 248b289fa..000000000 --- a/include/Nazara/Shader/FieldOffsets.inl +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz -{ - inline FieldOffsets::FieldOffsets(StructLayout layout) : - m_largestFieldAlignment(1), - m_offsetRounding(1), - m_size(0), - m_layout(layout) - { - } - - inline std::size_t FieldOffsets::GetLargestFieldAlignement() const - { - return m_largestFieldAlignment; - } - - inline StructLayout FieldOffsets::GetLayout() const - { - return m_layout; - } - - inline std::size_t FieldOffsets::GetAlignedSize() const - { - if (m_layout == StructLayout::Std140) - return Align(m_size, m_largestFieldAlignment); - else - return m_size; - } - - inline std::size_t FieldOffsets::GetSize() const - { - return m_size; - } - - inline std::size_t FieldOffsets::GetAlignement(StructLayout layout, StructFieldType fieldType) - { - switch (layout) - { - case StructLayout::Packed: - return 1; - - case StructLayout::Std140: - { - switch (fieldType) - { - case StructFieldType::Bool1: - case StructFieldType::Float1: - case StructFieldType::Int1: - case StructFieldType::UInt1: - return 4; - - case StructFieldType::Bool2: - case StructFieldType::Float2: - case StructFieldType::Int2: - case StructFieldType::UInt2: - return 2 * 4; - - case StructFieldType::Bool3: - case StructFieldType::Float3: - case StructFieldType::Int3: - case StructFieldType::UInt3: - case StructFieldType::Bool4: - case StructFieldType::Float4: - case StructFieldType::Int4: - case StructFieldType::UInt4: - return 4 * 4; - - case StructFieldType::Double1: - return 8; - - case StructFieldType::Double2: - return 2 * 8; - - case StructFieldType::Double3: - case StructFieldType::Double4: - return 4 * 8; - } - } - } - - return 0; - } - - inline std::size_t FieldOffsets::GetCount(StructFieldType fieldType) - { - switch (fieldType) - { - case StructFieldType::Bool1: - case StructFieldType::Double1: - case StructFieldType::Float1: - case StructFieldType::Int1: - case StructFieldType::UInt1: - return 1; - - case StructFieldType::Bool2: - case StructFieldType::Double2: - case StructFieldType::Float2: - case StructFieldType::Int2: - case StructFieldType::UInt2: - return 2; - - case StructFieldType::Bool3: - case StructFieldType::Double3: - case StructFieldType::Float3: - case StructFieldType::Int3: - case StructFieldType::UInt3: - return 3; - - case StructFieldType::Bool4: - case StructFieldType::Double4: - case StructFieldType::Float4: - case StructFieldType::Int4: - case StructFieldType::UInt4: - return 4; - } - - return 0; - } - - inline std::size_t FieldOffsets::GetSize(StructFieldType fieldType) - { - switch (fieldType) - { - case StructFieldType::Bool1: - case StructFieldType::Float1: - case StructFieldType::Int1: - case StructFieldType::UInt1: - return 4; - - case StructFieldType::Bool2: - case StructFieldType::Float2: - case StructFieldType::Int2: - case StructFieldType::UInt2: - return 2 * 4; - - case StructFieldType::Bool3: - case StructFieldType::Float3: - case StructFieldType::Int3: - case StructFieldType::UInt3: - return 3 * 4; - - case StructFieldType::Bool4: - case StructFieldType::Float4: - case StructFieldType::Int4: - case StructFieldType::UInt4: - return 4 * 4; - - case StructFieldType::Double1: - return 8; - - case StructFieldType::Double2: - return 2 * 8; - - case StructFieldType::Double3: - return 3 * 8; - - case StructFieldType::Double4: - return 4 * 8; - } - - return 0; - } -} - -#include diff --git a/include/Nazara/Shader/FilesystemModuleResolver.hpp b/include/Nazara/Shader/FilesystemModuleResolver.hpp deleted file mode 100644 index b5bd7dff4..000000000 --- a/include/Nazara/Shader/FilesystemModuleResolver.hpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_FILESYSTEMMODULERESOLVER_HPP -#define NAZARA_SHADER_FILESYSTEMMODULERESOLVER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API FilesystemModuleResolver : public ShaderModuleResolver - { - public: - FilesystemModuleResolver(); - FilesystemModuleResolver(const FilesystemModuleResolver&) = delete; - FilesystemModuleResolver(FilesystemModuleResolver&&) noexcept = delete; - ~FilesystemModuleResolver(); - - void RegisterModule(const std::filesystem::path& realPath); - void RegisterModule(std::string_view moduleSource); - void RegisterModule(ShaderAst::ModulePtr module); - void RegisterModuleDirectory(const std::filesystem::path& realPath, bool watchDirectory = true); - - ShaderAst::ModulePtr Resolve(const std::string& moduleName) override; - - FilesystemModuleResolver& operator=(const FilesystemModuleResolver&) = delete; - FilesystemModuleResolver& operator=(FilesystemModuleResolver&&) noexcept = delete; - - static constexpr const char* CompiledModuleExtension = ".nzslb"; - static constexpr const char* ModuleExtension = ".nzsl"; - - private: - void OnFileAdded(std::string_view directory, std::string_view filename); - void OnFileRemoved(std::string_view directory, std::string_view filename); - void OnFileMoved(std::string_view directory, std::string_view filename, std::string_view oldFilename); - void OnFileUpdated(std::string_view directory, std::string_view filename); - - static bool CheckExtension(std::string_view filename); - - std::unordered_map m_moduleByFilepath; - std::unordered_map m_modules; - MovablePtr m_fileWatcher; - }; -} - -#include - -#endif // NAZARA_SHADER_FILESYSTEMMODULERESOLVER_HPP diff --git a/include/Nazara/Shader/FilesystemModuleResolver.inl b/include/Nazara/Shader/FilesystemModuleResolver.inl deleted file mode 100644 index 8ba355c2f..000000000 --- a/include/Nazara/Shader/FilesystemModuleResolver.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Shader/GlslWriter.hpp b/include/Nazara/Shader/GlslWriter.hpp deleted file mode 100644 index a608f33b9..000000000 --- a/include/Nazara/Shader/GlslWriter.hpp +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_GLSLWRITER_HPP -#define NAZARA_SHADER_GLSLWRITER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API GlslWriter : public ShaderWriter, public ShaderAst::AstExpressionVisitorExcept, public ShaderAst::AstStatementVisitorExcept - { - public: - using BindingMapping = std::unordered_map; - struct Environment; - using ExtSupportCallback = std::function; - - inline GlslWriter(); - GlslWriter(const GlslWriter&) = delete; - GlslWriter(GlslWriter&&) = delete; - ~GlslWriter() = default; - - inline std::string Generate(const ShaderAst::Module& module, const BindingMapping& bindingMapping = {}, const States& states = {}); - std::string Generate(std::optional shaderStage, const ShaderAst::Module& module, const BindingMapping& bindingMapping = {}, const States& states = {}); - - void SetEnv(Environment environment); - - struct Environment - { - ExtSupportCallback extCallback; - unsigned int glMajorVersion = 3; - unsigned int glMinorVersion = 0; - bool glES = true; - bool flipYPosition = false; - bool remapZPosition = false; - }; - - static const char* GetFlipYUniformName(); - static ShaderAst::SanitizeVisitor::Options GetSanitizeOptions(); - - private: - void Append(const ShaderAst::AliasType& aliasType); - void Append(const ShaderAst::ArrayType& type); - void Append(ShaderAst::BuiltinEntry builtin); - void Append(const ShaderAst::ExpressionType& type); - void Append(const ShaderAst::ExpressionValue& type); - void Append(const ShaderAst::FunctionType& functionType); - void Append(const ShaderAst::IntrinsicFunctionType& intrinsicFunctionType); - void Append(const ShaderAst::MatrixType& matrixType); - void Append(const ShaderAst::MethodType& methodType); - void Append(ShaderAst::MemoryLayout layout); - void Append(ShaderAst::NoType); - void Append(ShaderAst::PrimitiveType type); - void Append(const ShaderAst::SamplerType& samplerType); - void Append(const ShaderAst::StructType& structType); - void Append(const ShaderAst::Type& type); - void Append(const ShaderAst::UniformType& uniformType); - void Append(const ShaderAst::VectorType& vecType); - template void Append(const T& param); - template void Append(const T1& firstParam, const T2& secondParam, Args&&... params); - void AppendComment(const std::string& section); - void AppendCommentSection(const std::string& section); - void AppendFunctionDeclaration(const ShaderAst::DeclareFunctionStatement& node, const std::string& nameOverride, bool forward = false); - void AppendHeader(); - void AppendLine(const std::string& txt = {}); - template void AppendLine(Args&&... params); - void AppendStatementList(std::vector& statements); - void AppendVariableDeclaration(const ShaderAst::ExpressionType& varType, const std::string& varName); - - void EnterScope(); - void LeaveScope(bool skipLine = true); - - void HandleEntryPoint(ShaderAst::DeclareFunctionStatement& node); - void HandleInOut(); - - void RegisterStruct(std::size_t structIndex, ShaderAst::StructDescription* desc, std::string structName); - void RegisterVariable(std::size_t varIndex, std::string varName); - - void ScopeVisit(ShaderAst::Statement& node); - - void Visit(ShaderAst::ExpressionPtr& expr, bool encloseIfRequired = false); - - void Visit(ShaderAst::AccessIdentifierExpression& node) override; - void Visit(ShaderAst::AccessIndexExpression& node) override; - void Visit(ShaderAst::AliasValueExpression& node) override; - void Visit(ShaderAst::AssignExpression& node) override; - void Visit(ShaderAst::BinaryExpression& node) override; - void Visit(ShaderAst::CallFunctionExpression& node) override; - void Visit(ShaderAst::CastExpression& node) override; - void Visit(ShaderAst::ConstantValueExpression& node) override; - void Visit(ShaderAst::FunctionExpression& node) override; - void Visit(ShaderAst::IntrinsicExpression& node) override; - void Visit(ShaderAst::SwizzleExpression& node) override; - void Visit(ShaderAst::VariableValueExpression& node) override; - void Visit(ShaderAst::UnaryExpression& node) override; - - void Visit(ShaderAst::BranchStatement& node) override; - void Visit(ShaderAst::DeclareAliasStatement& node) override; - void Visit(ShaderAst::DeclareConstStatement& node) override; - void Visit(ShaderAst::DeclareExternalStatement& node) override; - void Visit(ShaderAst::DeclareFunctionStatement& node) override; - void Visit(ShaderAst::DeclareOptionStatement& node) override; - void Visit(ShaderAst::DeclareStructStatement& node) override; - void Visit(ShaderAst::DeclareVariableStatement& node) override; - void Visit(ShaderAst::DiscardStatement& node) override; - void Visit(ShaderAst::ExpressionStatement& node) override; - void Visit(ShaderAst::ImportStatement& node) override; - void Visit(ShaderAst::MultiStatement& node) override; - void Visit(ShaderAst::NoOpStatement& node) override; - void Visit(ShaderAst::ReturnStatement& node) override; - void Visit(ShaderAst::ScopedStatement& node) override; - void Visit(ShaderAst::WhileStatement& node) override; - - static bool HasExplicitBinding(ShaderAst::StatementPtr& shader); - static bool HasExplicitLocation(ShaderAst::StatementPtr& shader); - - struct State; - - Environment m_environment; - State* m_currentState; - }; -} - -#include - -#endif // NAZARA_SHADER_GLSLWRITER_HPP diff --git a/include/Nazara/Shader/GlslWriter.inl b/include/Nazara/Shader/GlslWriter.inl deleted file mode 100644 index a50323c0e..000000000 --- a/include/Nazara/Shader/GlslWriter.inl +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline GlslWriter::GlslWriter() : - m_currentState(nullptr) - { - } - - inline std::string GlslWriter::Generate(const ShaderAst::Module& shader, const BindingMapping& bindingMapping, const States& states) - { - return Generate(std::nullopt, shader, bindingMapping, states); - } -} - -#include diff --git a/include/Nazara/Shader/LangWriter.hpp b/include/Nazara/Shader/LangWriter.hpp deleted file mode 100644 index fdb44bca3..000000000 --- a/include/Nazara/Shader/LangWriter.hpp +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_LANGWRITER_HPP -#define NAZARA_SHADER_LANGWRITER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API LangWriter : public ShaderWriter, public ShaderAst::AstExpressionVisitorExcept, public ShaderAst::AstStatementVisitorExcept - { - public: - struct Environment; - - inline LangWriter(); - LangWriter(const LangWriter&) = delete; - LangWriter(LangWriter&&) = delete; - ~LangWriter() = default; - - std::string Generate(const ShaderAst::Module& module, const States& conditions = {}); - - void SetEnv(Environment environment); - - struct Environment - { - }; - - private: - struct BindingAttribute; - struct BuiltinAttribute; - struct DepthWriteAttribute; - struct EarlyFragmentTestsAttribute; - struct EntryAttribute; - struct LangVersionAttribute; - struct LayoutAttribute; - struct LocationAttribute; - struct SetAttribute; - struct UnrollAttribute; - struct UuidAttribute; - - void Append(const ShaderAst::AliasType& type); - void Append(const ShaderAst::ArrayType& type); - void Append(const ShaderAst::ExpressionType& type); - void Append(const ShaderAst::ExpressionValue& type); - void Append(const ShaderAst::FunctionType& functionType); - void Append(const ShaderAst::IntrinsicFunctionType& intrinsicFunctionType); - void Append(const ShaderAst::MatrixType& matrixType); - void Append(const ShaderAst::MethodType& methodType); - void Append(ShaderAst::NoType); - void Append(ShaderAst::PrimitiveType type); - void Append(const ShaderAst::SamplerType& samplerType); - void Append(const ShaderAst::StructType& structType); - void Append(const ShaderAst::Type& type); - void Append(const ShaderAst::UniformType& uniformType); - void Append(const ShaderAst::VectorType& vecType); - template void Append(const T& param); - template void Append(const T1& firstParam, const T2& secondParam, Args&&... params); - template void AppendAttributes(bool appendLine, Args&&... params); - template void AppendAttributesInternal(bool& first, const T& param); - template void AppendAttributesInternal(bool& first, const T1& firstParam, const T2& secondParam, Rest&&... params); - void AppendAttribute(BindingAttribute attribute); - void AppendAttribute(BuiltinAttribute attribute); - void AppendAttribute(DepthWriteAttribute attribute); - void AppendAttribute(EarlyFragmentTestsAttribute attribute); - void AppendAttribute(EntryAttribute attribute); - void AppendAttribute(LangVersionAttribute attribute); - void AppendAttribute(LayoutAttribute attribute); - void AppendAttribute(LocationAttribute attribute); - void AppendAttribute(SetAttribute seattributet); - void AppendAttribute(UnrollAttribute attribute); - void AppendAttribute(UuidAttribute attribute); - void AppendComment(const std::string& section); - void AppendCommentSection(const std::string& section); - void AppendHeader(); - template void AppendIdentifier(const T& map, std::size_t id); - void AppendLine(const std::string& txt = {}); - template void AppendLine(Args&&... params); - void AppendStatementList(std::vector& statements); - - void EnterScope(); - void LeaveScope(bool skipLine = true); - - void RegisterAlias(std::size_t aliasIndex, std::string aliasName); - void RegisterConstant(std::size_t constantIndex, std::string constantName); - void RegisterFunction(std::size_t funcIndex, std::string functionName); - void RegisterStruct(std::size_t structIndex, std::string structName); - void RegisterVariable(std::size_t varIndex, std::string varName); - - void ScopeVisit(ShaderAst::Statement& node); - - void Visit(ShaderAst::ExpressionPtr& expr, bool encloseIfRequired = false); - - void Visit(ShaderAst::AccessIdentifierExpression& node) override; - void Visit(ShaderAst::AccessIndexExpression& node) override; - void Visit(ShaderAst::AliasValueExpression& node) override; - void Visit(ShaderAst::AssignExpression& node) override; - void Visit(ShaderAst::BinaryExpression& node) override; - void Visit(ShaderAst::CallFunctionExpression& node) override; - void Visit(ShaderAst::CastExpression& node) override; - void Visit(ShaderAst::ConditionalExpression& node) override; - void Visit(ShaderAst::ConstantValueExpression& node) override; - void Visit(ShaderAst::ConstantExpression& node) override; - void Visit(ShaderAst::FunctionExpression& node) override; - void Visit(ShaderAst::IdentifierExpression& node) override; - void Visit(ShaderAst::IntrinsicExpression& node) override; - void Visit(ShaderAst::StructTypeExpression& node) override; - void Visit(ShaderAst::SwizzleExpression& node) override; - void Visit(ShaderAst::VariableValueExpression& node) override; - void Visit(ShaderAst::UnaryExpression& node) override; - - void Visit(ShaderAst::BranchStatement& node) override; - void Visit(ShaderAst::ConditionalStatement& node) override; - void Visit(ShaderAst::DeclareAliasStatement& node) override; - void Visit(ShaderAst::DeclareConstStatement& node) override; - void Visit(ShaderAst::DeclareExternalStatement& node) override; - void Visit(ShaderAst::DeclareFunctionStatement& node) override; - void Visit(ShaderAst::DeclareOptionStatement& node) override; - void Visit(ShaderAst::DeclareStructStatement& node) override; - void Visit(ShaderAst::DeclareVariableStatement& node) override; - void Visit(ShaderAst::DiscardStatement& node) override; - void Visit(ShaderAst::ExpressionStatement& node) override; - void Visit(ShaderAst::ForStatement& node) override; - void Visit(ShaderAst::ForEachStatement& node) override; - void Visit(ShaderAst::ImportStatement& node) override; - void Visit(ShaderAst::MultiStatement& node) override; - void Visit(ShaderAst::NoOpStatement& node) override; - void Visit(ShaderAst::ReturnStatement& node) override; - void Visit(ShaderAst::ScopedStatement& node) override; - void Visit(ShaderAst::WhileStatement& node) override; - - struct State; - - Environment m_environment; - State* m_currentState; - }; -} - -#include - -#endif // NAZARA_SHADER_LANGWRITER_HPP diff --git a/include/Nazara/Shader/LangWriter.inl b/include/Nazara/Shader/LangWriter.inl deleted file mode 100644 index 22b376c74..000000000 --- a/include/Nazara/Shader/LangWriter.inl +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline LangWriter::LangWriter() : - m_currentState(nullptr) - { - } -} - -#include diff --git a/include/Nazara/Shader/Shader.hpp b/include/Nazara/Shader/Shader.hpp deleted file mode 100644 index a871e40b0..000000000 --- a/include/Nazara/Shader/Shader.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_HPP -#define NAZARA_SHADER_HPP - -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API Shader : public ModuleBase - { - friend ModuleBase; - - public: - using Dependencies = TypeList; - - struct Config {}; - - Shader(Config /*config*/); - ~Shader() = default; - - private: - static Shader* s_instance; - }; -} - -#endif // NAZARA_SHADER_HPP diff --git a/include/Nazara/Shader/ShaderBuilder.hpp b/include/Nazara/Shader/ShaderBuilder.hpp deleted file mode 100644 index 29f206c00..000000000 --- a/include/Nazara/Shader/ShaderBuilder.hpp +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERBUILDER_HPP -#define NAZARA_SHADER_SHADERBUILDER_HPP - -#include -#include -#include -#include -#include - -namespace Nz::ShaderBuilder -{ - namespace Impl - { - struct AccessIndex - { - inline ShaderAst::AccessIndexExpressionPtr operator()(ShaderAst::ExpressionPtr expr, Int32 index) const; - inline ShaderAst::AccessIndexExpressionPtr operator()(ShaderAst::ExpressionPtr expr, const std::vector& indexConstants) const; - inline ShaderAst::AccessIndexExpressionPtr operator()(ShaderAst::ExpressionPtr expr, ShaderAst::ExpressionPtr indexExpression) const; - inline ShaderAst::AccessIndexExpressionPtr operator()(ShaderAst::ExpressionPtr expr, std::vector indexExpressions) const; - }; - - struct AccessMember - { - inline ShaderAst::AccessIdentifierExpressionPtr operator()(ShaderAst::ExpressionPtr expr, std::vector memberIdentifiers) const; - }; - - struct Assign - { - inline ShaderAst::AssignExpressionPtr operator()(ShaderAst::AssignType op, ShaderAst::ExpressionPtr left, ShaderAst::ExpressionPtr right) const; - }; - - struct Binary - { - inline ShaderAst::BinaryExpressionPtr operator()(ShaderAst::BinaryType op, ShaderAst::ExpressionPtr left, ShaderAst::ExpressionPtr right) const; - }; - - template - struct Branch - { - inline ShaderAst::BranchStatementPtr operator()(ShaderAst::ExpressionPtr condition, ShaderAst::StatementPtr truePath, ShaderAst::StatementPtr falsePath = nullptr) const; - inline ShaderAst::BranchStatementPtr operator()(std::vector condStatements, ShaderAst::StatementPtr elseStatement = nullptr) const; - }; - - struct CallFunction - { - inline ShaderAst::CallFunctionExpressionPtr operator()(std::string functionName, std::vector parameters) const; - inline ShaderAst::CallFunctionExpressionPtr operator()(ShaderAst::ExpressionPtr functionExpr, std::vector parameters) const; - }; - - struct Cast - { - inline ShaderAst::CastExpressionPtr operator()(ShaderAst::ExpressionValue targetType, ShaderAst::ExpressionPtr expression) const; - inline ShaderAst::CastExpressionPtr operator()(ShaderAst::ExpressionValue targetType, std::array expressions) const; - inline ShaderAst::CastExpressionPtr operator()(ShaderAst::ExpressionValue targetType, std::vector expressions) const; - }; - - struct ConditionalExpression - { - inline ShaderAst::ConditionalExpressionPtr operator()(ShaderAst::ExpressionPtr condition, ShaderAst::ExpressionPtr truePath, ShaderAst::ExpressionPtr falsePath) const; - }; - - struct ConditionalStatement - { - inline ShaderAst::ConditionalStatementPtr operator()(ShaderAst::ExpressionPtr condition, ShaderAst::StatementPtr statement) const; - }; - - struct Constant - { - inline ShaderAst::ConstantValueExpressionPtr operator()(ShaderAst::ConstantValue value) const; - template ShaderAst::ConstantValueExpressionPtr operator()(ShaderAst::ExpressionType type, T value) const; - }; - - struct DeclareAlias - { - inline ShaderAst::DeclareAliasStatementPtr operator()(std::string name, ShaderAst::ExpressionPtr expression) const; - }; - - struct DeclareConst - { - inline ShaderAst::DeclareConstStatementPtr operator()(std::string name, ShaderAst::ExpressionPtr initialValue) const; - inline ShaderAst::DeclareConstStatementPtr operator()(std::string name, ShaderAst::ExpressionValue type, ShaderAst::ExpressionPtr initialValue = nullptr) const; - }; - - struct DeclareFunction - { - inline ShaderAst::DeclareFunctionStatementPtr operator()(std::string name, ShaderAst::StatementPtr statement) const; - inline ShaderAst::DeclareFunctionStatementPtr operator()(std::string name, std::vector parameters, std::vector statements, ShaderAst::ExpressionValue returnType = ShaderAst::ExpressionType{ ShaderAst::NoType{} }) const; - inline ShaderAst::DeclareFunctionStatementPtr operator()(std::optional entryStage, std::string name, ShaderAst::StatementPtr statement) const; - inline ShaderAst::DeclareFunctionStatementPtr operator()(std::optional entryStage, std::string name, std::vector parameters, std::vector statements, ShaderAst::ExpressionValue returnType = ShaderAst::ExpressionType{ ShaderAst::NoType{} }) const; - }; - - struct DeclareOption - { - inline ShaderAst::DeclareOptionStatementPtr operator()(std::string name, ShaderAst::ExpressionValue type, ShaderAst::ExpressionPtr initialValue = nullptr) const; - }; - - struct DeclareStruct - { - inline ShaderAst::DeclareStructStatementPtr operator()(ShaderAst::StructDescription description, ShaderAst::ExpressionValue isExported) const; - }; - - struct DeclareVariable - { - inline ShaderAst::DeclareVariableStatementPtr operator()(std::string name, ShaderAst::ExpressionPtr initialValue) const; - inline ShaderAst::DeclareVariableStatementPtr operator()(std::string name, ShaderAst::ExpressionValue type, ShaderAst::ExpressionPtr initialValue = nullptr) const; - }; - - struct ExpressionStatement - { - inline ShaderAst::ExpressionStatementPtr operator()(ShaderAst::ExpressionPtr expression) const; - }; - - struct For - { - inline ShaderAst::ForStatementPtr operator()(std::string varName, ShaderAst::ExpressionPtr fromExpression, ShaderAst::ExpressionPtr toExpression, ShaderAst::StatementPtr statement) const; - inline ShaderAst::ForStatementPtr operator()(std::string varName, ShaderAst::ExpressionPtr fromExpression, ShaderAst::ExpressionPtr toExpression, ShaderAst::ExpressionPtr stepExpression, ShaderAst::StatementPtr statement) const; - }; - - struct ForEach - { - inline ShaderAst::ForEachStatementPtr operator()(std::string varName, ShaderAst::ExpressionPtr expression, ShaderAst::StatementPtr statement) const; - }; - - struct Function - { - inline ShaderAst::FunctionExpressionPtr operator()(std::size_t funcId) const; - }; - - struct Identifier - { - inline ShaderAst::IdentifierExpressionPtr operator()(std::string name) const; - }; - - struct Import - { - inline ShaderAst::ImportStatementPtr operator()(std::string modulePath) const; - }; - - struct Intrinsic - { - inline ShaderAst::IntrinsicExpressionPtr operator()(ShaderAst::IntrinsicType intrinsicType, std::vector parameters) const; - }; - - struct IntrinsicFunction - { - inline ShaderAst::IntrinsicFunctionExpressionPtr operator()(std::size_t intrinsicFunctionId, ShaderAst::IntrinsicType intrinsicType) const; - }; - - struct Multi - { - inline ShaderAst::MultiStatementPtr operator()(std::vector statements = {}) const; - }; - - template - struct NoParam - { - inline std::unique_ptr operator()() const; - }; - - struct Return - { - inline ShaderAst::ReturnStatementPtr operator()(ShaderAst::ExpressionPtr expr = nullptr) const; - }; - - struct Scoped - { - inline ShaderAst::ScopedStatementPtr operator()(ShaderAst::StatementPtr statement) const; - }; - - struct StructType - { - inline ShaderAst::StructTypeExpressionPtr operator()(std::size_t structTypeId) const; - }; - - struct Swizzle - { - inline ShaderAst::SwizzleExpressionPtr operator()(ShaderAst::ExpressionPtr expression, std::array swizzleComponents, std::size_t componentCount) const; - inline ShaderAst::SwizzleExpressionPtr operator()(ShaderAst::ExpressionPtr expression, std::vector swizzleComponents) const; - }; - - struct Unary - { - inline ShaderAst::UnaryExpressionPtr operator()(ShaderAst::UnaryType op, ShaderAst::ExpressionPtr expression) const; - }; - - struct Variable - { - inline ShaderAst::VariableValueExpressionPtr operator()(std::size_t variableId, ShaderAst::ExpressionType expressionType) const; - }; - - struct While - { - inline ShaderAst::WhileStatementPtr operator()(ShaderAst::ExpressionPtr condition, ShaderAst::StatementPtr body) const; - }; - } - - constexpr Impl::AccessIndex AccessIndex; - constexpr Impl::AccessMember AccessMember; - constexpr Impl::Assign Assign; - constexpr Impl::Binary Binary; - constexpr Impl::Branch Branch; - constexpr Impl::CallFunction CallFunction; - constexpr Impl::Cast Cast; - constexpr Impl::ConditionalExpression ConditionalExpression; - constexpr Impl::ConditionalStatement ConditionalStatement; - constexpr Impl::Constant Constant; - constexpr Impl::Branch ConstBranch; - constexpr Impl::DeclareAlias DeclareAlias; - constexpr Impl::DeclareConst DeclareConst; - constexpr Impl::DeclareFunction DeclareFunction; - constexpr Impl::DeclareOption DeclareOption; - constexpr Impl::DeclareStruct DeclareStruct; - constexpr Impl::DeclareVariable DeclareVariable; - constexpr Impl::ExpressionStatement ExpressionStatement; - constexpr Impl::NoParam Discard; - constexpr Impl::For For; - constexpr Impl::ForEach ForEach; - constexpr Impl::Function Function; - constexpr Impl::Identifier Identifier; - constexpr Impl::IntrinsicFunction IntrinsicFunction; - constexpr Impl::Import Import; - constexpr Impl::Intrinsic Intrinsic; - constexpr Impl::Multi MultiStatement; - constexpr Impl::NoParam NoOp; - constexpr Impl::Return Return; - constexpr Impl::Scoped Scoped; - constexpr Impl::StructType StructType; - constexpr Impl::Swizzle Swizzle; - constexpr Impl::Unary Unary; - constexpr Impl::Variable Variable; - constexpr Impl::While While; -} - -#include - -#endif // NAZARA_SHADER_SHADERBUILDER_HPP diff --git a/include/Nazara/Shader/ShaderBuilder.inl b/include/Nazara/Shader/ShaderBuilder.inl deleted file mode 100644 index b6e145265..000000000 --- a/include/Nazara/Shader/ShaderBuilder.inl +++ /dev/null @@ -1,497 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderBuilder -{ - inline ShaderAst::AccessIdentifierExpressionPtr Impl::AccessMember::operator()(ShaderAst::ExpressionPtr expr, std::vector memberIdentifiers) const - { - auto accessMemberNode = std::make_unique(); - accessMemberNode->expr = std::move(expr); - accessMemberNode->identifiers.reserve(memberIdentifiers.size()); - for (std::string& identifier : memberIdentifiers) - { - auto& identifierEntry = accessMemberNode->identifiers.emplace_back(); - identifierEntry.identifier = std::move(identifier); - } - - return accessMemberNode; - } - - inline ShaderAst::AccessIndexExpressionPtr Impl::AccessIndex::operator()(ShaderAst::ExpressionPtr expr, Int32 index) const - { - auto accessMemberNode = std::make_unique(); - accessMemberNode->expr = std::move(expr); - accessMemberNode->indices.push_back(ShaderBuilder::Constant(index)); - - return accessMemberNode; - } - - inline ShaderAst::AccessIndexExpressionPtr Impl::AccessIndex::operator()(ShaderAst::ExpressionPtr expr, const std::vector& indexConstants) const - { - auto accessMemberNode = std::make_unique(); - accessMemberNode->expr = std::move(expr); - - accessMemberNode->indices.reserve(indexConstants.size()); - for (Int32 index : indexConstants) - accessMemberNode->indices.push_back(ShaderBuilder::Constant(index)); - - return accessMemberNode; - } - - inline ShaderAst::AccessIndexExpressionPtr Impl::AccessIndex::operator()(ShaderAst::ExpressionPtr expr, ShaderAst::ExpressionPtr indexExpression) const - { - auto accessMemberNode = std::make_unique(); - accessMemberNode->expr = std::move(expr); - accessMemberNode->indices.push_back(std::move(indexExpression)); - - return accessMemberNode; - } - - inline ShaderAst::AccessIndexExpressionPtr Impl::AccessIndex::operator()(ShaderAst::ExpressionPtr expr, std::vector indexExpressions) const - { - auto accessMemberNode = std::make_unique(); - accessMemberNode->expr = std::move(expr); - accessMemberNode->indices = std::move(indexExpressions); - - return accessMemberNode; - } - - inline ShaderAst::AssignExpressionPtr Impl::Assign::operator()(ShaderAst::AssignType op, ShaderAst::ExpressionPtr left, ShaderAst::ExpressionPtr right) const - { - auto assignNode = std::make_unique(); - assignNode->op = op; - assignNode->left = std::move(left); - assignNode->right = std::move(right); - - return assignNode; - } - - inline ShaderAst::BinaryExpressionPtr Impl::Binary::operator()(ShaderAst::BinaryType op, ShaderAst::ExpressionPtr left, ShaderAst::ExpressionPtr right) const - { - auto binaryNode = std::make_unique(); - binaryNode->op = op; - binaryNode->left = std::move(left); - binaryNode->right = std::move(right); - - return binaryNode; - } - - template - ShaderAst::BranchStatementPtr Impl::Branch::operator()(ShaderAst::ExpressionPtr condition, ShaderAst::StatementPtr truePath, ShaderAst::StatementPtr falsePath) const - { - auto branchNode = std::make_unique(); - - auto& condStatement = branchNode->condStatements.emplace_back(); - condStatement.condition = std::move(condition); - condStatement.statement = std::move(truePath); - - branchNode->elseStatement = std::move(falsePath); - branchNode->isConst = Const; - - return branchNode; - } - - template - ShaderAst::BranchStatementPtr Impl::Branch::operator()(std::vector condStatements, ShaderAst::StatementPtr elseStatement) const - { - auto branchNode = std::make_unique(); - branchNode->condStatements = std::move(condStatements); - branchNode->elseStatement = std::move(elseStatement); - branchNode->isConst = Const; - - return branchNode; - } - - inline ShaderAst::CallFunctionExpressionPtr Impl::CallFunction::operator()(std::string functionName, std::vector parameters) const - { - auto callFunctionExpression = std::make_unique(); - callFunctionExpression->targetFunction = ShaderBuilder::Identifier(std::move(functionName)); - callFunctionExpression->parameters = std::move(parameters); - - return callFunctionExpression; - } - - inline ShaderAst::CallFunctionExpressionPtr Impl::CallFunction::operator()(ShaderAst::ExpressionPtr functionExpr, std::vector parameters) const - { - auto callFunctionExpression = std::make_unique(); - callFunctionExpression->targetFunction = std::move(functionExpr); - callFunctionExpression->parameters = std::move(parameters); - - return callFunctionExpression; - } - - inline ShaderAst::CastExpressionPtr Impl::Cast::operator()(ShaderAst::ExpressionValue targetType, ShaderAst::ExpressionPtr expression) const - { - auto castNode = std::make_unique(); - castNode->targetType = std::move(targetType); - castNode->expressions[0] = std::move(expression); - - return castNode; - } - - inline ShaderAst::CastExpressionPtr Impl::Cast::operator()(ShaderAst::ExpressionValue targetType, std::array expressions) const - { - auto castNode = std::make_unique(); - castNode->expressions = std::move(expressions); - castNode->targetType = std::move(targetType); - - return castNode; - } - - inline ShaderAst::CastExpressionPtr Impl::Cast::operator()(ShaderAst::ExpressionValue targetType, std::vector expressions) const - { - auto castNode = std::make_unique(); - castNode->targetType = std::move(targetType); - - assert(expressions.size() <= castNode->expressions.size()); - for (std::size_t i = 0; i < expressions.size(); ++i) - castNode->expressions[i] = std::move(expressions[i]); - - return castNode; - } - - inline ShaderAst::ConditionalExpressionPtr Impl::ConditionalExpression::operator()(ShaderAst::ExpressionPtr condition, ShaderAst::ExpressionPtr truePath, ShaderAst::ExpressionPtr falsePath) const - { - auto condExprNode = std::make_unique(); - condExprNode->condition = std::move(condition); - condExprNode->falsePath = std::move(falsePath); - condExprNode->truePath = std::move(truePath); - - return condExprNode; - } - - inline ShaderAst::ConditionalStatementPtr Impl::ConditionalStatement::operator()(ShaderAst::ExpressionPtr condition, ShaderAst::StatementPtr statement) const - { - auto condStatementNode = std::make_unique(); - condStatementNode->condition = std::move(condition); - condStatementNode->statement = std::move(statement); - - return condStatementNode; - } - - inline ShaderAst::ConstantValueExpressionPtr Impl::Constant::operator()(ShaderAst::ConstantValue value) const - { - auto constantNode = std::make_unique(); - constantNode->value = std::move(value); - constantNode->cachedExpressionType = ShaderAst::GetConstantType(constantNode->value); - - return constantNode; - } - - template - ShaderAst::ConstantValueExpressionPtr Impl::Constant::operator()(ShaderAst::ExpressionType type, T value) const - { - assert(IsPrimitiveType(type)); - - switch (std::get(type)) - { - case ShaderAst::PrimitiveType::Boolean: return ShaderBuilder::Constant(value != T(0)); - case ShaderAst::PrimitiveType::Float32: return ShaderBuilder::Constant(SafeCast(value)); - case ShaderAst::PrimitiveType::Int32: return ShaderBuilder::Constant(SafeCast(value)); - case ShaderAst::PrimitiveType::UInt32: return ShaderBuilder::Constant(SafeCast(value)); - case ShaderAst::PrimitiveType::String: return ShaderBuilder::Constant(value); - } - - throw std::runtime_error("unexpected primitive type"); - } - - inline ShaderAst::DeclareAliasStatementPtr Impl::DeclareAlias::operator()(std::string name, ShaderAst::ExpressionPtr expression) const - { - auto declareAliasNode = std::make_unique(); - declareAliasNode->name = std::move(name); - declareAliasNode->expression = std::move(expression); - - return declareAliasNode; - } - - inline ShaderAst::DeclareConstStatementPtr Impl::DeclareConst::operator()(std::string name, ShaderAst::ExpressionPtr initialValue) const - { - auto declareConstNode = std::make_unique(); - declareConstNode->name = std::move(name); - declareConstNode->expression = std::move(initialValue); - - return declareConstNode; - } - - inline ShaderAst::DeclareConstStatementPtr Impl::DeclareConst::operator()(std::string name, ShaderAst::ExpressionValue type, ShaderAst::ExpressionPtr initialValue) const - { - auto declareConstNode = std::make_unique(); - declareConstNode->name = std::move(name); - declareConstNode->type = std::move(type); - declareConstNode->expression = std::move(initialValue); - - return declareConstNode; - } - - inline ShaderAst::DeclareFunctionStatementPtr Impl::DeclareFunction::operator()(std::string name, ShaderAst::StatementPtr statement) const - { - auto declareFunctionNode = std::make_unique(); - declareFunctionNode->name = std::move(name); - declareFunctionNode->statements.push_back(std::move(statement)); - - return declareFunctionNode; - } - - inline ShaderAst::DeclareFunctionStatementPtr Impl::DeclareFunction::operator()(std::string name, std::vector parameters, std::vector statements, ShaderAst::ExpressionValue returnType) const - { - auto declareFunctionNode = std::make_unique(); - declareFunctionNode->name = std::move(name); - declareFunctionNode->parameters = std::move(parameters); - declareFunctionNode->returnType = std::move(returnType); - declareFunctionNode->statements = std::move(statements); - - return declareFunctionNode; - } - - inline ShaderAst::DeclareFunctionStatementPtr Impl::DeclareFunction::operator()(std::optional entryStage, std::string name, ShaderAst::StatementPtr statement) const - { - auto declareFunctionNode = std::make_unique(); - declareFunctionNode->name = std::move(name); - declareFunctionNode->statements.push_back(std::move(statement)); - - if (entryStage) - declareFunctionNode->entryStage = *entryStage; - - return declareFunctionNode; - } - - inline ShaderAst::DeclareFunctionStatementPtr Impl::DeclareFunction::operator()(std::optional entryStage, std::string name, std::vector parameters, std::vector statements, ShaderAst::ExpressionValue returnType) const - { - auto declareFunctionNode = std::make_unique(); - declareFunctionNode->name = std::move(name); - declareFunctionNode->parameters = std::move(parameters); - declareFunctionNode->returnType = std::move(returnType); - declareFunctionNode->statements = std::move(statements); - - if (entryStage) - declareFunctionNode->entryStage = *entryStage; - - return declareFunctionNode; - } - - inline ShaderAst::DeclareOptionStatementPtr Impl::DeclareOption::operator()(std::string name, ShaderAst::ExpressionValue type, ShaderAst::ExpressionPtr initialValue) const - { - auto declareOptionNode = std::make_unique(); - declareOptionNode->optName = std::move(name); - declareOptionNode->optType = std::move(type); - declareOptionNode->defaultValue = std::move(initialValue); - - return declareOptionNode; - } - - inline ShaderAst::DeclareStructStatementPtr Impl::DeclareStruct::operator()(ShaderAst::StructDescription description, ShaderAst::ExpressionValue isExported) const - { - auto declareStructNode = std::make_unique(); - declareStructNode->description = std::move(description); - declareStructNode->isExported = std::move(isExported); - - return declareStructNode; - } - - inline ShaderAst::DeclareVariableStatementPtr Impl::DeclareVariable::operator()(std::string name, ShaderAst::ExpressionPtr initialValue) const - { - auto declareVariableNode = std::make_unique(); - declareVariableNode->varName = std::move(name); - declareVariableNode->initialExpression = std::move(initialValue); - - return declareVariableNode; - } - - inline ShaderAst::DeclareVariableStatementPtr Impl::DeclareVariable::operator()(std::string name, ShaderAst::ExpressionValue type, ShaderAst::ExpressionPtr initialValue) const - { - auto declareVariableNode = std::make_unique(); - declareVariableNode->varName = std::move(name); - declareVariableNode->varType = std::move(type); - declareVariableNode->initialExpression = std::move(initialValue); - - return declareVariableNode; - } - - inline ShaderAst::ExpressionStatementPtr Impl::ExpressionStatement::operator()(ShaderAst::ExpressionPtr expression) const - { - auto expressionStatementNode = std::make_unique(); - expressionStatementNode->sourceLocation = expression->sourceLocation; - expressionStatementNode->expression = std::move(expression); - - return expressionStatementNode; - } - - inline ShaderAst::ForStatementPtr Impl::For::operator()(std::string varName, ShaderAst::ExpressionPtr fromExpression, ShaderAst::ExpressionPtr toExpression, ShaderAst::StatementPtr statement) const - { - auto forNode = std::make_unique(); - forNode->fromExpr = std::move(fromExpression); - forNode->statement = std::move(statement); - forNode->toExpr = std::move(toExpression); - forNode->varName = std::move(varName); - - return forNode; - } - - inline ShaderAst::ForStatementPtr Impl::For::operator()(std::string varName, ShaderAst::ExpressionPtr fromExpression, ShaderAst::ExpressionPtr toExpression, ShaderAst::ExpressionPtr stepExpression, ShaderAst::StatementPtr statement) const - { - auto forNode = std::make_unique(); - forNode->fromExpr = std::move(fromExpression); - forNode->statement = std::move(statement); - forNode->stepExpr = std::move(stepExpression); - forNode->toExpr = std::move(toExpression); - forNode->varName = std::move(varName); - - return forNode; - } - - ShaderAst::ForEachStatementPtr Impl::ForEach::operator()(std::string varName, ShaderAst::ExpressionPtr expression, ShaderAst::StatementPtr statement) const - { - auto forEachNode = std::make_unique(); - forEachNode->expression = std::move(expression); - forEachNode->statement = std::move(statement); - forEachNode->varName = std::move(varName); - - return forEachNode; - } - - inline ShaderAst::FunctionExpressionPtr Impl::Function::operator()(std::size_t funcId) const - { - auto intrinsicTypeExpr = std::make_unique(); - intrinsicTypeExpr->cachedExpressionType = ShaderAst::FunctionType{ funcId }; - intrinsicTypeExpr->funcId = funcId; - - return intrinsicTypeExpr; - } - - inline ShaderAst::IdentifierExpressionPtr Impl::Identifier::operator()(std::string name) const - { - auto identifierNode = std::make_unique(); - identifierNode->identifier = std::move(name); - - return identifierNode; - } - - inline ShaderAst::ImportStatementPtr Impl::Import::operator()(std::string moduleName) const - { - auto importNode = std::make_unique(); - importNode->moduleName = std::move(moduleName); - - return importNode; - } - - inline ShaderAst::IntrinsicExpressionPtr Impl::Intrinsic::operator()(ShaderAst::IntrinsicType intrinsicType, std::vector parameters) const - { - auto intrinsicExpression = std::make_unique(); - intrinsicExpression->intrinsic = intrinsicType; - intrinsicExpression->parameters = std::move(parameters); - - return intrinsicExpression; - } - - inline ShaderAst::IntrinsicFunctionExpressionPtr Impl::IntrinsicFunction::operator()(std::size_t intrinsicFunctionId, ShaderAst::IntrinsicType intrinsicType) const - { - auto intrinsicTypeExpr = std::make_unique(); - intrinsicTypeExpr->cachedExpressionType = ShaderAst::IntrinsicFunctionType{ intrinsicType }; - intrinsicTypeExpr->intrinsicId = intrinsicFunctionId; - - return intrinsicTypeExpr; - } - - inline ShaderAst::MultiStatementPtr Impl::Multi::operator()(std::vector statements) const - { - auto multiStatement = std::make_unique(); - multiStatement->statements = std::move(statements); - - return multiStatement; - } - - template - std::unique_ptr Impl::NoParam::operator()() const - { - return std::make_unique(); - } - - inline ShaderAst::ReturnStatementPtr Impl::Return::operator()(ShaderAst::ExpressionPtr expr) const - { - auto returnNode = std::make_unique(); - returnNode->returnExpr = std::move(expr); - - return returnNode; - } - - inline ShaderAst::ScopedStatementPtr Impl::Scoped::operator()(ShaderAst::StatementPtr statement) const - { - auto scopedNode = std::make_unique(); - scopedNode->sourceLocation = statement->sourceLocation; - scopedNode->statement = std::move(statement); - - return scopedNode; - } - - inline ShaderAst::StructTypeExpressionPtr Impl::StructType::operator()(std::size_t structTypeId) const - { - auto structTypeExpr = std::make_unique(); - structTypeExpr->cachedExpressionType = ShaderAst::StructType{ structTypeId }; - structTypeExpr->structTypeId = structTypeId; - - return structTypeExpr; - } - - inline ShaderAst::SwizzleExpressionPtr Impl::Swizzle::operator()(ShaderAst::ExpressionPtr expression, std::array swizzleComponents, std::size_t componentCount) const - { - assert(componentCount > 0); - assert(componentCount <= 4); - - auto swizzleNode = std::make_unique(); - swizzleNode->expression = std::move(expression); - swizzleNode->componentCount = componentCount; - swizzleNode->components = swizzleComponents; - - return swizzleNode; - } - - inline ShaderAst::SwizzleExpressionPtr Impl::Swizzle::operator()(ShaderAst::ExpressionPtr expression, std::vector swizzleComponents) const - { - auto swizzleNode = std::make_unique(); - swizzleNode->expression = std::move(expression); - - assert(swizzleComponents.size() <= swizzleNode->components.size()); - swizzleNode->componentCount = swizzleComponents.size(); - for (std::size_t i = 0; i < swizzleNode->componentCount; ++i) - { - assert(swizzleComponents[i] <= 4); - swizzleNode->components[i] = swizzleComponents[i]; - } - - return swizzleNode; - } - - inline ShaderAst::UnaryExpressionPtr Impl::Unary::operator()(ShaderAst::UnaryType op, ShaderAst::ExpressionPtr expression) const - { - auto unaryNode = std::make_unique(); - unaryNode->expression = std::move(expression); - unaryNode->op = op; - - return unaryNode; - } - - inline ShaderAst::VariableValueExpressionPtr Impl::Variable::operator()(std::size_t variableId, ShaderAst::ExpressionType expressionType) const - { - auto varNode = std::make_unique(); - varNode->variableId = variableId; - varNode->cachedExpressionType = std::move(expressionType); - - return varNode; - } - - inline ShaderAst::WhileStatementPtr Impl::While::operator()(ShaderAst::ExpressionPtr condition, ShaderAst::StatementPtr body) const - { - auto whileNode = std::make_unique(); - whileNode->condition = std::move(condition); - whileNode->body = std::move(body); - - return whileNode; - } -} - -#include diff --git a/include/Nazara/Shader/ShaderLangErrorList.hpp b/include/Nazara/Shader/ShaderLangErrorList.hpp deleted file mode 100644 index f69ab9279..000000000 --- a/include/Nazara/Shader/ShaderLangErrorList.hpp +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// no header guards - -#if !defined(NAZARA_SHADERLANG_ERROR) && (!defined(NAZARA_SHADERLANG_LEXER_ERROR) || !defined(NAZARA_SHADERLANG_PARSER_ERROR) || !defined(NAZARA_SHADERLANG_COMPILER_ERROR) || !defined(NAZARA_SHADERLANG_AST_ERROR)) -#error You must define NAZARA_SHADERLANG_ERROR or NAZARA_SHADERLANG_LEXER_ERROR/NAZARA_SHADERLANG_PARSER_ERROR/NAZARA_SHADERLANG_COMPILER_ERROR before including this file -#endif - -#ifndef NAZARA_SHADERLANG_AST_ERROR -#define NAZARA_SHADERLANG_AST_ERROR(...) NAZARA_SHADERLANG_ERROR(A, __VA_ARGS__) -#endif - -#ifndef NAZARA_SHADERLANG_COMPILER_ERROR -#define NAZARA_SHADERLANG_COMPILER_ERROR(...) NAZARA_SHADERLANG_ERROR(C, __VA_ARGS__) -#endif - -#ifndef NAZARA_SHADERLANG_LEXER_ERROR -#define NAZARA_SHADERLANG_LEXER_ERROR(...) NAZARA_SHADERLANG_ERROR(L, __VA_ARGS__) -#endif - -#ifndef NAZARA_SHADERLANG_PARSER_ERROR -#define NAZARA_SHADERLANG_PARSER_ERROR(...) NAZARA_SHADERLANG_ERROR(P, __VA_ARGS__) -#endif - -// Lexer errors -NAZARA_SHADERLANG_LEXER_ERROR(BadNumber, "bad number") -NAZARA_SHADERLANG_LEXER_ERROR(NumberOutOfRange, "number is out of range") -NAZARA_SHADERLANG_LEXER_ERROR(UnfinishedString, "unfinished string") -NAZARA_SHADERLANG_LEXER_ERROR(UnrecognizedChar, "unrecognized character") -NAZARA_SHADERLANG_LEXER_ERROR(UnrecognizedToken, "unrecognized token") - -// Parser errors -NAZARA_SHADERLANG_PARSER_ERROR(AttributeExpectString, "attribute {} requires a string parameter", ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(AttributeInvalidParameter, "invalid parameter {} for attribute {}", std::string, ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(AttributeMissingParameter, "attribute {} requires a parameter", ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(AttributeMultipleUnique, "attribute {} can only be present once", ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(AttributeParameterIdentifier, "attribute {} parameter can only be an identifier", ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(ExpectedToken, "expected token {}, got {}", ShaderLang::TokenType, ShaderLang::TokenType) -NAZARA_SHADERLANG_PARSER_ERROR(DuplicateIdentifier, "duplicate identifier") -NAZARA_SHADERLANG_PARSER_ERROR(DuplicateModule, "duplicate module") -NAZARA_SHADERLANG_PARSER_ERROR(InvalidVersion, "\"{}\" is not a valid version", std::string) -NAZARA_SHADERLANG_PARSER_ERROR(InvalidUuid, "\"{}\" is not a valid UUID", std::string) -NAZARA_SHADERLANG_PARSER_ERROR(MissingAttribute, "missing attribute {}", ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(ReservedKeyword, "reserved keyword") -NAZARA_SHADERLANG_PARSER_ERROR(UnknownAttribute, "unknown attribute") -NAZARA_SHADERLANG_PARSER_ERROR(UnknownType, "unknown type") -NAZARA_SHADERLANG_PARSER_ERROR(UnexpectedAttribute, "unexpected attribute {}", ShaderAst::AttributeType) -NAZARA_SHADERLANG_PARSER_ERROR(UnexpectedEndOfFile, "unexpected end of file") -NAZARA_SHADERLANG_PARSER_ERROR(UnexpectedToken, "unexpected token {}", ShaderLang::TokenType) - -// Compiler errors -NAZARA_SHADERLANG_COMPILER_ERROR(AliasUnexpectedType, "for now, only aliases, functions and structs can be aliased (got {})", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ArrayLength, "array length must a strictly positive integer, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(AssignTemporary, "temporary values cannot be assigned") -NAZARA_SHADERLANG_COMPILER_ERROR(AttributeUnexpectedExpression, "unexpected expression for this type") -NAZARA_SHADERLANG_COMPILER_ERROR(AttributeUnexpectedType, "unexpected attribute type") -NAZARA_SHADERLANG_COMPILER_ERROR(BinaryIncompatibleTypes, "incompatibles types ({} and {})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(BinaryUnsupported, "{} type ({}) does not support this binary operation", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(BranchOutsideOfFunction, "non-const branching statements can only exist inside a function") -NAZARA_SHADERLANG_COMPILER_ERROR(CastComponentMismatch, "component count ({}) doesn't match required component count ({})", UInt32, UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(CastIncompatibleBaseTypes, "incompatibles base types (expected {}, got {})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(CastIncompatibleTypes, "incompatibles types ({} and {})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(CastMatrixExpectedVector, "expected vector type, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(CastMatrixVectorComponentMismatch, "vector component count ({}) doesn't match target matrix row count ({})", UInt32, UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(CircularImport, "circular import detected on {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ConditionExpectedBool, "expected boolean for condition, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ConstMissingExpression, "const variables must have an expression") -NAZARA_SHADERLANG_COMPILER_ERROR(ConstantExpectedValue, "expected a value") -NAZARA_SHADERLANG_COMPILER_ERROR(ConstantExpressionRequired, "a constant expression is required in this context") -NAZARA_SHADERLANG_COMPILER_ERROR(DepthWriteAttribute, "only fragment entry-points can have the depth_write attribute") -NAZARA_SHADERLANG_COMPILER_ERROR(DiscardEarlyFragmentTests, "discard is not compatible with early fragment tests") -NAZARA_SHADERLANG_COMPILER_ERROR(DiscardOutsideOfFragmentStage, "discard can only be used in the fragment stage (function gets called in the {} stage)", ShaderStageType) -NAZARA_SHADERLANG_COMPILER_ERROR(DiscardOutsideOfFunction, "discard can only be used inside a function") -NAZARA_SHADERLANG_COMPILER_ERROR(EarlyFragmentTestsAttribute, "only functions with entry(frag) attribute can have the early_fragments_tests attribute") -NAZARA_SHADERLANG_COMPILER_ERROR(EntryFunctionParameter, "entry functions can either take one struct parameter or no parameter") -NAZARA_SHADERLANG_COMPILER_ERROR(EntryPointAlreadyDefined, "the {} entry type has been defined multiple times", ShaderStageType) -NAZARA_SHADERLANG_COMPILER_ERROR(ExpectedFunction, "expected function expression") -NAZARA_SHADERLANG_COMPILER_ERROR(ExpectedIntrinsicFunction, "expected intrinsic function expression") -NAZARA_SHADERLANG_COMPILER_ERROR(ExpectedPartialType, "only partial types can be specialized, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ExtAlreadyDeclared, "external variable {} is already declared", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ExtBindingAlreadyUsed, "binding (set={}, binding={}) is already in use", UInt32, UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(ExtMissingBindingIndex, "external variable requires a binding index") -NAZARA_SHADERLANG_COMPILER_ERROR(ExtTypeNotAllowed, "external variable {} is of wrong type ({}): only uniform and sampler are allowed in external blocks", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ForEachUnsupportedType, "for-each statements can only be called on array types, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ForFromTypeExpectIntegerType, "numerical for from expression must be an integer or unsigned integer, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ForStepUnmatchingType, "numerical for step expression type ({}) must match from expression type ({})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ForToUnmatchingType, "numerical for to expression type ({}) must match from expression type ({})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(FullTypeExpected, "expected a full type, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(FunctionCallExpectedFunction, "expected function expression") -NAZARA_SHADERLANG_COMPILER_ERROR(FunctionCallOutsideOfFunction, "function calls must happen inside a function") -NAZARA_SHADERLANG_COMPILER_ERROR(FunctionCallUnexpectedEntryFunction, "{} is an entry function which cannot be called by the program", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(FunctionCallUnmatchingParameterCount, "function {} expects {} parameter(s), but got {}", std::string, UInt32, UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(FunctionCallUnmatchingParameterType, "function {} parameter #{} type mismatch (expected {}, got {})", std::string, UInt32, std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(FunctionDeclarationInsideFunction, "a function cannot be defined inside another function") -NAZARA_SHADERLANG_COMPILER_ERROR(IdentifierAlreadyUsed, "identifier {} is already used", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(IndexRequiresIntegerIndices, "index access requires integer indices (got {})", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(IndexStructRequiresInt32Indices, "struct indexing requires constant i32 indices (got {})", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(IndexUnexpectedType, "unexpected type: only arrays, structs, vectors and matrices can be indexed (got {})", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(IntrinsicExpectedFloat, "expected scalar or vector floating-points") -NAZARA_SHADERLANG_COMPILER_ERROR(IntrinsicExpectedParameterCount, "expected {} parameter(s)", UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(IntrinsicExpectedType, "expected type {1} for parameter #{0}, got {2}", UInt32, std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(IntrinsicUnexpectedBoolean, "boolean parameters are not allowed") -NAZARA_SHADERLANG_COMPILER_ERROR(IntrinsicUnmatchingParameterType, "all types must match") -NAZARA_SHADERLANG_COMPILER_ERROR(InvalidCast, "invalid cast to type {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(InvalidScalarSwizzle, "invalid swizzle for scalar") -NAZARA_SHADERLANG_COMPILER_ERROR(InvalidSwizzle, "invalid swizzle {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(MissingOptionValue, "option {} requires a value (no default value set)", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ModuleCompilationFailed, "module {} compilation failed: {}", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(ModuleNotFound, "module {} not found", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(NoModuleResolver, "import statement found but no module resolver has been set (and partial sanitization is not enabled)") -NAZARA_SHADERLANG_COMPILER_ERROR(OptionDeclarationInsideFunction, "options must be declared outside of functions") -NAZARA_SHADERLANG_COMPILER_ERROR(PartialTypeExpect, "expected a {} type at #{}", std::string, UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(PartialTypeParameterCountMismatch, "parameter count mismatch (expected {}, got {})", UInt32, UInt32) -NAZARA_SHADERLANG_COMPILER_ERROR(SamplerUnexpectedType, "for now only f32 samplers are supported (got {})", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(StructDeclarationInsideFunction, "structs must be declared outside of functions") -NAZARA_SHADERLANG_COMPILER_ERROR(StructExpected, "struct type expected, got {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(StructFieldBuiltinLocation, "a struct field cannot have both builtin and location attributes") -NAZARA_SHADERLANG_COMPILER_ERROR(StructFieldMultiple, "multiple {} active struct field found, only one can be active at a time", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(StructLayoutInnerMismatch, "inner struct layout mismatch, struct is declared with {} but field has layout {}", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(StructLayoutTypeNotAllowed, "{} type is not allowed in {} layout", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(SwizzleUnexpectedType, "expression type ({}) does not support swizzling", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(UnaryUnsupported, "type ({}) does not support this unary operation", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(UnexpectedAccessedType, "unexpected type (only struct and vectors can be indexed with identifiers)") -NAZARA_SHADERLANG_COMPILER_ERROR(UnknownField, "unknown field {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(UnknownIdentifier, "unknown identifier {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(UnknownMethod, "unknown method {}", std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(UnmatchingTypes, "left expression type ({}) doesn't match right expression type ({})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(VarDeclarationMissingTypeAndValue, "variable must either have a type or an initial value") -NAZARA_SHADERLANG_COMPILER_ERROR(VarDeclarationOutsideOfFunction, "global variables outside of external blocks are forbidden") -NAZARA_SHADERLANG_COMPILER_ERROR(VarDeclarationTypeUnmatching, "initial expression type ({}) doesn't match specified type ({})", std::string, std::string) -NAZARA_SHADERLANG_COMPILER_ERROR(WhileUnrollNotSupported, "unroll(always) is not yet supported on while, use a for loop") - -// AST errors -NAZARA_SHADERLANG_AST_ERROR(AlreadyUsedIndex, "index {} is already used", std::size_t) -NAZARA_SHADERLANG_AST_ERROR(AttributeRequiresValue, "index {} is already used", std::size_t) -NAZARA_SHADERLANG_AST_ERROR(AlreadyUsedIndexPreregister, "cannot preregister used index {} as its already used", std::size_t) -NAZARA_SHADERLANG_AST_ERROR(EmptyIdentifier, "identifier cannot be empty") -NAZARA_SHADERLANG_AST_ERROR(Internal, "internal error: {}", std::string) -NAZARA_SHADERLANG_AST_ERROR(InvalidConstantIndex, "invalid constant index #{}", std::size_t) -NAZARA_SHADERLANG_AST_ERROR(InvalidIndex, "invalid index {}", std::size_t) -NAZARA_SHADERLANG_AST_ERROR(MissingExpression, "a mandatory expression is missing") -NAZARA_SHADERLANG_AST_ERROR(MissingStatement, "a mandatory statement is missing") -NAZARA_SHADERLANG_AST_ERROR(NoIdentifier, "at least one identifier is required") -NAZARA_SHADERLANG_AST_ERROR(NoIndex, "at least one index is required") -NAZARA_SHADERLANG_AST_ERROR(UnexpectedIdentifier, "unexpected identifier of type {}", std::string) - -#undef NAZARA_SHADERLANG_ERROR -#undef NAZARA_SHADERLANG_AST_ERROR -#undef NAZARA_SHADERLANG_COMPILER_ERROR -#undef NAZARA_SHADERLANG_LEXER_ERROR -#undef NAZARA_SHADERLANG_PARSER_ERROR diff --git a/include/Nazara/Shader/ShaderLangErrors.hpp b/include/Nazara/Shader/ShaderLangErrors.hpp deleted file mode 100644 index 4ff6e7306..000000000 --- a/include/Nazara/Shader/ShaderLangErrors.hpp +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERLANGERRORS_HPP -#define NAZARA_SHADER_SHADERLANGERRORS_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderLang -{ - enum class ErrorCategory - { - Ast, - Compilation, - Lexing, - Parsing, - - Max = Parsing - }; - - enum class ErrorType - { -#define NAZARA_SHADERLANG_ERROR(ErrorPrefix, ErrorName, ...) ErrorPrefix ## ErrorName, - -#include - }; - - NAZARA_SHADER_API std::string_view ToString(ErrorCategory errorCategory); - NAZARA_SHADER_API std::string_view ToString(ErrorType errorType); - - class NAZARA_SHADER_API Error : public std::exception - { - public: - inline Error(SourceLocation sourceLocation, ErrorCategory errorCategory, ErrorType errorType) noexcept; - Error(const Error&) = default; - Error(Error&&) noexcept = default; - ~Error() = default; - - inline ErrorCategory GetErrorCategory() const; - const std::string& GetErrorMessage() const; - inline ErrorType GetErrorType() const; - const std::string& GetFullErrorMessage() const; - inline const SourceLocation& GetSourceLocation() const; - - const char* what() const noexcept override; - - Error& operator=(const Error&) = default; - Error& operator=(Error&&) noexcept = default; - - protected: - virtual std::string BuildErrorMessage() const = 0; - - private: - mutable std::string m_fullErrorMessage; - mutable std::string m_errorMessage; - ErrorCategory m_errorCategory; - SourceLocation m_sourceLocation; - ErrorType m_errorType; - }; - - class AstError : public Error - { - public: - inline AstError(SourceLocation sourceLocation, ErrorType errorType) noexcept; - }; - - class CompilationError : public Error - { - public: - inline CompilationError(SourceLocation sourceLocation, ErrorType errorType) noexcept; - }; - - class LexingError : public Error - { - public: - inline LexingError(SourceLocation sourceLocation, ErrorType errorType) noexcept; - }; - - class ParsingError : public Error - { - public: - inline ParsingError(SourceLocation sourceLocation, ErrorType errorType) noexcept; - }; - -#define NAZARA_SHADERLANG_NEWERRORTYPE(Prefix, BaseClass, ErrorPrefix, ErrorName, ErrorString, ...) \ - class Prefix ## ErrorName ## Error final : public BaseClass \ - { \ - public: \ - template Prefix ## ErrorName ## Error(SourceLocation sourceLocation, Args&&... args) : \ - BaseClass(std::move(sourceLocation), ErrorType:: ErrorPrefix ## ErrorName), \ - m_parameters(std::forward(args)...) \ - { \ - } \ - \ - private: \ - std::string BuildErrorMessage() const override; \ - \ - std::tuple<__VA_ARGS__> m_parameters; \ - }; - -#define NAZARA_SHADERLANG_AST_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Ast, AstError, A, ErrorName, ErrorString, __VA_ARGS__) -#define NAZARA_SHADERLANG_LEXER_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Lexer, LexingError, L, ErrorName, ErrorString, __VA_ARGS__) -#define NAZARA_SHADERLANG_PARSER_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Parser, ParsingError, P, ErrorName, ErrorString, __VA_ARGS__) -#define NAZARA_SHADERLANG_COMPILER_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Compiler, CompilationError, C, ErrorName, ErrorString, __VA_ARGS__) - -#include - -#undef NAZARA_SHADERLANG_NEWERRORTYPE -} - -#include - -#endif // NAZARA_SHADER_SHADERLANGERRORS_HPP diff --git a/include/Nazara/Shader/ShaderLangErrors.inl b/include/Nazara/Shader/ShaderLangErrors.inl deleted file mode 100644 index ff3768dba..000000000 --- a/include/Nazara/Shader/ShaderLangErrors.inl +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderLang -{ - inline Error::Error(SourceLocation sourceLocation, ErrorCategory errorCategory, ErrorType errorType) noexcept : - m_errorCategory(errorCategory), - m_sourceLocation(std::move(sourceLocation)), - m_errorType(errorType) - { - } - - inline ErrorCategory Error::GetErrorCategory() const - { - return m_errorCategory; - } - - inline ErrorType Error::GetErrorType() const - { - return m_errorType; - } - - inline const SourceLocation& Error::GetSourceLocation() const - { - return m_sourceLocation; - } - - - inline AstError::AstError(SourceLocation sourceLocation, ErrorType errorType) noexcept : - Error(std::move(sourceLocation), ErrorCategory::Ast, errorType) - { - } - - inline CompilationError::CompilationError(SourceLocation sourceLocation, ErrorType errorType) noexcept : - Error(std::move(sourceLocation), ErrorCategory::Compilation, errorType) - { - } - - inline ParsingError::ParsingError(SourceLocation sourceLocation, ErrorType errorType) noexcept : - Error(std::move(sourceLocation), ErrorCategory::Parsing, errorType) - { - } - - inline LexingError::LexingError(SourceLocation sourceLocation, ErrorType errorType) noexcept : - Error(std::move(sourceLocation), ErrorCategory::Lexing, errorType) - { - } -} - -#include diff --git a/include/Nazara/Shader/ShaderLangLexer.hpp b/include/Nazara/Shader/ShaderLangLexer.hpp deleted file mode 100644 index 35b1097ba..000000000 --- a/include/Nazara/Shader/ShaderLangLexer.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERLANGLEXER_HPP -#define NAZARA_SHADER_SHADERLANGLEXER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderLang -{ - enum class TokenType - { -#define NAZARA_SHADERLANG_TOKEN(X) X, - -#include - }; - - struct Token - { - SourceLocation location; - TokenType type; - std::variant data; - }; - - NAZARA_SHADER_API std::vector Tokenize(const std::string_view& str, const std::string& filePath = std::string{}); - NAZARA_SHADER_API const char* ToString(TokenType tokenType); - NAZARA_SHADER_API std::string ToString(const std::vector& tokens, bool pretty = true); -} - -#include - -#endif // NAZARA_SHADER_SHADERLANGLEXER_HPP diff --git a/include/Nazara/Shader/ShaderLangLexer.inl b/include/Nazara/Shader/ShaderLangLexer.inl deleted file mode 100644 index b5208d8a1..000000000 --- a/include/Nazara/Shader/ShaderLangLexer.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Shader/ShaderLangParser.hpp b/include/Nazara/Shader/ShaderLangParser.hpp deleted file mode 100644 index 494ffc3e8..000000000 --- a/include/Nazara/Shader/ShaderLangParser.hpp +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERLANGPARSER_HPP -#define NAZARA_SHADER_SHADERLANGPARSER_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderLang -{ - class NAZARA_SHADER_API Parser - { - public: - inline Parser(); - ~Parser() = default; - - ShaderAst::ModulePtr Parse(const std::vector& tokens); - - private: - struct Attribute - { - ShaderAst::AttributeType type; - ShaderAst::ExpressionPtr args; - SourceLocation sourceLocation; - }; - - // Flow control - const Token& Advance(); - void Consume(std::size_t count = 1); - const Token& Expect(const Token& token, TokenType type); - const Token& ExpectNot(const Token& token, TokenType type); - const Token& Expect(TokenType type); - const Token& Peek(std::size_t advance = 0); - - std::vector ParseAttributes(); - void ParseModuleStatement(std::vector attributes); - void ParseVariableDeclaration(std::string& name, ShaderAst::ExpressionValue& type, ShaderAst::ExpressionPtr& initialValue, SourceLocation& sourceLocation); - - ShaderAst::ExpressionPtr BuildIdentifierAccess(ShaderAst::ExpressionPtr lhs, ShaderAst::ExpressionPtr rhs); - ShaderAst::ExpressionPtr BuildIndexAccess(ShaderAst::ExpressionPtr lhs, ShaderAst::ExpressionPtr rhs); - ShaderAst::ExpressionPtr BuildBinary(ShaderAst::BinaryType binaryType, ShaderAst::ExpressionPtr lhs, ShaderAst::ExpressionPtr rhs); - - // Statements - ShaderAst::StatementPtr ParseAliasDeclaration(); - ShaderAst::StatementPtr ParseBranchStatement(); - ShaderAst::StatementPtr ParseConstStatement(); - ShaderAst::StatementPtr ParseDiscardStatement(); - ShaderAst::StatementPtr ParseExternalBlock(std::vector attributes = {}); - ShaderAst::StatementPtr ParseForDeclaration(std::vector attributes = {}); - ShaderAst::StatementPtr ParseFunctionDeclaration(std::vector attributes = {}); - ShaderAst::DeclareFunctionStatement::Parameter ParseFunctionParameter(); - ShaderAst::StatementPtr ParseImportStatement(); - ShaderAst::StatementPtr ParseOptionDeclaration(); - ShaderAst::StatementPtr ParseReturnStatement(); - ShaderAst::StatementPtr ParseRootStatement(std::vector attributes = {}); - ShaderAst::StatementPtr ParseSingleStatement(); - ShaderAst::StatementPtr ParseStatement(); - std::vector ParseStatementList(SourceLocation* sourceLocation); - ShaderAst::StatementPtr ParseStructDeclaration(std::vector attributes = {}); - ShaderAst::StatementPtr ParseVariableDeclaration(); - ShaderAst::StatementPtr ParseWhileStatement(std::vector attributes); - - // Expressions - ShaderAst::ExpressionPtr ParseBinOpRhs(int exprPrecedence, ShaderAst::ExpressionPtr lhs); - ShaderAst::ExpressionPtr ParseConstSelectExpression(); - ShaderAst::ExpressionPtr ParseExpression(); - std::vector ParseExpressionList(TokenType terminationToken, SourceLocation* terminationLocation); - ShaderAst::ExpressionPtr ParseFloatingPointExpression(); - ShaderAst::ExpressionPtr ParseIdentifier(); - ShaderAst::ExpressionPtr ParseIntegerExpression(); - ShaderAst::ExpressionPtr ParseParenthesisExpression(); - ShaderAst::ExpressionPtr ParsePrimaryExpression(); - ShaderAst::ExpressionPtr ParseStringExpression(); - ShaderAst::ExpressionPtr ParseVariableAssignation(); - - const std::string& ParseIdentifierAsName(SourceLocation* sourceLocation); - std::string ParseModuleName(); - ShaderAst::ExpressionPtr ParseType(); - - template void HandleUniqueAttribute(ShaderAst::ExpressionValue& targetAttribute, Attribute&& attribute); - template void HandleUniqueAttribute(ShaderAst::ExpressionValue& targetAttribute, Attribute&& attribute, T defaultValue); - template void HandleUniqueStringAttribute(ShaderAst::ExpressionValue& targetAttribute, Attribute&& attribute, const M& map, std::optional defaultValue = {}); - - static int GetTokenPrecedence(TokenType token); - - struct Context - { - std::size_t tokenCount; - std::size_t tokenIndex = 0; - ShaderAst::ModulePtr module; - const Token* tokens; - bool parsingImportedModule = false; - }; - - Context* m_context; - }; - - inline ShaderAst::ModulePtr Parse(const std::string_view& source, const std::string& filePath = std::string{}); - inline ShaderAst::ModulePtr Parse(const std::vector& tokens); - NAZARA_SHADER_API ShaderAst::ModulePtr ParseFromFile(const std::filesystem::path& sourcePath); -} - -#include - -#endif // NAZARA_SHADER_SHADERLANGPARSER_HPP diff --git a/include/Nazara/Shader/ShaderLangParser.inl b/include/Nazara/Shader/ShaderLangParser.inl deleted file mode 100644 index 86679f20e..000000000 --- a/include/Nazara/Shader/ShaderLangParser.inl +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderLang -{ - inline Parser::Parser() : - m_context(nullptr) - { - } - - inline ShaderAst::ModulePtr Parse(const std::string_view& source, const std::string& filePath) - { - return Parse(Tokenize(source, filePath)); - } - - inline ShaderAst::ModulePtr Parse(const std::vector& tokens) - { - Parser parser; - return parser.Parse(tokens); - } -} - -#include diff --git a/include/Nazara/Shader/ShaderLangSourceLocation.hpp b/include/Nazara/Shader/ShaderLangSourceLocation.hpp deleted file mode 100644 index 159f5bb6a..000000000 --- a/include/Nazara/Shader/ShaderLangSourceLocation.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERLANGSOURCELOCATION_HPP -#define NAZARA_SHADER_SHADERLANGSOURCELOCATION_HPP - -#include -#include -#include -#include - -namespace Nz::ShaderLang -{ - struct SourceLocation - { - inline SourceLocation(); - inline SourceLocation(unsigned int line, unsigned int column, std::shared_ptr file); - inline SourceLocation(unsigned int line, unsigned int startColumn, unsigned int endColumn, std::shared_ptr file); - inline SourceLocation(unsigned int startLine, unsigned int endLine, unsigned int startColumn, unsigned int endColumn, std::shared_ptr file); - - inline void ExtendToLeft(const SourceLocation& leftLocation); - inline void ExtendToRight(const SourceLocation& rightLocation); - - inline bool IsValid() const; - - static inline SourceLocation BuildFromTo(const SourceLocation& leftSource, const SourceLocation& rightSource); - - std::shared_ptr file; //< Since the same file will be used for every node, prevent storing X time the same path - UInt32 endColumn; - UInt32 endLine; - UInt32 startColumn; - UInt32 startLine; - }; -} - -#include - -#endif // NAZARA_SHADER_SHADERLANGSOURCELOCATION_HPP diff --git a/include/Nazara/Shader/ShaderLangSourceLocation.inl b/include/Nazara/Shader/ShaderLangSourceLocation.inl deleted file mode 100644 index 6f09e732c..000000000 --- a/include/Nazara/Shader/ShaderLangSourceLocation.inl +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderLang -{ - inline SourceLocation::SourceLocation() : - endColumn(0), - endLine(0), - startColumn(0), - startLine(0) - { - } - - inline SourceLocation::SourceLocation(unsigned int Line, unsigned int Column, std::shared_ptr File) : - file(std::move(File)), - endColumn(Column), - endLine(Line), - startColumn(Column), - startLine(Line) - { - } - - inline SourceLocation::SourceLocation(unsigned int Line, unsigned int StartColumn, unsigned int EndColumn, std::shared_ptr File) : - file(std::move(File)), - endColumn(EndColumn), - endLine(Line), - startColumn(StartColumn), - startLine(Line) - { - } - - inline SourceLocation::SourceLocation(unsigned int StartLine, unsigned int EndLine, unsigned int StartColumn, unsigned int EndColumn, std::shared_ptr File) : - file(std::move(File)), - endColumn(EndColumn), - endLine(EndLine), - startColumn(StartColumn), - startLine(StartLine) - { - } - - inline void SourceLocation::ExtendToLeft(const SourceLocation& leftLocation) - { - assert(file == leftLocation.file); - assert(leftLocation.startLine <= endLine); - startLine = leftLocation.startLine; - assert(leftLocation.startLine < endLine || leftLocation.startColumn <= endColumn); - startColumn = leftLocation.startColumn; - } - - inline void SourceLocation::ExtendToRight(const SourceLocation& rightLocation) - { - assert(file == rightLocation.file); - assert(rightLocation.endLine >= startLine); - endLine = rightLocation.endLine; - assert(rightLocation.endLine > startLine || rightLocation.endColumn >= startColumn); - endColumn = rightLocation.endColumn; - } - - inline SourceLocation SourceLocation::BuildFromTo(const SourceLocation& leftSource, const SourceLocation& rightSource) - { - assert(leftSource.file == rightSource.file); - assert(leftSource.startLine <= rightSource.endLine); - assert(leftSource.startLine < rightSource.endLine || leftSource.startColumn <= rightSource.endColumn); - - SourceLocation sourceLoc; - sourceLoc.file = leftSource.file; - sourceLoc.startLine = leftSource.startLine; - sourceLoc.startColumn = leftSource.startColumn; - sourceLoc.endLine = rightSource.endLine; - sourceLoc.endColumn = rightSource.endColumn; - - return sourceLoc; - } - - inline bool SourceLocation::IsValid() const - { - return startLine != 0 || endLine != 0 || endColumn != 0 || startColumn != 0; - } -} - -#include diff --git a/include/Nazara/Shader/ShaderLangTokenList.hpp b/include/Nazara/Shader/ShaderLangTokenList.hpp deleted file mode 100644 index a94e359eb..000000000 --- a/include/Nazara/Shader/ShaderLangTokenList.hpp +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// no header guards - -#if !defined(NAZARA_SHADERLANG_TOKEN) -#error You must define NAZARA_SHADERLANG_TOKEN before including this file -#endif - -#ifndef NAZARA_SHADERLANG_TOKEN_LAST -#define NAZARA_SHADERLANG_TOKEN_LAST(X) NAZARA_SHADERLANG_TOKEN(X) -#endif - -NAZARA_SHADERLANG_TOKEN(Alias) -NAZARA_SHADERLANG_TOKEN(Arrow) -NAZARA_SHADERLANG_TOKEN(Assign) -NAZARA_SHADERLANG_TOKEN(BoolFalse) -NAZARA_SHADERLANG_TOKEN(BoolTrue) -NAZARA_SHADERLANG_TOKEN(ClosingParenthesis) -NAZARA_SHADERLANG_TOKEN(ClosingCurlyBracket) -NAZARA_SHADERLANG_TOKEN(ClosingSquareBracket) -NAZARA_SHADERLANG_TOKEN(Colon) -NAZARA_SHADERLANG_TOKEN(Comma) -NAZARA_SHADERLANG_TOKEN(Const) -NAZARA_SHADERLANG_TOKEN(ConstSelect) -NAZARA_SHADERLANG_TOKEN(Discard) -NAZARA_SHADERLANG_TOKEN(Divide) -NAZARA_SHADERLANG_TOKEN(DivideAssign) -NAZARA_SHADERLANG_TOKEN(Dot) -NAZARA_SHADERLANG_TOKEN(Equal) -NAZARA_SHADERLANG_TOKEN(Else) -NAZARA_SHADERLANG_TOKEN(EndOfStream) -NAZARA_SHADERLANG_TOKEN(External) -NAZARA_SHADERLANG_TOKEN(FloatingPointValue) -NAZARA_SHADERLANG_TOKEN(For) -NAZARA_SHADERLANG_TOKEN(FunctionDeclaration) -NAZARA_SHADERLANG_TOKEN(GreaterThan) -NAZARA_SHADERLANG_TOKEN(GreaterThanEqual) -NAZARA_SHADERLANG_TOKEN(IntegerValue) -NAZARA_SHADERLANG_TOKEN(Identifier) -NAZARA_SHADERLANG_TOKEN(If) -NAZARA_SHADERLANG_TOKEN(Import) -NAZARA_SHADERLANG_TOKEN(In) -NAZARA_SHADERLANG_TOKEN(LessThan) -NAZARA_SHADERLANG_TOKEN(LessThanEqual) -NAZARA_SHADERLANG_TOKEN(Let) -NAZARA_SHADERLANG_TOKEN(LogicalAnd) -NAZARA_SHADERLANG_TOKEN(LogicalAndAssign) -NAZARA_SHADERLANG_TOKEN(LogicalOr) -NAZARA_SHADERLANG_TOKEN(LogicalOrAssign) -NAZARA_SHADERLANG_TOKEN(Multiply) -NAZARA_SHADERLANG_TOKEN(MultiplyAssign) -NAZARA_SHADERLANG_TOKEN(Minus) -NAZARA_SHADERLANG_TOKEN(MinusAssign) -NAZARA_SHADERLANG_TOKEN(Module) -NAZARA_SHADERLANG_TOKEN(Not) -NAZARA_SHADERLANG_TOKEN(NotEqual) -NAZARA_SHADERLANG_TOKEN(Plus) -NAZARA_SHADERLANG_TOKEN(PlusAssign) -NAZARA_SHADERLANG_TOKEN(OpenCurlyBracket) -NAZARA_SHADERLANG_TOKEN(OpenSquareBracket) -NAZARA_SHADERLANG_TOKEN(OpenParenthesis) -NAZARA_SHADERLANG_TOKEN(Option) -NAZARA_SHADERLANG_TOKEN(Return) -NAZARA_SHADERLANG_TOKEN(Semicolon) -NAZARA_SHADERLANG_TOKEN(StringValue) -NAZARA_SHADERLANG_TOKEN(Struct) -NAZARA_SHADERLANG_TOKEN(While) - -#undef NAZARA_SHADERLANG_TOKEN -#undef NAZARA_SHADERLANG_TOKEN_LAST diff --git a/include/Nazara/Shader/ShaderModuleResolver.hpp b/include/Nazara/Shader/ShaderModuleResolver.hpp deleted file mode 100644 index 57fbf1e89..000000000 --- a/include/Nazara/Shader/ShaderModuleResolver.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERMODULERESOLVER_HPP -#define NAZARA_SHADER_SHADERMODULERESOLVER_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - namespace ShaderAst - { - using ModulePtr = std::shared_ptr; - } - - class NAZARA_SHADER_API ShaderModuleResolver - { - public: - ShaderModuleResolver() = default; - ShaderModuleResolver(const ShaderModuleResolver&) = default; - ShaderModuleResolver(ShaderModuleResolver&&) = default; - virtual ~ShaderModuleResolver(); - - virtual ShaderAst::ModulePtr Resolve(const std::string& /*moduleName*/) = 0; - - ShaderModuleResolver& operator=(const ShaderModuleResolver&) = default; - ShaderModuleResolver& operator=(ShaderModuleResolver&&) = default; - - NazaraSignal(OnModuleUpdated, ShaderModuleResolver* /*resolver*/, const std::string& /*moduleName*/); - }; -} - -#include - -#endif // NAZARA_SHADER_SHADERMODULERESOLVER_HPP diff --git a/include/Nazara/Shader/ShaderModuleResolver.inl b/include/Nazara/Shader/ShaderModuleResolver.inl deleted file mode 100644 index 326202e63..000000000 --- a/include/Nazara/Shader/ShaderModuleResolver.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Shader/ShaderWriter.hpp b/include/Nazara/Shader/ShaderWriter.hpp deleted file mode 100644 index 909f94377..000000000 --- a/include/Nazara/Shader/ShaderWriter.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SHADERWRITER_HPP -#define NAZARA_SHADER_SHADERWRITER_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class ShaderModuleResolver; - - class NAZARA_SHADER_API ShaderWriter - { - public: - struct States; - - ShaderWriter() = default; - ShaderWriter(const ShaderWriter&) = default; - ShaderWriter(ShaderWriter&&) = default; - virtual ~ShaderWriter(); - - struct States - { - std::shared_ptr shaderModuleResolver; - std::unordered_map optionValues; - bool optimize = false; - bool sanitized = false; - }; - }; -} - -#endif // NAZARA_SHADER_SHADERWRITER_HPP diff --git a/include/Nazara/Shader/SpirvAstVisitor.hpp b/include/Nazara/Shader/SpirvAstVisitor.hpp deleted file mode 100644 index 580fbb1d2..000000000 --- a/include/Nazara/Shader/SpirvAstVisitor.hpp +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVASTVISITOR_HPP -#define NAZARA_SHADER_SPIRVASTVISITOR_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class SpirvWriter; - - class NAZARA_SHADER_API SpirvAstVisitor : public ShaderAst::AstExpressionVisitorExcept, public ShaderAst::AstStatementVisitorExcept - { - public: - struct EntryPoint; - struct FuncData; - struct Variable; - - inline SpirvAstVisitor(SpirvWriter& writer, SpirvSection& instructions, std::unordered_map& funcData); - SpirvAstVisitor(const SpirvAstVisitor&) = delete; - SpirvAstVisitor(SpirvAstVisitor&&) = delete; - ~SpirvAstVisitor() = default; - - UInt32 AllocateResultId(); - - UInt32 EvaluateExpression(ShaderAst::ExpressionPtr& expr); - - const Variable& GetVariable(std::size_t varIndex) const; - - using AstExpressionVisitorExcept::Visit; - using AstStatementVisitorExcept::Visit; - - void Visit(ShaderAst::AccessIndexExpression& node) override; - void Visit(ShaderAst::AssignExpression& node) override; - void Visit(ShaderAst::BinaryExpression& node) override; - void Visit(ShaderAst::BranchStatement& node) override; - void Visit(ShaderAst::CallFunctionExpression& node) override; - void Visit(ShaderAst::CastExpression& node) override; - void Visit(ShaderAst::ConstantValueExpression& node) override; - void Visit(ShaderAst::DeclareExternalStatement& node) override; - void Visit(ShaderAst::DeclareFunctionStatement& node) override; - void Visit(ShaderAst::DeclareOptionStatement& node) override; - void Visit(ShaderAst::DeclareStructStatement& node) override; - void Visit(ShaderAst::DeclareVariableStatement& node) override; - void Visit(ShaderAst::DiscardStatement& node) override; - void Visit(ShaderAst::ExpressionStatement& node) override; - void Visit(ShaderAst::IntrinsicExpression& node) override; - void Visit(ShaderAst::MultiStatement& node) override; - void Visit(ShaderAst::NoOpStatement& node) override; - void Visit(ShaderAst::ReturnStatement& node) override; - void Visit(ShaderAst::ScopedStatement& node) override; - void Visit(ShaderAst::SwizzleExpression& node) override; - void Visit(ShaderAst::UnaryExpression& node) override; - void Visit(ShaderAst::VariableValueExpression& node) override; - void Visit(ShaderAst::WhileStatement& node) override; - - SpirvAstVisitor& operator=(const SpirvAstVisitor&) = delete; - SpirvAstVisitor& operator=(SpirvAstVisitor&&) = delete; - - struct EntryPoint - { - struct Input - { - UInt32 memberIndexConstantId; - UInt32 memberPointerId; - UInt32 varId; - }; - - struct Output - { - Int32 memberIndex; - UInt32 typeId; - UInt32 varId; - }; - - struct InputStruct - { - UInt32 pointerId; - UInt32 typeId; - }; - - ShaderStageType stageType; - std::optional inputStruct; - std::optional outputStructTypeId; - std::vector inputs; - std::vector outputs; - std::vector executionModes; - }; - - struct FuncData - { - std::optional entryPointData; - - struct FuncCall - { - std::size_t firstVarIndex; - }; - - struct Parameter - { - UInt32 pointerTypeId; - UInt32 typeId; - }; - - struct Variable - { - UInt32 typeId; - UInt32 varId; - }; - - std::size_t funcIndex; - std::string name; - std::vector funcCalls; - std::vector parameters; - std::vector variables; - std::unordered_map varIndexToVarId; - UInt32 funcId; - UInt32 funcTypeId; - UInt32 returnTypeId; - }; - - struct Variable - { - SpirvStorageClass storage; - UInt32 pointerId; - UInt32 pointedTypeId; - }; - - private: - void HandleStatementList(const std::vector& statements); - - void PushResultId(UInt32 value); - UInt32 PopResultId(); - - inline void RegisterExternalVariable(std::size_t varIndex, const ShaderAst::ExpressionType& type); - inline void RegisterStruct(std::size_t structIndex, ShaderAst::StructDescription* structDesc); - inline void RegisterVariable(std::size_t varIndex, UInt32 typeId, UInt32 pointerId, SpirvStorageClass storageClass); - - std::size_t m_extVarIndex; - std::size_t m_funcCallIndex; - std::size_t m_funcIndex; - std::unordered_map& m_funcData; - std::unordered_map m_structs; - std::unordered_map m_variables; - std::vector m_scopeSizes; - std::vector> m_functionBlocks; - std::vector m_resultIds; - SpirvBlock* m_currentBlock; - SpirvSection& m_instructions; - SpirvWriter& m_writer; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVASTVISITOR_HPP diff --git a/include/Nazara/Shader/SpirvAstVisitor.inl b/include/Nazara/Shader/SpirvAstVisitor.inl deleted file mode 100644 index 94d47c4e2..000000000 --- a/include/Nazara/Shader/SpirvAstVisitor.inl +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - inline SpirvAstVisitor::SpirvAstVisitor(SpirvWriter& writer, SpirvSection& instructions, std::unordered_map& funcData) : - m_extVarIndex(0), - m_funcIndex(0), - m_funcData(funcData), - m_currentBlock(nullptr), - m_instructions(instructions), - m_writer(writer) - { - } - - void SpirvAstVisitor::RegisterExternalVariable(std::size_t varIndex, const ShaderAst::ExpressionType& type) - { - UInt32 pointerId = m_writer.GetExtVarPointerId(varIndex); - SpirvStorageClass storageClass = (IsSamplerType(type)) ? SpirvStorageClass::UniformConstant : SpirvStorageClass::Uniform; - - RegisterVariable(varIndex, m_writer.GetTypeId(type), pointerId, storageClass); - } - - inline void SpirvAstVisitor::RegisterStruct(std::size_t structIndex, ShaderAst::StructDescription* structDesc) - { - assert(m_structs.find(structIndex) == m_structs.end()); - m_structs[structIndex] = structDesc; - } - - inline void SpirvAstVisitor::RegisterVariable(std::size_t varIndex, UInt32 typeId, UInt32 pointerId, SpirvStorageClass storageClass) - { - assert(m_variables.find(varIndex) == m_variables.end()); - m_variables[varIndex] = Variable{ - storageClass, - pointerId, - typeId - }; - } -} - -#include diff --git a/include/Nazara/Shader/SpirvBlock.hpp b/include/Nazara/Shader/SpirvBlock.hpp deleted file mode 100644 index cd25ae13a..000000000 --- a/include/Nazara/Shader/SpirvBlock.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVBLOCK_HPP -#define NAZARA_SHADER_SPIRVBLOCK_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API SpirvBlock : public SpirvSectionBase - { - public: - inline SpirvBlock(SpirvWriter& writer); - SpirvBlock(const SpirvBlock&) = default; - SpirvBlock(SpirvBlock&&) = default; - ~SpirvBlock() = default; - - inline std::size_t Append(SpirvOp opcode, const OpSize& wordCount); - template std::size_t Append(SpirvOp opcode, Args&&... args); - template std::size_t AppendVariadic(SpirvOp opcode, F&& callback); - - inline UInt32 GetLabelId() const; - - inline bool IsTerminated() const; - - SpirvBlock& operator=(const SpirvBlock&) = delete; - SpirvBlock& operator=(SpirvBlock&&) = default; - - static inline bool IsTerminationInstruction(SpirvOp op); - - private: - inline void HandleSpirvOp(SpirvOp op); - - UInt32 m_labelId; - bool m_isTerminated; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVBLOCK_HPP diff --git a/include/Nazara/Shader/SpirvBlock.inl b/include/Nazara/Shader/SpirvBlock.inl deleted file mode 100644 index 01b8880a4..000000000 --- a/include/Nazara/Shader/SpirvBlock.inl +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline SpirvBlock::SpirvBlock(SpirvWriter& writer) : - m_isTerminated(false) - { - m_labelId = writer.AllocateResultId(); - Append(SpirvOp::OpLabel, m_labelId); - } - - inline std::size_t SpirvBlock::Append(SpirvOp opcode, const OpSize& wordCount) - { - HandleSpirvOp(opcode); - - return SpirvSectionBase::Append(opcode, wordCount); - } - - template - std::size_t SpirvBlock::Append(SpirvOp opcode, Args&&... args) - { - HandleSpirvOp(opcode); - - return SpirvSectionBase::Append(opcode, std::forward(args)...); - } - - template - std::size_t SpirvBlock::AppendVariadic(SpirvOp opcode, F&& callback) - { - HandleSpirvOp(opcode); - - return SpirvSectionBase::AppendVariadic(opcode, std::forward(callback)); - } - - inline UInt32 SpirvBlock::GetLabelId() const - { - return m_labelId; - } - - inline bool SpirvBlock::IsTerminated() const - { - return m_isTerminated; - } - - inline bool SpirvBlock::IsTerminationInstruction(SpirvOp op) - { - switch (op) - { - case SpirvOp::OpBranch: - case SpirvOp::OpBranchConditional: - case SpirvOp::OpKill: - case SpirvOp::OpReturn: - case SpirvOp::OpReturnValue: - case SpirvOp::OpSwitch: - case SpirvOp::OpUnreachable: - return true; - - default: - return false; - } - } - - inline void SpirvBlock::HandleSpirvOp(SpirvOp op) - { - assert(!m_isTerminated); - if (IsTerminationInstruction(op)) - m_isTerminated = true; - } -} - -#include diff --git a/include/Nazara/Shader/SpirvConstantCache.hpp b/include/Nazara/Shader/SpirvConstantCache.hpp deleted file mode 100644 index 007523868..000000000 --- a/include/Nazara/Shader/SpirvConstantCache.hpp +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVCONSTANTCACHE_HPP -#define NAZARA_SHADER_SPIRVCONSTANTCACHE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class FieldOffsets; - class SpirvSection; - - class NAZARA_SHADER_API SpirvConstantCache - { - public: - using StructCallback = std::function; - - SpirvConstantCache(UInt32& resultId); - SpirvConstantCache(const SpirvConstantCache& cache) = delete; - SpirvConstantCache(SpirvConstantCache&& cache) noexcept; - ~SpirvConstantCache(); - - struct Constant; - struct Identifier; - struct Type; - - using ConstantPtr = std::shared_ptr; - using TypePtr = std::shared_ptr; - - struct Array - { - TypePtr elementType; - ConstantPtr length; - std::optional stride; - }; - - struct Bool {}; - - struct Float - { - UInt32 width; - }; - - struct Integer - { - UInt32 width; - bool signedness; - }; - - struct Void {}; - - struct Vector - { - TypePtr componentType; - UInt32 componentCount; - }; - - struct Matrix - { - TypePtr columnType; - UInt32 columnCount; - }; - - struct Image - { - std::optional qualifier; - std::optional depth; - std::optional sampled; - SpirvDim dim; - SpirvImageFormat format = SpirvImageFormat::Unknown; - TypePtr sampledType; - bool arrayed = false; - bool multisampled = false; - }; - - struct Pointer - { - TypePtr type; - SpirvStorageClass storageClass; - }; - - struct Function - { - TypePtr returnType; - std::vector parameters; - }; - - struct SampledImage - { - TypePtr image; - }; - - struct Structure - { - struct Member - { - std::string name; - TypePtr type; - mutable std::optional offset; - }; - - std::string name; - std::vector members; - std::vector decorations; - }; - - using AnyType = std::variant; - - struct ConstantBool - { - bool value; - }; - - struct ConstantComposite - { - TypePtr type; - std::vector values; - }; - - struct ConstantScalar - { - std::variant value; - }; - - using AnyConstant = std::variant; - - struct Variable - { - std::optional funcId; //< For inputs/outputs - std::optional initializer; - std::string debugName; - TypePtr type; - SpirvStorageClass storageClass; - }; - - using BaseType = std::variant; - using CompositeValue = std::variant; - using PointerOrBaseType = std::variant; - using PrimitiveType = std::variant; - using ScalarType = std::variant; - - struct Constant - { - Constant(AnyConstant c) : - constant(std::move(c)) - { - } - - AnyConstant constant; - }; - - struct Type - { - Type(AnyType c) : - type(std::move(c)) - { - } - - AnyType type; - }; - - ConstantPtr BuildConstant(const ShaderAst::ConstantValue& value) const; - FieldOffsets BuildFieldOffsets(const Structure& structData) const; - TypePtr BuildFunctionType(const ShaderAst::ExpressionType& retType, const std::vector& parameters) const; - TypePtr BuildPointerType(const ShaderAst::PrimitiveType& type, SpirvStorageClass storageClass) const; - TypePtr BuildPointerType(const ShaderAst::ExpressionType& type, SpirvStorageClass storageClass) const; - TypePtr BuildPointerType(const TypePtr& type, SpirvStorageClass storageClass) const; - TypePtr BuildType(const ShaderAst::AliasType& type) const; - TypePtr BuildType(const ShaderAst::ArrayType& type) const; - TypePtr BuildType(const ShaderAst::ExpressionType& type) const; - TypePtr BuildType(const ShaderAst::MatrixType& type) const; - TypePtr BuildType(const ShaderAst::NoType& type) const; - TypePtr BuildType(const ShaderAst::PrimitiveType& type) const; - TypePtr BuildType(const ShaderAst::SamplerType& type) const; - TypePtr BuildType(const ShaderAst::StructType& type) const; - TypePtr BuildType(const ShaderAst::StructDescription& structDesc, std::vector decorations = {}) const; - TypePtr BuildType(const ShaderAst::VectorType& type) const; - TypePtr BuildType(const ShaderAst::UniformType& type) const; - - UInt32 GetId(const Constant& c); - UInt32 GetId(const Type& t); - UInt32 GetId(const Variable& v); - - UInt32 Register(Constant c); - UInt32 Register(Type t); - UInt32 Register(Variable v); - - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Array& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Bool& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Float& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Function& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Image& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Integer& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Matrix& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Pointer& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const SampledImage& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Structure& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Type& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Vector& type, std::size_t arrayLength) const; - std::size_t RegisterArrayField(FieldOffsets& fieldOffsets, const Void& type, std::size_t arrayLength) const; - - void SetStructCallback(StructCallback callback); - - void Write(SpirvSection& annotations, SpirvSection& constants, SpirvSection& debugInfos); - - SpirvConstantCache& operator=(const SpirvConstantCache& cache) = delete; - SpirvConstantCache& operator=(SpirvConstantCache&& cache) noexcept; - - private: - struct DepRegisterer; - struct Eq; - struct Internal; - - void Write(const AnyConstant& constant, UInt32 resultId, SpirvSection& constants); - void Write(const AnyType& type, UInt32 resultId, SpirvSection& annotations, SpirvSection& constants, SpirvSection& debugInfos); - - void WriteStruct(const Structure& structData, UInt32 resultId, SpirvSection& annotations, SpirvSection& constants, SpirvSection& debugInfos); - - std::unique_ptr m_internal; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVCONSTANTCACHE_HPP diff --git a/include/Nazara/Shader/SpirvConstantCache.inl b/include/Nazara/Shader/SpirvConstantCache.inl deleted file mode 100644 index 8ae2b1af0..000000000 --- a/include/Nazara/Shader/SpirvConstantCache.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Shader/SpirvData.hpp b/include/Nazara/Shader/SpirvData.hpp deleted file mode 100644 index 819fe255c..000000000 --- a/include/Nazara/Shader/SpirvData.hpp +++ /dev/null @@ -1,1873 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// this file was automatically generated and should not be edited - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVDATA_HPP -#define NAZARA_SHADER_SPIRVDATA_HPP - -#include -#include -#include - -namespace Nz -{ - constexpr UInt32 SpirvMagicNumber = 0x07230203; - constexpr UInt32 SpirvMajorVersion = 1; - constexpr UInt32 SpirvMinorVersion = 6; - constexpr UInt32 SpirvRevision = 1; - constexpr UInt32 SpirvVersion = (SpirvMajorVersion << 16) | (SpirvMinorVersion << 8); - - enum class SpirvOp - { - OpNop = 0, - OpUndef = 1, - OpSourceContinued = 2, - OpSource = 3, - OpSourceExtension = 4, - OpName = 5, - OpMemberName = 6, - OpString = 7, - OpLine = 8, - OpExtension = 10, - OpExtInstImport = 11, - OpExtInst = 12, - OpMemoryModel = 14, - OpEntryPoint = 15, - OpExecutionMode = 16, - OpCapability = 17, - OpTypeVoid = 19, - OpTypeBool = 20, - OpTypeInt = 21, - OpTypeFloat = 22, - OpTypeVector = 23, - OpTypeMatrix = 24, - OpTypeImage = 25, - OpTypeSampler = 26, - OpTypeSampledImage = 27, - OpTypeArray = 28, - OpTypeRuntimeArray = 29, - OpTypeStruct = 30, - OpTypeOpaque = 31, - OpTypePointer = 32, - OpTypeFunction = 33, - OpTypeEvent = 34, - OpTypeDeviceEvent = 35, - OpTypeReserveId = 36, - OpTypeQueue = 37, - OpTypePipe = 38, - OpTypeForwardPointer = 39, - OpConstantTrue = 41, - OpConstantFalse = 42, - OpConstant = 43, - OpConstantComposite = 44, - OpConstantSampler = 45, - OpConstantNull = 46, - OpSpecConstantTrue = 48, - OpSpecConstantFalse = 49, - OpSpecConstant = 50, - OpSpecConstantComposite = 51, - OpSpecConstantOp = 52, - OpFunction = 54, - OpFunctionParameter = 55, - OpFunctionEnd = 56, - OpFunctionCall = 57, - OpVariable = 59, - OpImageTexelPointer = 60, - OpLoad = 61, - OpStore = 62, - OpCopyMemory = 63, - OpCopyMemorySized = 64, - OpAccessChain = 65, - OpInBoundsAccessChain = 66, - OpPtrAccessChain = 67, - OpArrayLength = 68, - OpGenericPtrMemSemantics = 69, - OpInBoundsPtrAccessChain = 70, - OpDecorate = 71, - OpMemberDecorate = 72, - OpDecorationGroup = 73, - OpGroupDecorate = 74, - OpGroupMemberDecorate = 75, - OpVectorExtractDynamic = 77, - OpVectorInsertDynamic = 78, - OpVectorShuffle = 79, - OpCompositeConstruct = 80, - OpCompositeExtract = 81, - OpCompositeInsert = 82, - OpCopyObject = 83, - OpTranspose = 84, - OpSampledImage = 86, - OpImageSampleImplicitLod = 87, - OpImageSampleExplicitLod = 88, - OpImageSampleDrefImplicitLod = 89, - OpImageSampleDrefExplicitLod = 90, - OpImageSampleProjImplicitLod = 91, - OpImageSampleProjExplicitLod = 92, - OpImageSampleProjDrefImplicitLod = 93, - OpImageSampleProjDrefExplicitLod = 94, - OpImageFetch = 95, - OpImageGather = 96, - OpImageDrefGather = 97, - OpImageRead = 98, - OpImageWrite = 99, - OpImage = 100, - OpImageQueryFormat = 101, - OpImageQueryOrder = 102, - OpImageQuerySizeLod = 103, - OpImageQuerySize = 104, - OpImageQueryLod = 105, - OpImageQueryLevels = 106, - OpImageQuerySamples = 107, - OpConvertFToU = 109, - OpConvertFToS = 110, - OpConvertSToF = 111, - OpConvertUToF = 112, - OpUConvert = 113, - OpSConvert = 114, - OpFConvert = 115, - OpQuantizeToF16 = 116, - OpConvertPtrToU = 117, - OpSatConvertSToU = 118, - OpSatConvertUToS = 119, - OpConvertUToPtr = 120, - OpPtrCastToGeneric = 121, - OpGenericCastToPtr = 122, - OpGenericCastToPtrExplicit = 123, - OpBitcast = 124, - OpSNegate = 126, - OpFNegate = 127, - OpIAdd = 128, - OpFAdd = 129, - OpISub = 130, - OpFSub = 131, - OpIMul = 132, - OpFMul = 133, - OpUDiv = 134, - OpSDiv = 135, - OpFDiv = 136, - OpUMod = 137, - OpSRem = 138, - OpSMod = 139, - OpFRem = 140, - OpFMod = 141, - OpVectorTimesScalar = 142, - OpMatrixTimesScalar = 143, - OpVectorTimesMatrix = 144, - OpMatrixTimesVector = 145, - OpMatrixTimesMatrix = 146, - OpOuterProduct = 147, - OpDot = 148, - OpIAddCarry = 149, - OpISubBorrow = 150, - OpUMulExtended = 151, - OpSMulExtended = 152, - OpAny = 154, - OpAll = 155, - OpIsNan = 156, - OpIsInf = 157, - OpIsFinite = 158, - OpIsNormal = 159, - OpSignBitSet = 160, - OpLessOrGreater = 161, - OpOrdered = 162, - OpUnordered = 163, - OpLogicalEqual = 164, - OpLogicalNotEqual = 165, - OpLogicalOr = 166, - OpLogicalAnd = 167, - OpLogicalNot = 168, - OpSelect = 169, - OpIEqual = 170, - OpINotEqual = 171, - OpUGreaterThan = 172, - OpSGreaterThan = 173, - OpUGreaterThanEqual = 174, - OpSGreaterThanEqual = 175, - OpULessThan = 176, - OpSLessThan = 177, - OpULessThanEqual = 178, - OpSLessThanEqual = 179, - OpFOrdEqual = 180, - OpFUnordEqual = 181, - OpFOrdNotEqual = 182, - OpFUnordNotEqual = 183, - OpFOrdLessThan = 184, - OpFUnordLessThan = 185, - OpFOrdGreaterThan = 186, - OpFUnordGreaterThan = 187, - OpFOrdLessThanEqual = 188, - OpFUnordLessThanEqual = 189, - OpFOrdGreaterThanEqual = 190, - OpFUnordGreaterThanEqual = 191, - OpShiftRightLogical = 194, - OpShiftRightArithmetic = 195, - OpShiftLeftLogical = 196, - OpBitwiseOr = 197, - OpBitwiseXor = 198, - OpBitwiseAnd = 199, - OpNot = 200, - OpBitFieldInsert = 201, - OpBitFieldSExtract = 202, - OpBitFieldUExtract = 203, - OpBitReverse = 204, - OpBitCount = 205, - OpDPdx = 207, - OpDPdy = 208, - OpFwidth = 209, - OpDPdxFine = 210, - OpDPdyFine = 211, - OpFwidthFine = 212, - OpDPdxCoarse = 213, - OpDPdyCoarse = 214, - OpFwidthCoarse = 215, - OpEmitVertex = 218, - OpEndPrimitive = 219, - OpEmitStreamVertex = 220, - OpEndStreamPrimitive = 221, - OpControlBarrier = 224, - OpMemoryBarrier = 225, - OpAtomicLoad = 227, - OpAtomicStore = 228, - OpAtomicExchange = 229, - OpAtomicCompareExchange = 230, - OpAtomicCompareExchangeWeak = 231, - OpAtomicIIncrement = 232, - OpAtomicIDecrement = 233, - OpAtomicIAdd = 234, - OpAtomicISub = 235, - OpAtomicSMin = 236, - OpAtomicUMin = 237, - OpAtomicSMax = 238, - OpAtomicUMax = 239, - OpAtomicAnd = 240, - OpAtomicOr = 241, - OpAtomicXor = 242, - OpPhi = 245, - OpLoopMerge = 246, - OpSelectionMerge = 247, - OpLabel = 248, - OpBranch = 249, - OpBranchConditional = 250, - OpSwitch = 251, - OpKill = 252, - OpReturn = 253, - OpReturnValue = 254, - OpUnreachable = 255, - OpLifetimeStart = 256, - OpLifetimeStop = 257, - OpGroupAsyncCopy = 259, - OpGroupWaitEvents = 260, - OpGroupAll = 261, - OpGroupAny = 262, - OpGroupBroadcast = 263, - OpGroupIAdd = 264, - OpGroupFAdd = 265, - OpGroupFMin = 266, - OpGroupUMin = 267, - OpGroupSMin = 268, - OpGroupFMax = 269, - OpGroupUMax = 270, - OpGroupSMax = 271, - OpReadPipe = 274, - OpWritePipe = 275, - OpReservedReadPipe = 276, - OpReservedWritePipe = 277, - OpReserveReadPipePackets = 278, - OpReserveWritePipePackets = 279, - OpCommitReadPipe = 280, - OpCommitWritePipe = 281, - OpIsValidReserveId = 282, - OpGetNumPipePackets = 283, - OpGetMaxPipePackets = 284, - OpGroupReserveReadPipePackets = 285, - OpGroupReserveWritePipePackets = 286, - OpGroupCommitReadPipe = 287, - OpGroupCommitWritePipe = 288, - OpEnqueueMarker = 291, - OpEnqueueKernel = 292, - OpGetKernelNDrangeSubGroupCount = 293, - OpGetKernelNDrangeMaxSubGroupSize = 294, - OpGetKernelWorkGroupSize = 295, - OpGetKernelPreferredWorkGroupSizeMultiple = 296, - OpRetainEvent = 297, - OpReleaseEvent = 298, - OpCreateUserEvent = 299, - OpIsValidEvent = 300, - OpSetUserEventStatus = 301, - OpCaptureEventProfilingInfo = 302, - OpGetDefaultQueue = 303, - OpBuildNDRange = 304, - OpImageSparseSampleImplicitLod = 305, - OpImageSparseSampleExplicitLod = 306, - OpImageSparseSampleDrefImplicitLod = 307, - OpImageSparseSampleDrefExplicitLod = 308, - OpImageSparseSampleProjImplicitLod = 309, - OpImageSparseSampleProjExplicitLod = 310, - OpImageSparseSampleProjDrefImplicitLod = 311, - OpImageSparseSampleProjDrefExplicitLod = 312, - OpImageSparseFetch = 313, - OpImageSparseGather = 314, - OpImageSparseDrefGather = 315, - OpImageSparseTexelsResident = 316, - OpNoLine = 317, - OpAtomicFlagTestAndSet = 318, - OpAtomicFlagClear = 319, - OpImageSparseRead = 320, - OpSizeOf = 321, - OpTypePipeStorage = 322, - OpConstantPipeStorage = 323, - OpCreatePipeFromPipeStorage = 324, - OpGetKernelLocalSizeForSubgroupCount = 325, - OpGetKernelMaxNumSubgroups = 326, - OpTypeNamedBarrier = 327, - OpNamedBarrierInitialize = 328, - OpMemoryNamedBarrier = 329, - OpModuleProcessed = 330, - OpExecutionModeId = 331, - OpDecorateId = 332, - OpGroupNonUniformElect = 333, - OpGroupNonUniformAll = 334, - OpGroupNonUniformAny = 335, - OpGroupNonUniformAllEqual = 336, - OpGroupNonUniformBroadcast = 337, - OpGroupNonUniformBroadcastFirst = 338, - OpGroupNonUniformBallot = 339, - OpGroupNonUniformInverseBallot = 340, - OpGroupNonUniformBallotBitExtract = 341, - OpGroupNonUniformBallotBitCount = 342, - OpGroupNonUniformBallotFindLSB = 343, - OpGroupNonUniformBallotFindMSB = 344, - OpGroupNonUniformShuffle = 345, - OpGroupNonUniformShuffleXor = 346, - OpGroupNonUniformShuffleUp = 347, - OpGroupNonUniformShuffleDown = 348, - OpGroupNonUniformIAdd = 349, - OpGroupNonUniformFAdd = 350, - OpGroupNonUniformIMul = 351, - OpGroupNonUniformFMul = 352, - OpGroupNonUniformSMin = 353, - OpGroupNonUniformUMin = 354, - OpGroupNonUniformFMin = 355, - OpGroupNonUniformSMax = 356, - OpGroupNonUniformUMax = 357, - OpGroupNonUniformFMax = 358, - OpGroupNonUniformBitwiseAnd = 359, - OpGroupNonUniformBitwiseOr = 360, - OpGroupNonUniformBitwiseXor = 361, - OpGroupNonUniformLogicalAnd = 362, - OpGroupNonUniformLogicalOr = 363, - OpGroupNonUniformLogicalXor = 364, - OpGroupNonUniformQuadBroadcast = 365, - OpGroupNonUniformQuadSwap = 366, - OpCopyLogical = 400, - OpPtrEqual = 401, - OpPtrNotEqual = 402, - OpPtrDiff = 403, - OpTerminateInvocation = 4416, - OpSubgroupBallotKHR = 4421, - OpSubgroupFirstInvocationKHR = 4422, - OpSubgroupAllKHR = 4428, - OpSubgroupAnyKHR = 4429, - OpSubgroupAllEqualKHR = 4430, - OpGroupNonUniformRotateKHR = 4431, - OpSubgroupReadInvocationKHR = 4432, - OpTraceRayKHR = 4445, - OpExecuteCallableKHR = 4446, - OpConvertUToAccelerationStructureKHR = 4447, - OpIgnoreIntersectionKHR = 4448, - OpTerminateRayKHR = 4449, - OpSDot = 4450, - OpSDotKHR = 4450, - OpUDot = 4451, - OpUDotKHR = 4451, - OpSUDot = 4452, - OpSUDotKHR = 4452, - OpSDotAccSat = 4453, - OpSDotAccSatKHR = 4453, - OpUDotAccSat = 4454, - OpUDotAccSatKHR = 4454, - OpSUDotAccSat = 4455, - OpSUDotAccSatKHR = 4455, - OpTypeRayQueryKHR = 4472, - OpRayQueryInitializeKHR = 4473, - OpRayQueryTerminateKHR = 4474, - OpRayQueryGenerateIntersectionKHR = 4475, - OpRayQueryConfirmIntersectionKHR = 4476, - OpRayQueryProceedKHR = 4477, - OpRayQueryGetIntersectionTypeKHR = 4479, - OpGroupIAddNonUniformAMD = 5000, - OpGroupFAddNonUniformAMD = 5001, - OpGroupFMinNonUniformAMD = 5002, - OpGroupUMinNonUniformAMD = 5003, - OpGroupSMinNonUniformAMD = 5004, - OpGroupFMaxNonUniformAMD = 5005, - OpGroupUMaxNonUniformAMD = 5006, - OpGroupSMaxNonUniformAMD = 5007, - OpFragmentMaskFetchAMD = 5011, - OpFragmentFetchAMD = 5012, - OpReadClockKHR = 5056, - OpImageSampleFootprintNV = 5283, - OpGroupNonUniformPartitionNV = 5296, - OpWritePackedPrimitiveIndices4x8NV = 5299, - OpReportIntersectionNV = 5334, - OpReportIntersectionKHR = 5334, - OpIgnoreIntersectionNV = 5335, - OpTerminateRayNV = 5336, - OpTraceNV = 5337, - OpTraceMotionNV = 5338, - OpTraceRayMotionNV = 5339, - OpTypeAccelerationStructureNV = 5341, - OpTypeAccelerationStructureKHR = 5341, - OpExecuteCallableNV = 5344, - OpTypeCooperativeMatrixNV = 5358, - OpCooperativeMatrixLoadNV = 5359, - OpCooperativeMatrixStoreNV = 5360, - OpCooperativeMatrixMulAddNV = 5361, - OpCooperativeMatrixLengthNV = 5362, - OpBeginInvocationInterlockEXT = 5364, - OpEndInvocationInterlockEXT = 5365, - OpDemoteToHelperInvocation = 5380, - OpDemoteToHelperInvocationEXT = 5380, - OpIsHelperInvocationEXT = 5381, - OpConvertUToImageNV = 5391, - OpConvertUToSamplerNV = 5392, - OpConvertImageToUNV = 5393, - OpConvertSamplerToUNV = 5394, - OpConvertUToSampledImageNV = 5395, - OpConvertSampledImageToUNV = 5396, - OpSamplerImageAddressingModeNV = 5397, - OpSubgroupShuffleINTEL = 5571, - OpSubgroupShuffleDownINTEL = 5572, - OpSubgroupShuffleUpINTEL = 5573, - OpSubgroupShuffleXorINTEL = 5574, - OpSubgroupBlockReadINTEL = 5575, - OpSubgroupBlockWriteINTEL = 5576, - OpSubgroupImageBlockReadINTEL = 5577, - OpSubgroupImageBlockWriteINTEL = 5578, - OpSubgroupImageMediaBlockReadINTEL = 5580, - OpSubgroupImageMediaBlockWriteINTEL = 5581, - OpUCountLeadingZerosINTEL = 5585, - OpUCountTrailingZerosINTEL = 5586, - OpAbsISubINTEL = 5587, - OpAbsUSubINTEL = 5588, - OpIAddSatINTEL = 5589, - OpUAddSatINTEL = 5590, - OpIAverageINTEL = 5591, - OpUAverageINTEL = 5592, - OpIAverageRoundedINTEL = 5593, - OpUAverageRoundedINTEL = 5594, - OpISubSatINTEL = 5595, - OpUSubSatINTEL = 5596, - OpIMul32x16INTEL = 5597, - OpUMul32x16INTEL = 5598, - OpConstantFunctionPointerINTEL = 5600, - OpFunctionPointerCallINTEL = 5601, - OpAsmTargetINTEL = 5609, - OpAsmINTEL = 5610, - OpAsmCallINTEL = 5611, - OpAtomicFMinEXT = 5614, - OpAtomicFMaxEXT = 5615, - OpAssumeTrueKHR = 5630, - OpExpectKHR = 5631, - OpDecorateString = 5632, - OpDecorateStringGOOGLE = 5632, - OpMemberDecorateString = 5633, - OpMemberDecorateStringGOOGLE = 5633, - OpVmeImageINTEL = 5699, - OpTypeVmeImageINTEL = 5700, - OpTypeAvcImePayloadINTEL = 5701, - OpTypeAvcRefPayloadINTEL = 5702, - OpTypeAvcSicPayloadINTEL = 5703, - OpTypeAvcMcePayloadINTEL = 5704, - OpTypeAvcMceResultINTEL = 5705, - OpTypeAvcImeResultINTEL = 5706, - OpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707, - OpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708, - OpTypeAvcImeSingleReferenceStreaminINTEL = 5709, - OpTypeAvcImeDualReferenceStreaminINTEL = 5710, - OpTypeAvcRefResultINTEL = 5711, - OpTypeAvcSicResultINTEL = 5712, - OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713, - OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714, - OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715, - OpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716, - OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717, - OpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718, - OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719, - OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720, - OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721, - OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722, - OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723, - OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724, - OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725, - OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726, - OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727, - OpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728, - OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729, - OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730, - OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731, - OpSubgroupAvcMceConvertToImePayloadINTEL = 5732, - OpSubgroupAvcMceConvertToImeResultINTEL = 5733, - OpSubgroupAvcMceConvertToRefPayloadINTEL = 5734, - OpSubgroupAvcMceConvertToRefResultINTEL = 5735, - OpSubgroupAvcMceConvertToSicPayloadINTEL = 5736, - OpSubgroupAvcMceConvertToSicResultINTEL = 5737, - OpSubgroupAvcMceGetMotionVectorsINTEL = 5738, - OpSubgroupAvcMceGetInterDistortionsINTEL = 5739, - OpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740, - OpSubgroupAvcMceGetInterMajorShapeINTEL = 5741, - OpSubgroupAvcMceGetInterMinorShapeINTEL = 5742, - OpSubgroupAvcMceGetInterDirectionsINTEL = 5743, - OpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744, - OpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745, - OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746, - OpSubgroupAvcImeInitializeINTEL = 5747, - OpSubgroupAvcImeSetSingleReferenceINTEL = 5748, - OpSubgroupAvcImeSetDualReferenceINTEL = 5749, - OpSubgroupAvcImeRefWindowSizeINTEL = 5750, - OpSubgroupAvcImeAdjustRefOffsetINTEL = 5751, - OpSubgroupAvcImeConvertToMcePayloadINTEL = 5752, - OpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753, - OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754, - OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755, - OpSubgroupAvcImeSetWeightedSadINTEL = 5756, - OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757, - OpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758, - OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759, - OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760, - OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761, - OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762, - OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763, - OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764, - OpSubgroupAvcImeConvertToMceResultINTEL = 5765, - OpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766, - OpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767, - OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768, - OpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769, - OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770, - OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771, - OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772, - OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773, - OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774, - OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775, - OpSubgroupAvcImeGetBorderReachedINTEL = 5776, - OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777, - OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778, - OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779, - OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780, - OpSubgroupAvcFmeInitializeINTEL = 5781, - OpSubgroupAvcBmeInitializeINTEL = 5782, - OpSubgroupAvcRefConvertToMcePayloadINTEL = 5783, - OpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784, - OpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785, - OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786, - OpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787, - OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788, - OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789, - OpSubgroupAvcRefConvertToMceResultINTEL = 5790, - OpSubgroupAvcSicInitializeINTEL = 5791, - OpSubgroupAvcSicConfigureSkcINTEL = 5792, - OpSubgroupAvcSicConfigureIpeLumaINTEL = 5793, - OpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794, - OpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795, - OpSubgroupAvcSicConvertToMcePayloadINTEL = 5796, - OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797, - OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798, - OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799, - OpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800, - OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801, - OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802, - OpSubgroupAvcSicEvaluateIpeINTEL = 5803, - OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804, - OpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805, - OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806, - OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807, - OpSubgroupAvcSicConvertToMceResultINTEL = 5808, - OpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809, - OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810, - OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811, - OpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812, - OpSubgroupAvcSicGetIpeChromaModeINTEL = 5813, - OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, - OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, - OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, - OpVariableLengthArrayINTEL = 5818, - OpSaveMemoryINTEL = 5819, - OpRestoreMemoryINTEL = 5820, - OpArbitraryFloatSinCosPiINTEL = 5840, - OpArbitraryFloatCastINTEL = 5841, - OpArbitraryFloatCastFromIntINTEL = 5842, - OpArbitraryFloatCastToIntINTEL = 5843, - OpArbitraryFloatAddINTEL = 5846, - OpArbitraryFloatSubINTEL = 5847, - OpArbitraryFloatMulINTEL = 5848, - OpArbitraryFloatDivINTEL = 5849, - OpArbitraryFloatGTINTEL = 5850, - OpArbitraryFloatGEINTEL = 5851, - OpArbitraryFloatLTINTEL = 5852, - OpArbitraryFloatLEINTEL = 5853, - OpArbitraryFloatEQINTEL = 5854, - OpArbitraryFloatRecipINTEL = 5855, - OpArbitraryFloatRSqrtINTEL = 5856, - OpArbitraryFloatCbrtINTEL = 5857, - OpArbitraryFloatHypotINTEL = 5858, - OpArbitraryFloatSqrtINTEL = 5859, - OpArbitraryFloatLogINTEL = 5860, - OpArbitraryFloatLog2INTEL = 5861, - OpArbitraryFloatLog10INTEL = 5862, - OpArbitraryFloatLog1pINTEL = 5863, - OpArbitraryFloatExpINTEL = 5864, - OpArbitraryFloatExp2INTEL = 5865, - OpArbitraryFloatExp10INTEL = 5866, - OpArbitraryFloatExpm1INTEL = 5867, - OpArbitraryFloatSinINTEL = 5868, - OpArbitraryFloatCosINTEL = 5869, - OpArbitraryFloatSinCosINTEL = 5870, - OpArbitraryFloatSinPiINTEL = 5871, - OpArbitraryFloatCosPiINTEL = 5872, - OpArbitraryFloatASinINTEL = 5873, - OpArbitraryFloatASinPiINTEL = 5874, - OpArbitraryFloatACosINTEL = 5875, - OpArbitraryFloatACosPiINTEL = 5876, - OpArbitraryFloatATanINTEL = 5877, - OpArbitraryFloatATanPiINTEL = 5878, - OpArbitraryFloatATan2INTEL = 5879, - OpArbitraryFloatPowINTEL = 5880, - OpArbitraryFloatPowRINTEL = 5881, - OpArbitraryFloatPowNINTEL = 5882, - OpLoopControlINTEL = 5887, - OpAliasDomainDeclINTEL = 5911, - OpAliasScopeDeclINTEL = 5912, - OpAliasScopeListDeclINTEL = 5913, - OpFixedSqrtINTEL = 5923, - OpFixedRecipINTEL = 5924, - OpFixedRsqrtINTEL = 5925, - OpFixedSinINTEL = 5926, - OpFixedCosINTEL = 5927, - OpFixedSinCosINTEL = 5928, - OpFixedSinPiINTEL = 5929, - OpFixedCosPiINTEL = 5930, - OpFixedSinCosPiINTEL = 5931, - OpFixedLogINTEL = 5932, - OpFixedExpINTEL = 5933, - OpPtrCastToCrossWorkgroupINTEL = 5934, - OpCrossWorkgroupCastToPtrINTEL = 5938, - OpReadPipeBlockingINTEL = 5946, - OpWritePipeBlockingINTEL = 5947, - OpFPGARegINTEL = 5949, - OpRayQueryGetRayTMinKHR = 6016, - OpRayQueryGetRayFlagsKHR = 6017, - OpRayQueryGetIntersectionTKHR = 6018, - OpRayQueryGetIntersectionInstanceCustomIndexKHR = 6019, - OpRayQueryGetIntersectionInstanceIdKHR = 6020, - OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021, - OpRayQueryGetIntersectionGeometryIndexKHR = 6022, - OpRayQueryGetIntersectionPrimitiveIndexKHR = 6023, - OpRayQueryGetIntersectionBarycentricsKHR = 6024, - OpRayQueryGetIntersectionFrontFaceKHR = 6025, - OpRayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026, - OpRayQueryGetIntersectionObjectRayDirectionKHR = 6027, - OpRayQueryGetIntersectionObjectRayOriginKHR = 6028, - OpRayQueryGetWorldRayDirectionKHR = 6029, - OpRayQueryGetWorldRayOriginKHR = 6030, - OpRayQueryGetIntersectionObjectToWorldKHR = 6031, - OpRayQueryGetIntersectionWorldToObjectKHR = 6032, - OpAtomicFAddEXT = 6035, - OpTypeBufferSurfaceINTEL = 6086, - OpTypeStructContinuedINTEL = 6090, - OpConstantCompositeContinuedINTEL = 6091, - OpSpecConstantCompositeContinuedINTEL = 6092, - OpControlBarrierArriveINTEL = 6142, - OpControlBarrierWaitINTEL = 6143, - OpGroupIMulKHR = 6401, - OpGroupFMulKHR = 6402, - OpGroupBitwiseAndKHR = 6403, - OpGroupBitwiseOrKHR = 6404, - OpGroupBitwiseXorKHR = 6405, - OpGroupLogicalAndKHR = 6406, - OpGroupLogicalOrKHR = 6407, - OpGroupLogicalXorKHR = 6408, - }; - - enum class SpirvOperandKind - { - ImageOperands, - FPFastMathMode, - SelectionControl, - LoopControl, - FunctionControl, - MemorySemantics, - MemoryAccess, - KernelProfilingInfo, - RayFlags, - FragmentShadingRate, - SourceLanguage, - ExecutionModel, - AddressingModel, - MemoryModel, - ExecutionMode, - StorageClass, - Dim, - SamplerAddressingMode, - SamplerFilterMode, - ImageFormat, - ImageChannelOrder, - ImageChannelDataType, - FPRoundingMode, - FPDenormMode, - QuantizationModes, - FPOperationMode, - OverflowModes, - LinkageType, - AccessQualifier, - FunctionParameterAttribute, - Decoration, - BuiltIn, - Scope, - GroupOperation, - KernelEnqueueFlags, - Capability, - RayQueryIntersection, - RayQueryCommittedIntersectionType, - RayQueryCandidateIntersectionType, - PackedVectorFormat, - IdResultType, - IdResult, - IdMemorySemantics, - IdScope, - IdRef, - LiteralInteger, - LiteralString, - LiteralContextDependentNumber, - LiteralExtInstInteger, - LiteralSpecConstantOpInteger, - PairLiteralIntegerIdRef, - PairIdRefLiteralInteger, - PairIdRefIdRef, - }; - - enum class SpirvImageOperands - { - None = 0x0000, - Bias = 0x0001, - Lod = 0x0002, - Grad = 0x0004, - ConstOffset = 0x0008, - Offset = 0x0010, - ConstOffsets = 0x0020, - Sample = 0x0040, - MinLod = 0x0080, - MakeTexelAvailable = 0x0100, - MakeTexelAvailableKHR = 0x0100, - MakeTexelVisible = 0x0200, - MakeTexelVisibleKHR = 0x0200, - NonPrivateTexel = 0x0400, - NonPrivateTexelKHR = 0x0400, - VolatileTexel = 0x0800, - VolatileTexelKHR = 0x0800, - SignExtend = 0x1000, - ZeroExtend = 0x2000, - Nontemporal = 0x4000, - Offsets = 0x10000, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvImageOperands max = SpirvImageOperands::Offsets; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvFPFastMathMode - { - None = 0x0000, - NotNaN = 0x0001, - NotInf = 0x0002, - NSZ = 0x0004, - AllowRecip = 0x0008, - Fast = 0x0010, - AllowContractFastINTEL = 0x10000, - AllowReassocINTEL = 0x20000, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvFPFastMathMode max = SpirvFPFastMathMode::AllowReassocINTEL; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvSelectionControl - { - None = 0x0000, - Flatten = 0x0001, - DontFlatten = 0x0002, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvSelectionControl max = SpirvSelectionControl::DontFlatten; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvLoopControl - { - None = 0x0000, - Unroll = 0x0001, - DontUnroll = 0x0002, - DependencyInfinite = 0x0004, - DependencyLength = 0x0008, - MinIterations = 0x0010, - MaxIterations = 0x0020, - IterationMultiple = 0x0040, - PeelCount = 0x0080, - PartialCount = 0x0100, - InitiationIntervalINTEL = 0x10000, - MaxConcurrencyINTEL = 0x20000, - DependencyArrayINTEL = 0x40000, - PipelineEnableINTEL = 0x80000, - LoopCoalesceINTEL = 0x100000, - MaxInterleavingINTEL = 0x200000, - SpeculatedIterationsINTEL = 0x400000, - NoFusionINTEL = 0x800000, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvLoopControl max = SpirvLoopControl::NoFusionINTEL; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvFunctionControl - { - None = 0x0000, - Inline = 0x0001, - DontInline = 0x0002, - Pure = 0x0004, - Const = 0x0008, - OptNoneINTEL = 0x10000, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvFunctionControl max = SpirvFunctionControl::OptNoneINTEL; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvMemorySemantics - { - Relaxed = 0x0000, - None = 0x0000, - Acquire = 0x0002, - Release = 0x0004, - AcquireRelease = 0x0008, - SequentiallyConsistent = 0x0010, - UniformMemory = 0x0040, - SubgroupMemory = 0x0080, - WorkgroupMemory = 0x0100, - CrossWorkgroupMemory = 0x0200, - AtomicCounterMemory = 0x0400, - ImageMemory = 0x0800, - OutputMemory = 0x1000, - OutputMemoryKHR = 0x1000, - MakeAvailable = 0x2000, - MakeAvailableKHR = 0x2000, - MakeVisible = 0x4000, - MakeVisibleKHR = 0x4000, - Volatile = 0x8000, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvMemorySemantics max = SpirvMemorySemantics::Volatile; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvMemoryAccess - { - None = 0x0000, - Volatile = 0x0001, - Aligned = 0x0002, - Nontemporal = 0x0004, - MakePointerAvailable = 0x0008, - MakePointerAvailableKHR = 0x0008, - MakePointerVisible = 0x0010, - MakePointerVisibleKHR = 0x0010, - NonPrivatePointer = 0x0020, - NonPrivatePointerKHR = 0x0020, - AliasScopeINTELMask = 0x10000, - NoAliasINTELMask = 0x20000, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvMemoryAccess max = SpirvMemoryAccess::NoAliasINTELMask; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvKernelProfilingInfo - { - None = 0x0000, - CmdExecTime = 0x0001, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvKernelProfilingInfo max = SpirvKernelProfilingInfo::CmdExecTime; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvRayFlags - { - NoneKHR = 0x0000, - OpaqueKHR = 0x0001, - NoOpaqueKHR = 0x0002, - TerminateOnFirstHitKHR = 0x0004, - SkipClosestHitShaderKHR = 0x0008, - CullBackFacingTrianglesKHR = 0x0010, - CullFrontFacingTrianglesKHR = 0x0020, - CullOpaqueKHR = 0x0040, - CullNoOpaqueKHR = 0x0080, - SkipTrianglesKHR = 0x0100, - SkipAABBsKHR = 0x0200, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvRayFlags max = SpirvRayFlags::SkipAABBsKHR; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvFragmentShadingRate - { - Vertical2Pixels = 0x0001, - Vertical4Pixels = 0x0002, - Horizontal2Pixels = 0x0004, - Horizontal4Pixels = 0x0008, - }; - - template<> - struct EnumAsFlags - { - static constexpr SpirvFragmentShadingRate max = SpirvFragmentShadingRate::Horizontal4Pixels; - - static constexpr bool AutoFlag = false; - }; - - - enum class SpirvSourceLanguage - { - Unknown = 0, - ESSL = 1, - GLSL = 2, - OpenCL_C = 3, - OpenCL_CPP = 4, - HLSL = 5, - CPP_for_OpenCL = 6, - SYCL = 7, - }; - - enum class SpirvExecutionModel - { - Vertex = 0, - TessellationControl = 1, - TessellationEvaluation = 2, - Geometry = 3, - Fragment = 4, - GLCompute = 5, - Kernel = 6, - TaskNV = 5267, - MeshNV = 5268, - RayGenerationNV = 5313, - RayGenerationKHR = 5313, - IntersectionNV = 5314, - IntersectionKHR = 5314, - AnyHitNV = 5315, - AnyHitKHR = 5315, - ClosestHitNV = 5316, - ClosestHitKHR = 5316, - MissNV = 5317, - MissKHR = 5317, - CallableNV = 5318, - CallableKHR = 5318, - }; - - enum class SpirvAddressingModel - { - Logical = 0, - Physical32 = 1, - Physical64 = 2, - PhysicalStorageBuffer64 = 5348, - PhysicalStorageBuffer64EXT = 5348, - }; - - enum class SpirvMemoryModel - { - Simple = 0, - GLSL450 = 1, - OpenCL = 2, - Vulkan = 3, - VulkanKHR = 3, - }; - - enum class SpirvExecutionMode - { - Invocations = 0, - SpacingEqual = 1, - SpacingFractionalEven = 2, - SpacingFractionalOdd = 3, - VertexOrderCw = 4, - VertexOrderCcw = 5, - PixelCenterInteger = 6, - OriginUpperLeft = 7, - OriginLowerLeft = 8, - EarlyFragmentTests = 9, - PointMode = 10, - Xfb = 11, - DepthReplacing = 12, - DepthGreater = 14, - DepthLess = 15, - DepthUnchanged = 16, - LocalSize = 17, - LocalSizeHint = 18, - InputPoints = 19, - InputLines = 20, - InputLinesAdjacency = 21, - Triangles = 22, - InputTrianglesAdjacency = 23, - Quads = 24, - Isolines = 25, - OutputVertices = 26, - OutputPoints = 27, - OutputLineStrip = 28, - OutputTriangleStrip = 29, - VecTypeHint = 30, - ContractionOff = 31, - Initializer = 33, - Finalizer = 34, - SubgroupSize = 35, - SubgroupsPerWorkgroup = 36, - SubgroupsPerWorkgroupId = 37, - LocalSizeId = 38, - LocalSizeHintId = 39, - SubgroupUniformControlFlowKHR = 4421, - PostDepthCoverage = 4446, - DenormPreserve = 4459, - DenormFlushToZero = 4460, - SignedZeroInfNanPreserve = 4461, - RoundingModeRTE = 4462, - RoundingModeRTZ = 4463, - StencilRefReplacingEXT = 5027, - OutputLinesNV = 5269, - OutputPrimitivesNV = 5270, - DerivativeGroupQuadsNV = 5289, - DerivativeGroupLinearNV = 5290, - OutputTrianglesNV = 5298, - PixelInterlockOrderedEXT = 5366, - PixelInterlockUnorderedEXT = 5367, - SampleInterlockOrderedEXT = 5368, - SampleInterlockUnorderedEXT = 5369, - ShadingRateInterlockOrderedEXT = 5370, - ShadingRateInterlockUnorderedEXT = 5371, - SharedLocalMemorySizeINTEL = 5618, - RoundingModeRTPINTEL = 5620, - RoundingModeRTNINTEL = 5621, - FloatingPointModeALTINTEL = 5622, - FloatingPointModeIEEEINTEL = 5623, - MaxWorkgroupSizeINTEL = 5893, - MaxWorkDimINTEL = 5894, - NoGlobalOffsetINTEL = 5895, - NumSIMDWorkitemsINTEL = 5896, - SchedulerTargetFmaxMhzINTEL = 5903, - NamedBarrierCountINTEL = 6417, - }; - - enum class SpirvStorageClass - { - UniformConstant = 0, - Input = 1, - Uniform = 2, - Output = 3, - Workgroup = 4, - CrossWorkgroup = 5, - Private = 6, - Function = 7, - Generic = 8, - PushConstant = 9, - AtomicCounter = 10, - Image = 11, - StorageBuffer = 12, - CallableDataNV = 5328, - CallableDataKHR = 5328, - IncomingCallableDataNV = 5329, - IncomingCallableDataKHR = 5329, - RayPayloadNV = 5338, - RayPayloadKHR = 5338, - HitAttributeNV = 5339, - HitAttributeKHR = 5339, - IncomingRayPayloadNV = 5342, - IncomingRayPayloadKHR = 5342, - ShaderRecordBufferNV = 5343, - ShaderRecordBufferKHR = 5343, - PhysicalStorageBuffer = 5349, - PhysicalStorageBufferEXT = 5349, - CodeSectionINTEL = 5605, - DeviceOnlyINTEL = 5936, - HostOnlyINTEL = 5937, - }; - - enum class SpirvDim - { - Dim1D = 0, - Dim2D = 1, - Dim3D = 2, - Cube = 3, - Rect = 4, - Buffer = 5, - SubpassData = 6, - }; - - enum class SpirvSamplerAddressingMode - { - None = 0, - ClampToEdge = 1, - Clamp = 2, - Repeat = 3, - RepeatMirrored = 4, - }; - - enum class SpirvSamplerFilterMode - { - Nearest = 0, - Linear = 1, - }; - - enum class SpirvImageFormat - { - Unknown = 0, - Rgba32f = 1, - Rgba16f = 2, - R32f = 3, - Rgba8 = 4, - Rgba8Snorm = 5, - Rg32f = 6, - Rg16f = 7, - R11fG11fB10f = 8, - R16f = 9, - Rgba16 = 10, - Rgb10A2 = 11, - Rg16 = 12, - Rg8 = 13, - R16 = 14, - R8 = 15, - Rgba16Snorm = 16, - Rg16Snorm = 17, - Rg8Snorm = 18, - R16Snorm = 19, - R8Snorm = 20, - Rgba32i = 21, - Rgba16i = 22, - Rgba8i = 23, - R32i = 24, - Rg32i = 25, - Rg16i = 26, - Rg8i = 27, - R16i = 28, - R8i = 29, - Rgba32ui = 30, - Rgba16ui = 31, - Rgba8ui = 32, - R32ui = 33, - Rgb10a2ui = 34, - Rg32ui = 35, - Rg16ui = 36, - Rg8ui = 37, - R16ui = 38, - R8ui = 39, - R64ui = 40, - R64i = 41, - }; - - enum class SpirvImageChannelOrder - { - R = 0, - A = 1, - RG = 2, - RA = 3, - RGB = 4, - RGBA = 5, - BGRA = 6, - ARGB = 7, - Intensity = 8, - Luminance = 9, - Rx = 10, - RGx = 11, - RGBx = 12, - Depth = 13, - DepthStencil = 14, - sRGB = 15, - sRGBx = 16, - sRGBA = 17, - sBGRA = 18, - ABGR = 19, - }; - - enum class SpirvImageChannelDataType - { - SnormInt8 = 0, - SnormInt16 = 1, - UnormInt8 = 2, - UnormInt16 = 3, - UnormShort565 = 4, - UnormShort555 = 5, - UnormInt101010 = 6, - SignedInt8 = 7, - SignedInt16 = 8, - SignedInt32 = 9, - UnsignedInt8 = 10, - UnsignedInt16 = 11, - UnsignedInt32 = 12, - HalfFloat = 13, - Float = 14, - UnormInt24 = 15, - UnormInt101010_2 = 16, - }; - - enum class SpirvFPRoundingMode - { - RTE = 0, - RTZ = 1, - RTP = 2, - RTN = 3, - }; - - enum class SpirvFPDenormMode - { - Preserve = 0, - FlushToZero = 1, - }; - - enum class SpirvQuantizationModes - { - TRN = 0, - TRN_ZERO = 1, - RND = 2, - RND_ZERO = 3, - RND_INF = 4, - RND_MIN_INF = 5, - RND_CONV = 6, - RND_CONV_ODD = 7, - }; - - enum class SpirvFPOperationMode - { - IEEE = 0, - ALT = 1, - }; - - enum class SpirvOverflowModes - { - WRAP = 0, - SAT = 1, - SAT_ZERO = 2, - SAT_SYM = 3, - }; - - enum class SpirvLinkageType - { - Export = 0, - Import = 1, - LinkOnceODR = 2, - }; - - enum class SpirvAccessQualifier - { - ReadOnly = 0, - WriteOnly = 1, - ReadWrite = 2, - }; - - enum class SpirvFunctionParameterAttribute - { - Zext = 0, - Sext = 1, - ByVal = 2, - Sret = 3, - NoAlias = 4, - NoCapture = 5, - NoWrite = 6, - NoReadWrite = 7, - }; - - enum class SpirvDecoration - { - RelaxedPrecision = 0, - SpecId = 1, - Block = 2, - BufferBlock = 3, - RowMajor = 4, - ColMajor = 5, - ArrayStride = 6, - MatrixStride = 7, - GLSLShared = 8, - GLSLPacked = 9, - CPacked = 10, - BuiltIn = 11, - NoPerspective = 13, - Flat = 14, - Patch = 15, - Centroid = 16, - Sample = 17, - Invariant = 18, - Restrict = 19, - Aliased = 20, - Volatile = 21, - Constant = 22, - Coherent = 23, - NonWritable = 24, - NonReadable = 25, - Uniform = 26, - UniformId = 27, - SaturatedConversion = 28, - Stream = 29, - Location = 30, - Component = 31, - Index = 32, - Binding = 33, - DescriptorSet = 34, - Offset = 35, - XfbBuffer = 36, - XfbStride = 37, - FuncParamAttr = 38, - FPRoundingMode = 39, - FPFastMathMode = 40, - LinkageAttributes = 41, - NoContraction = 42, - InputAttachmentIndex = 43, - Alignment = 44, - MaxByteOffset = 45, - AlignmentId = 46, - MaxByteOffsetId = 47, - NoSignedWrap = 4469, - NoUnsignedWrap = 4470, - ExplicitInterpAMD = 4999, - OverrideCoverageNV = 5248, - PassthroughNV = 5250, - ViewportRelativeNV = 5252, - SecondaryViewportRelativeNV = 5256, - PerPrimitiveNV = 5271, - PerViewNV = 5272, - PerTaskNV = 5273, - PerVertexKHR = 5285, - PerVertexNV = 5285, - NonUniform = 5300, - NonUniformEXT = 5300, - RestrictPointer = 5355, - RestrictPointerEXT = 5355, - AliasedPointer = 5356, - AliasedPointerEXT = 5356, - BindlessSamplerNV = 5398, - BindlessImageNV = 5399, - BoundSamplerNV = 5400, - BoundImageNV = 5401, - SIMTCallINTEL = 5599, - ReferencedIndirectlyINTEL = 5602, - ClobberINTEL = 5607, - SideEffectsINTEL = 5608, - VectorComputeVariableINTEL = 5624, - FuncParamIOKindINTEL = 5625, - VectorComputeFunctionINTEL = 5626, - StackCallINTEL = 5627, - GlobalVariableOffsetINTEL = 5628, - CounterBuffer = 5634, - HlslCounterBufferGOOGLE = 5634, - UserSemantic = 5635, - HlslSemanticGOOGLE = 5635, - UserTypeGOOGLE = 5636, - FunctionRoundingModeINTEL = 5822, - FunctionDenormModeINTEL = 5823, - RegisterINTEL = 5825, - MemoryINTEL = 5826, - NumbanksINTEL = 5827, - BankwidthINTEL = 5828, - MaxPrivateCopiesINTEL = 5829, - SinglepumpINTEL = 5830, - DoublepumpINTEL = 5831, - MaxReplicatesINTEL = 5832, - SimpleDualPortINTEL = 5833, - MergeINTEL = 5834, - BankBitsINTEL = 5835, - ForcePow2DepthINTEL = 5836, - BurstCoalesceINTEL = 5899, - CacheSizeINTEL = 5900, - DontStaticallyCoalesceINTEL = 5901, - PrefetchINTEL = 5902, - StallEnableINTEL = 5905, - FuseLoopsInFunctionINTEL = 5907, - AliasScopeINTEL = 5914, - NoAliasINTEL = 5915, - BufferLocationINTEL = 5921, - IOPipeStorageINTEL = 5944, - FunctionFloatingPointModeINTEL = 6080, - SingleElementVectorINTEL = 6085, - VectorComputeCallableFunctionINTEL = 6087, - MediaBlockIOINTEL = 6140, - }; - - enum class SpirvBuiltIn - { - Position = 0, - PointSize = 1, - ClipDistance = 3, - CullDistance = 4, - VertexId = 5, - InstanceId = 6, - PrimitiveId = 7, - InvocationId = 8, - Layer = 9, - ViewportIndex = 10, - TessLevelOuter = 11, - TessLevelInner = 12, - TessCoord = 13, - PatchVertices = 14, - FragCoord = 15, - PointCoord = 16, - FrontFacing = 17, - SampleId = 18, - SamplePosition = 19, - SampleMask = 20, - FragDepth = 22, - HelperInvocation = 23, - NumWorkgroups = 24, - WorkgroupSize = 25, - WorkgroupId = 26, - LocalInvocationId = 27, - GlobalInvocationId = 28, - LocalInvocationIndex = 29, - WorkDim = 30, - GlobalSize = 31, - EnqueuedWorkgroupSize = 32, - GlobalOffset = 33, - GlobalLinearId = 34, - SubgroupSize = 36, - SubgroupMaxSize = 37, - NumSubgroups = 38, - NumEnqueuedSubgroups = 39, - SubgroupId = 40, - SubgroupLocalInvocationId = 41, - VertexIndex = 42, - InstanceIndex = 43, - SubgroupEqMask = 4416, - SubgroupEqMaskKHR = 4416, - SubgroupGeMask = 4417, - SubgroupGeMaskKHR = 4417, - SubgroupGtMask = 4418, - SubgroupGtMaskKHR = 4418, - SubgroupLeMask = 4419, - SubgroupLeMaskKHR = 4419, - SubgroupLtMask = 4420, - SubgroupLtMaskKHR = 4420, - BaseVertex = 4424, - BaseInstance = 4425, - DrawIndex = 4426, - PrimitiveShadingRateKHR = 4432, - DeviceIndex = 4438, - ViewIndex = 4440, - ShadingRateKHR = 4444, - BaryCoordNoPerspAMD = 4992, - BaryCoordNoPerspCentroidAMD = 4993, - BaryCoordNoPerspSampleAMD = 4994, - BaryCoordSmoothAMD = 4995, - BaryCoordSmoothCentroidAMD = 4996, - BaryCoordSmoothSampleAMD = 4997, - BaryCoordPullModelAMD = 4998, - FragStencilRefEXT = 5014, - ViewportMaskNV = 5253, - SecondaryPositionNV = 5257, - SecondaryViewportMaskNV = 5258, - PositionPerViewNV = 5261, - ViewportMaskPerViewNV = 5262, - FullyCoveredEXT = 5264, - TaskCountNV = 5274, - PrimitiveCountNV = 5275, - PrimitiveIndicesNV = 5276, - ClipDistancePerViewNV = 5277, - CullDistancePerViewNV = 5278, - LayerPerViewNV = 5279, - MeshViewCountNV = 5280, - MeshViewIndicesNV = 5281, - BaryCoordKHR = 5286, - BaryCoordNV = 5286, - BaryCoordNoPerspKHR = 5287, - BaryCoordNoPerspNV = 5287, - FragSizeEXT = 5292, - FragmentSizeNV = 5292, - FragInvocationCountEXT = 5293, - InvocationsPerPixelNV = 5293, - LaunchIdNV = 5319, - LaunchIdKHR = 5319, - LaunchSizeNV = 5320, - LaunchSizeKHR = 5320, - WorldRayOriginNV = 5321, - WorldRayOriginKHR = 5321, - WorldRayDirectionNV = 5322, - WorldRayDirectionKHR = 5322, - ObjectRayOriginNV = 5323, - ObjectRayOriginKHR = 5323, - ObjectRayDirectionNV = 5324, - ObjectRayDirectionKHR = 5324, - RayTminNV = 5325, - RayTminKHR = 5325, - RayTmaxNV = 5326, - RayTmaxKHR = 5326, - InstanceCustomIndexNV = 5327, - InstanceCustomIndexKHR = 5327, - ObjectToWorldNV = 5330, - ObjectToWorldKHR = 5330, - WorldToObjectNV = 5331, - WorldToObjectKHR = 5331, - HitTNV = 5332, - HitKindNV = 5333, - HitKindKHR = 5333, - CurrentRayTimeNV = 5334, - IncomingRayFlagsNV = 5351, - IncomingRayFlagsKHR = 5351, - RayGeometryIndexKHR = 5352, - WarpsPerSMNV = 5374, - SMCountNV = 5375, - WarpIDNV = 5376, - SMIDNV = 5377, - CullMaskKHR = 6021, - }; - - enum class SpirvScope - { - CrossDevice = 0, - Device = 1, - Workgroup = 2, - Subgroup = 3, - Invocation = 4, - QueueFamily = 5, - QueueFamilyKHR = 5, - ShaderCallKHR = 6, - }; - - enum class SpirvGroupOperation - { - Reduce = 0, - InclusiveScan = 1, - ExclusiveScan = 2, - ClusteredReduce = 3, - PartitionedReduceNV = 6, - PartitionedInclusiveScanNV = 7, - PartitionedExclusiveScanNV = 8, - }; - - enum class SpirvKernelEnqueueFlags - { - NoWait = 0, - WaitKernel = 1, - WaitWorkGroup = 2, - }; - - enum class SpirvCapability - { - Matrix = 0, - Shader = 1, - Geometry = 2, - Tessellation = 3, - Addresses = 4, - Linkage = 5, - Kernel = 6, - Vector16 = 7, - Float16Buffer = 8, - Float16 = 9, - Float64 = 10, - Int64 = 11, - Int64Atomics = 12, - ImageBasic = 13, - ImageReadWrite = 14, - ImageMipmap = 15, - Pipes = 17, - Groups = 18, - DeviceEnqueue = 19, - LiteralSampler = 20, - AtomicStorage = 21, - Int16 = 22, - TessellationPointSize = 23, - GeometryPointSize = 24, - ImageGatherExtended = 25, - StorageImageMultisample = 27, - UniformBufferArrayDynamicIndexing = 28, - SampledImageArrayDynamicIndexing = 29, - StorageBufferArrayDynamicIndexing = 30, - StorageImageArrayDynamicIndexing = 31, - ClipDistance = 32, - CullDistance = 33, - ImageCubeArray = 34, - SampleRateShading = 35, - ImageRect = 36, - SampledRect = 37, - GenericPointer = 38, - Int8 = 39, - InputAttachment = 40, - SparseResidency = 41, - MinLod = 42, - Sampled1D = 43, - Image1D = 44, - SampledCubeArray = 45, - SampledBuffer = 46, - ImageBuffer = 47, - ImageMSArray = 48, - StorageImageExtendedFormats = 49, - ImageQuery = 50, - DerivativeControl = 51, - InterpolationFunction = 52, - TransformFeedback = 53, - GeometryStreams = 54, - StorageImageReadWithoutFormat = 55, - StorageImageWriteWithoutFormat = 56, - MultiViewport = 57, - SubgroupDispatch = 58, - NamedBarrier = 59, - PipeStorage = 60, - GroupNonUniform = 61, - GroupNonUniformVote = 62, - GroupNonUniformArithmetic = 63, - GroupNonUniformBallot = 64, - GroupNonUniformShuffle = 65, - GroupNonUniformShuffleRelative = 66, - GroupNonUniformClustered = 67, - GroupNonUniformQuad = 68, - ShaderLayer = 69, - ShaderViewportIndex = 70, - UniformDecoration = 71, - FragmentShadingRateKHR = 4422, - SubgroupBallotKHR = 4423, - DrawParameters = 4427, - WorkgroupMemoryExplicitLayoutKHR = 4428, - WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, - WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, - SubgroupVoteKHR = 4431, - StorageBuffer16BitAccess = 4433, - StorageUniformBufferBlock16 = 4433, - UniformAndStorageBuffer16BitAccess = 4434, - StorageUniform16 = 4434, - StoragePushConstant16 = 4435, - StorageInputOutput16 = 4436, - DeviceGroup = 4437, - MultiView = 4439, - VariablePointersStorageBuffer = 4441, - VariablePointers = 4442, - AtomicStorageOps = 4445, - SampleMaskPostDepthCoverage = 4447, - StorageBuffer8BitAccess = 4448, - UniformAndStorageBuffer8BitAccess = 4449, - StoragePushConstant8 = 4450, - DenormPreserve = 4464, - DenormFlushToZero = 4465, - SignedZeroInfNanPreserve = 4466, - RoundingModeRTE = 4467, - RoundingModeRTZ = 4468, - RayQueryProvisionalKHR = 4471, - RayQueryKHR = 4472, - RayTraversalPrimitiveCullingKHR = 4478, - RayTracingKHR = 4479, - Float16ImageAMD = 5008, - ImageGatherBiasLodAMD = 5009, - FragmentMaskAMD = 5010, - StencilExportEXT = 5013, - ImageReadWriteLodAMD = 5015, - Int64ImageEXT = 5016, - ShaderClockKHR = 5055, - SampleMaskOverrideCoverageNV = 5249, - GeometryShaderPassthroughNV = 5251, - ShaderViewportIndexLayerEXT = 5254, - ShaderViewportIndexLayerNV = 5254, - ShaderViewportMaskNV = 5255, - ShaderStereoViewNV = 5259, - PerViewAttributesNV = 5260, - FragmentFullyCoveredEXT = 5265, - MeshShadingNV = 5266, - ImageFootprintNV = 5282, - FragmentBarycentricKHR = 5284, - FragmentBarycentricNV = 5284, - ComputeDerivativeGroupQuadsNV = 5288, - FragmentDensityEXT = 5291, - ShadingRateNV = 5291, - GroupNonUniformPartitionedNV = 5297, - ShaderNonUniform = 5301, - ShaderNonUniformEXT = 5301, - RuntimeDescriptorArray = 5302, - RuntimeDescriptorArrayEXT = 5302, - InputAttachmentArrayDynamicIndexing = 5303, - InputAttachmentArrayDynamicIndexingEXT = 5303, - UniformTexelBufferArrayDynamicIndexing = 5304, - UniformTexelBufferArrayDynamicIndexingEXT = 5304, - StorageTexelBufferArrayDynamicIndexing = 5305, - StorageTexelBufferArrayDynamicIndexingEXT = 5305, - UniformBufferArrayNonUniformIndexing = 5306, - UniformBufferArrayNonUniformIndexingEXT = 5306, - SampledImageArrayNonUniformIndexing = 5307, - SampledImageArrayNonUniformIndexingEXT = 5307, - StorageBufferArrayNonUniformIndexing = 5308, - StorageBufferArrayNonUniformIndexingEXT = 5308, - StorageImageArrayNonUniformIndexing = 5309, - StorageImageArrayNonUniformIndexingEXT = 5309, - InputAttachmentArrayNonUniformIndexing = 5310, - InputAttachmentArrayNonUniformIndexingEXT = 5310, - UniformTexelBufferArrayNonUniformIndexing = 5311, - UniformTexelBufferArrayNonUniformIndexingEXT = 5311, - StorageTexelBufferArrayNonUniformIndexing = 5312, - StorageTexelBufferArrayNonUniformIndexingEXT = 5312, - RayTracingNV = 5340, - RayTracingMotionBlurNV = 5341, - VulkanMemoryModel = 5345, - VulkanMemoryModelKHR = 5345, - VulkanMemoryModelDeviceScope = 5346, - VulkanMemoryModelDeviceScopeKHR = 5346, - PhysicalStorageBufferAddresses = 5347, - PhysicalStorageBufferAddressesEXT = 5347, - ComputeDerivativeGroupLinearNV = 5350, - RayTracingProvisionalKHR = 5353, - CooperativeMatrixNV = 5357, - FragmentShaderSampleInterlockEXT = 5363, - FragmentShaderShadingRateInterlockEXT = 5372, - ShaderSMBuiltinsNV = 5373, - FragmentShaderPixelInterlockEXT = 5378, - DemoteToHelperInvocation = 5379, - DemoteToHelperInvocationEXT = 5379, - BindlessTextureNV = 5390, - SubgroupShuffleINTEL = 5568, - SubgroupBufferBlockIOINTEL = 5569, - SubgroupImageBlockIOINTEL = 5570, - SubgroupImageMediaBlockIOINTEL = 5579, - RoundToInfinityINTEL = 5582, - FloatingPointModeINTEL = 5583, - IntegerFunctions2INTEL = 5584, - FunctionPointersINTEL = 5603, - IndirectReferencesINTEL = 5604, - AsmINTEL = 5606, - AtomicFloat32MinMaxEXT = 5612, - AtomicFloat64MinMaxEXT = 5613, - AtomicFloat16MinMaxEXT = 5616, - VectorComputeINTEL = 5617, - VectorAnyINTEL = 5619, - ExpectAssumeKHR = 5629, - SubgroupAvcMotionEstimationINTEL = 5696, - SubgroupAvcMotionEstimationIntraINTEL = 5697, - SubgroupAvcMotionEstimationChromaINTEL = 5698, - VariableLengthArrayINTEL = 5817, - FunctionFloatControlINTEL = 5821, - FPGAMemoryAttributesINTEL = 5824, - FPFastMathModeINTEL = 5837, - ArbitraryPrecisionIntegersINTEL = 5844, - ArbitraryPrecisionFloatingPointINTEL = 5845, - UnstructuredLoopControlsINTEL = 5886, - FPGALoopControlsINTEL = 5888, - KernelAttributesINTEL = 5892, - FPGAKernelAttributesINTEL = 5897, - FPGAMemoryAccessesINTEL = 5898, - FPGAClusterAttributesINTEL = 5904, - LoopFuseINTEL = 5906, - MemoryAccessAliasingINTEL = 5910, - FPGABufferLocationINTEL = 5920, - ArbitraryPrecisionFixedPointINTEL = 5922, - USMStorageClassesINTEL = 5935, - IOPipesINTEL = 5943, - BlockingPipesINTEL = 5945, - FPGARegINTEL = 5948, - DotProductInputAll = 6016, - DotProductInputAllKHR = 6016, - DotProductInput4x8Bit = 6017, - DotProductInput4x8BitKHR = 6017, - DotProductInput4x8BitPacked = 6018, - DotProductInput4x8BitPackedKHR = 6018, - DotProduct = 6019, - DotProductKHR = 6019, - RayCullMaskKHR = 6020, - BitInstructions = 6025, - GroupNonUniformRotateKHR = 6026, - AtomicFloat32AddEXT = 6033, - AtomicFloat64AddEXT = 6034, - LongConstantCompositeINTEL = 6089, - OptNoneINTEL = 6094, - AtomicFloat16AddEXT = 6095, - DebugInfoModuleINTEL = 6114, - SplitBarrierINTEL = 6141, - GroupUniformArithmeticKHR = 6400, - }; - - enum class SpirvRayQueryIntersection - { - RayQueryCandidateIntersectionKHR = 0, - RayQueryCommittedIntersectionKHR = 1, - }; - - enum class SpirvRayQueryCommittedIntersectionType - { - RayQueryCommittedIntersectionNoneKHR = 0, - RayQueryCommittedIntersectionTriangleKHR = 1, - RayQueryCommittedIntersectionGeneratedKHR = 2, - }; - - enum class SpirvRayQueryCandidateIntersectionType - { - RayQueryCandidateIntersectionTriangleKHR = 0, - RayQueryCandidateIntersectionAABBKHR = 1, - }; - - enum class SpirvPackedVectorFormat - { - PackedVectorFormat4x8Bit = 0, - PackedVectorFormat4x8BitKHR = 0, - }; - - struct SpirvInstruction - { - struct Operand - { - SpirvOperandKind kind; - const char* name; - }; - - SpirvOp op; - const char* name; - const Operand* operands; - const Operand* resultOperand; - std::size_t minOperandCount; - }; - - NAZARA_SHADER_API const SpirvInstruction* GetInstructionData(UInt16 op); -} - -#endif // NAZARA_SHADER_SPIRVDATA_HPP diff --git a/include/Nazara/Shader/SpirvDecoder.hpp b/include/Nazara/Shader/SpirvDecoder.hpp deleted file mode 100644 index 1bbd5449c..000000000 --- a/include/Nazara/Shader/SpirvDecoder.hpp +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVDECODER_HPP -#define NAZARA_SHADER_SPIRVDECODER_HPP - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API SpirvDecoder - { - public: - SpirvDecoder() = default; - SpirvDecoder(const SpirvDecoder&) = default; - SpirvDecoder(SpirvDecoder&&) = default; - ~SpirvDecoder() = default; - - void Decode(const UInt32* codepoints, std::size_t count); - - SpirvDecoder& operator=(const SpirvDecoder&) = default; - SpirvDecoder& operator=(SpirvDecoder&&) = default; - - protected: - struct SpirvHeader; - - inline const UInt32* GetCurrentPtr() const; - - virtual bool HandleHeader(const SpirvHeader& header); - virtual bool HandleOpcode(const SpirvInstruction& instruction, UInt32 wordCount) = 0; - - std::string ReadString(); - UInt32 ReadWord(); - - struct SpirvHeader - { - UInt32 generatorId; - UInt32 bound; - UInt32 schema; - UInt32 versionNumber; - }; - - private: - const UInt32* m_currentCodepoint; - const UInt32* m_codepointEnd; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVDECODER_HPP diff --git a/include/Nazara/Shader/SpirvDecoder.inl b/include/Nazara/Shader/SpirvDecoder.inl deleted file mode 100644 index eb738933c..000000000 --- a/include/Nazara/Shader/SpirvDecoder.inl +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline const UInt32* SpirvDecoder::GetCurrentPtr() const - { - return m_currentCodepoint; - } -} - -#include diff --git a/include/Nazara/Shader/SpirvExpressionLoad.hpp b/include/Nazara/Shader/SpirvExpressionLoad.hpp deleted file mode 100644 index bd1a1b205..000000000 --- a/include/Nazara/Shader/SpirvExpressionLoad.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVEXPRESSIONLOAD_HPP -#define NAZARA_SHADER_SPIRVEXPRESSIONLOAD_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - class SpirvAstVisitor; - class SpirvBlock; - class SpirvWriter; - - class NAZARA_SHADER_API SpirvExpressionLoad : public ShaderAst::AstExpressionVisitorExcept - { - public: - inline SpirvExpressionLoad(SpirvWriter& writer, SpirvAstVisitor& visitor, SpirvBlock& block); - SpirvExpressionLoad(const SpirvExpressionLoad&) = delete; - SpirvExpressionLoad(SpirvExpressionLoad&&) = delete; - ~SpirvExpressionLoad() = default; - - UInt32 Evaluate(ShaderAst::Expression& node); - - using AstExpressionVisitorExcept::Visit; - void Visit(ShaderAst::AccessIndexExpression& node) override; - void Visit(ShaderAst::VariableValueExpression& node) override; - - SpirvExpressionLoad& operator=(const SpirvExpressionLoad&) = delete; - SpirvExpressionLoad& operator=(SpirvExpressionLoad&&) = delete; - - private: - struct PointerChainAccess - { - std::vector indices; - const ShaderAst::ExpressionType* exprType; - SpirvStorageClass storage; - UInt32 pointerId; - UInt32 pointedTypeId; - }; - - struct Pointer - { - SpirvStorageClass storage; - UInt32 pointerId; - UInt32 pointedTypeId; - }; - - struct Value - { - UInt32 valueId; - }; - - struct ValueExtraction - { - std::vector indices; - UInt32 typeId; - UInt32 valueId; - }; - - SpirvAstVisitor& m_visitor; - SpirvBlock& m_block; - SpirvWriter& m_writer; - std::variant m_value; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVEXPRESSIONLOAD_HPP diff --git a/include/Nazara/Shader/SpirvExpressionLoad.inl b/include/Nazara/Shader/SpirvExpressionLoad.inl deleted file mode 100644 index f545d2623..000000000 --- a/include/Nazara/Shader/SpirvExpressionLoad.inl +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline SpirvExpressionLoad::SpirvExpressionLoad(SpirvWriter& writer, SpirvAstVisitor& visitor, SpirvBlock& block) : - m_visitor(visitor), - m_block(block), - m_writer(writer) - { - } -} - -#include diff --git a/include/Nazara/Shader/SpirvExpressionStore.hpp b/include/Nazara/Shader/SpirvExpressionStore.hpp deleted file mode 100644 index a052e0ecd..000000000 --- a/include/Nazara/Shader/SpirvExpressionStore.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVEXPRESSIONSTORE_HPP -#define NAZARA_SHADER_SPIRVEXPRESSIONSTORE_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - class SpirvAstVisitor; - class SpirvBlock; - class SpirvWriter; - - class NAZARA_SHADER_API SpirvExpressionStore : public ShaderAst::AstExpressionVisitorExcept - { - public: - inline SpirvExpressionStore(SpirvWriter& writer, SpirvAstVisitor& visitor, SpirvBlock& block); - SpirvExpressionStore(const SpirvExpressionStore&) = delete; - SpirvExpressionStore(SpirvExpressionStore&&) = delete; - ~SpirvExpressionStore() = default; - - void Store(ShaderAst::ExpressionPtr& node, UInt32 resultId); - - using AstExpressionVisitorExcept::Visit; - void Visit(ShaderAst::AccessIndexExpression& node) override; - void Visit(ShaderAst::SwizzleExpression& node) override; - void Visit(ShaderAst::VariableValueExpression& node) override; - - SpirvExpressionStore& operator=(const SpirvExpressionStore&) = delete; - SpirvExpressionStore& operator=(SpirvExpressionStore&&) = delete; - - private: - struct Pointer - { - SpirvStorageClass storage; - UInt32 pointerId; - }; - - struct SwizzledPointer : Pointer - { - ShaderAst::VectorType swizzledType; - std::array swizzleIndices; - std::size_t componentCount; - }; - - SpirvAstVisitor& m_visitor; - SpirvBlock& m_block; - SpirvWriter& m_writer; - std::variant m_value; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVEXPRESSIONSTORE_HPP diff --git a/include/Nazara/Shader/SpirvExpressionStore.inl b/include/Nazara/Shader/SpirvExpressionStore.inl deleted file mode 100644 index d370b460c..000000000 --- a/include/Nazara/Shader/SpirvExpressionStore.inl +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline SpirvExpressionStore::SpirvExpressionStore(SpirvWriter& writer, SpirvAstVisitor& visitor, SpirvBlock& block) : - m_visitor(visitor), - m_block(block), - m_writer(writer) - { - } -} - -#include diff --git a/include/Nazara/Shader/SpirvPrinter.hpp b/include/Nazara/Shader/SpirvPrinter.hpp deleted file mode 100644 index 4979fc30a..000000000 --- a/include/Nazara/Shader/SpirvPrinter.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVPRINTER_HPP -#define NAZARA_SHADER_SPIRVPRINTER_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API SpirvPrinter : SpirvDecoder - { - public: - struct Settings; - - inline SpirvPrinter(); - SpirvPrinter(const SpirvPrinter&) = default; - SpirvPrinter(SpirvPrinter&&) = default; - ~SpirvPrinter() = default; - - inline std::string Print(const std::vector& codepoints); - inline std::string Print(const UInt32* codepoints, std::size_t count); - inline std::string Print(const std::vector& codepoints, const Settings& settings); - std::string Print(const UInt32* codepoints, std::size_t count, const Settings& settings); - - SpirvPrinter& operator=(const SpirvPrinter&) = default; - SpirvPrinter& operator=(SpirvPrinter&&) = default; - - struct Settings - { - bool printHeader = true; - bool printParameters = true; - }; - - private: - bool HandleHeader(const SpirvHeader& header) override; - bool HandleOpcode(const SpirvInstruction& instruction, UInt32 wordCount) override; - - struct State; - - State* m_currentState; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVPRINTER_HPP diff --git a/include/Nazara/Shader/SpirvPrinter.inl b/include/Nazara/Shader/SpirvPrinter.inl deleted file mode 100644 index 053e33037..000000000 --- a/include/Nazara/Shader/SpirvPrinter.inl +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline SpirvPrinter::SpirvPrinter() : - m_currentState(nullptr) - { - } - - inline std::string SpirvPrinter::Print(const std::vector& codepoints) - { - return Print(codepoints.data(), codepoints.size()); - } - - inline std::string SpirvPrinter::Print(const UInt32* codepoints, std::size_t count) - { - Settings settings; - return Print(codepoints, count, settings); - } - - inline std::string SpirvPrinter::Print(const std::vector& codepoints, const Settings& settings) - { - return Print(codepoints.data(), codepoints.size(), settings); - } -} - -#include diff --git a/include/Nazara/Shader/SpirvSection.hpp b/include/Nazara/Shader/SpirvSection.hpp deleted file mode 100644 index 928198b94..000000000 --- a/include/Nazara/Shader/SpirvSection.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVSECTION_HPP -#define NAZARA_SHADER_SPIRVSECTION_HPP - -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API SpirvSection : public SpirvSectionBase - { - public: - SpirvSection() = default; - SpirvSection(const SpirvSection&) = default; - SpirvSection(SpirvSection&&) = default; - ~SpirvSection() = default; - - using SpirvSectionBase::Append; - using SpirvSectionBase::AppendRaw; - using SpirvSectionBase::AppendSection; - using SpirvSectionBase::AppendVariadic; - - SpirvSection& operator=(const SpirvSection&) = delete; - SpirvSection& operator=(SpirvSection&&) = default; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVSECTION_HPP diff --git a/include/Nazara/Shader/SpirvSection.inl b/include/Nazara/Shader/SpirvSection.inl deleted file mode 100644 index 80220f74b..000000000 --- a/include/Nazara/Shader/SpirvSection.inl +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Shader/SpirvSectionBase.hpp b/include/Nazara/Shader/SpirvSectionBase.hpp deleted file mode 100644 index f5491d9ff..000000000 --- a/include/Nazara/Shader/SpirvSectionBase.hpp +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVSECTIONBASE_HPP -#define NAZARA_SHADER_SPIRVSECTIONBASE_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - class NAZARA_SHADER_API SpirvSectionBase - { - public: - struct OpSize; - struct Raw; - - SpirvSectionBase() = default; - SpirvSectionBase(const SpirvSectionBase&) = default; - SpirvSectionBase(SpirvSectionBase&&) = default; - ~SpirvSectionBase() = default; - - inline const std::vector& GetBytecode() const; - inline std::size_t GetOutputOffset() const; - - SpirvSectionBase& operator=(const SpirvSectionBase&) = delete; - SpirvSectionBase& operator=(SpirvSectionBase&&) = default; - - struct OpSize - { - unsigned int wc; - }; - - struct Raw - { - const void* ptr; - std::size_t size; - }; - - static inline UInt32 BuildOpcode(SpirvOp opcode, unsigned int wordCount); - - protected: - inline std::size_t Append(SpirvOp opcode, const OpSize& wordCount); - template std::size_t Append(SpirvOp opcode, const Args&... args); - template std::size_t AppendVariadic(SpirvOp opcode, F&& callback); - inline std::size_t AppendRaw(const char* str); - inline std::size_t AppendRaw(const std::string_view& str); - inline std::size_t AppendRaw(const std::string& str); - inline std::size_t AppendRaw(UInt32 value); - std::size_t AppendRaw(const Raw& raw); - inline std::size_t AppendRaw(std::initializer_list codepoints); - inline std::size_t AppendSection(const SpirvSectionBase& section); - template || std::is_enum_v>> std::size_t AppendRaw(T value); - - inline unsigned int CountWord(const char* str); - inline unsigned int CountWord(const std::string_view& str); - inline unsigned int CountWord(const std::string& str); - inline unsigned int CountWord(const Raw& raw); - template || std::is_enum_v>> unsigned int CountWord(const T& value); - template unsigned int CountWord(const T1& value, const T2& value2, const Args&... rest); - - private: - std::vector m_bytecode; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVSECTIONBASE_HPP diff --git a/include/Nazara/Shader/SpirvSectionBase.inl b/include/Nazara/Shader/SpirvSectionBase.inl deleted file mode 100644 index 3d055aa82..000000000 --- a/include/Nazara/Shader/SpirvSectionBase.inl +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - inline std::size_t SpirvSectionBase::Append(SpirvOp opcode, const OpSize& wordCount) - { - return AppendRaw(BuildOpcode(opcode, wordCount.wc)); - } - - template - std::size_t SpirvSectionBase::Append(SpirvOp opcode, const Args&... args) - { - unsigned int wordCount = 1 + (CountWord(args) + ... + 0); - std::size_t offset = Append(opcode, OpSize{ wordCount }); - if constexpr (sizeof...(args) > 0) - (AppendRaw(args), ...); - - return offset; - } - - template std::size_t SpirvSectionBase::AppendVariadic(SpirvOp opcode, F&& callback) - { - std::size_t offset = AppendRaw(0); //< Will be filled later - - unsigned int wordCount = 1; - auto appendFunctor = [&](const auto& value) - { - wordCount += CountWord(value); - AppendRaw(value); - }; - callback(appendFunctor); - - m_bytecode[offset] = BuildOpcode(opcode, wordCount); - - return offset; - } - - inline std::size_t SpirvSectionBase::AppendRaw(const char* str) - { - return AppendRaw(std::string_view(str)); - } - - inline std::size_t SpirvSectionBase::AppendRaw(const std::string_view& str) - { - std::size_t offset = GetOutputOffset(); - - std::size_t size4 = CountWord(str); - for (std::size_t i = 0; i < size4; ++i) - { - UInt32 codepoint = 0; - for (std::size_t j = 0; j < 4; ++j) - { - std::size_t pos = i * 4 + j; - if (pos < str.size()) - codepoint |= UInt32(str[pos]) << (j * 8); - } - - AppendRaw(codepoint); - } - - return offset; - } - - inline std::size_t SpirvSectionBase::AppendRaw(const std::string& str) - { - return AppendRaw(std::string_view(str)); - } - - inline std::size_t SpirvSectionBase::AppendRaw(UInt32 value) - { - std::size_t offset = GetOutputOffset(); - m_bytecode.push_back(value); - - return offset; - } - - inline std::size_t SpirvSectionBase::AppendRaw(std::initializer_list codepoints) - { - std::size_t offset = GetOutputOffset(); - - for (UInt32 cp : codepoints) - AppendRaw(cp); - - return offset; - } - - inline std::size_t SpirvSectionBase::AppendSection(const SpirvSectionBase& section) - { - const std::vector& bytecode = section.GetBytecode(); - - std::size_t offset = GetOutputOffset(); - m_bytecode.resize(offset + bytecode.size()); - std::copy(bytecode.begin(), bytecode.end(), m_bytecode.begin() + offset); - - return offset; - } - - template - std::size_t SpirvSectionBase::AppendRaw(T value) - { - return AppendRaw(static_cast(value)); - } - - template - unsigned int SpirvSectionBase::CountWord(const T& /*value*/) - { - return 1; - } - - template - unsigned int SpirvSectionBase::CountWord(const T1& value, const T2& value2, const Args&... rest) - { - return CountWord(value) + CountWord(value2) + (CountWord(rest) + ...); - } - - inline unsigned int SpirvSectionBase::CountWord(const char* str) - { - return CountWord(std::string_view(str)); - } - - inline unsigned int Nz::SpirvSectionBase::CountWord(const std::string& str) - { - return CountWord(std::string_view(str)); - } - - inline unsigned int SpirvSectionBase::CountWord(const Raw& raw) - { - return static_cast((raw.size + sizeof(UInt32) - 1) / sizeof(UInt32)); - } - - inline unsigned int SpirvSectionBase::CountWord(const std::string_view& str) - { - return (static_cast(str.size() + 1) + sizeof(UInt32) - 1) / sizeof(UInt32); //< + 1 for null character - } - - inline const std::vector& SpirvSectionBase::GetBytecode() const - { - return m_bytecode; - } - - inline std::size_t SpirvSectionBase::GetOutputOffset() const - { - return m_bytecode.size(); - } - - inline UInt32 SpirvSectionBase::BuildOpcode(SpirvOp opcode, unsigned int wordCount) - { - return UInt32(opcode) | UInt32(wordCount) << 16; - } -} - -#include diff --git a/include/Nazara/Shader/SpirvWriter.hpp b/include/Nazara/Shader/SpirvWriter.hpp deleted file mode 100644 index 478e0660e..000000000 --- a/include/Nazara/Shader/SpirvWriter.hpp +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SHADER_SPIRVWRITER_HPP -#define NAZARA_SHADER_SPIRVWRITER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class SpirvSection; - - class NAZARA_SHADER_API SpirvWriter : public ShaderWriter - { - friend class SpirvAstVisitor; - friend class SpirvBlock; - friend class SpirvExpressionLoad; - friend class SpirvExpressionStore; - - public: - struct Environment; - - SpirvWriter(); - SpirvWriter(const SpirvWriter&) = delete; - SpirvWriter(SpirvWriter&&) = delete; - ~SpirvWriter() = default; - - std::vector Generate(const ShaderAst::Module& module, const States& states = {}); - - void SetEnv(Environment environment); - - struct Environment - { - UInt32 spvMajorVersion = 1; - UInt32 spvMinorVersion = 0; - }; - - private: - struct FunctionParameter; - struct OnlyCache {}; - - UInt32 AllocateResultId(); - - void AppendHeader(); - - SpirvConstantCache::TypePtr BuildFunctionType(const ShaderAst::DeclareFunctionStatement& functionNode); - - UInt32 GetConstantId(const ShaderAst::ConstantValue& value) const; - UInt32 GetExtendedInstructionSet(const std::string& instructionSetName) const; - UInt32 GetExtVarPointerId(std::size_t varIndex) const; - UInt32 GetFunctionTypeId(const ShaderAst::DeclareFunctionStatement& functionNode); - UInt32 GetPointerTypeId(const ShaderAst::ExpressionType& type, SpirvStorageClass storageClass) const; - UInt32 GetTypeId(const ShaderAst::ExpressionType& type) const; - - UInt32 RegisterConstant(const ShaderAst::ConstantValue& value); - UInt32 RegisterFunctionType(const ShaderAst::DeclareFunctionStatement& functionNode); - UInt32 RegisterPointerType(ShaderAst::ExpressionType type, SpirvStorageClass storageClass); - UInt32 RegisterType(ShaderAst::ExpressionType type); - - static void MergeSections(std::vector& output, const SpirvSection& from); - - struct Context - { - const States* states = nullptr; - }; - - struct State; - - Context m_context; - Environment m_environment; - State* m_currentState; - }; -} - -#include - -#endif // NAZARA_SHADER_SPIRVWRITER_HPP diff --git a/include/Nazara/Shader/SpirvWriter.inl b/include/Nazara/Shader/SpirvWriter.inl deleted file mode 100644 index b396a26ed..000000000 --- a/include/Nazara/Shader/SpirvWriter.inl +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ -} - -#include diff --git a/include/Nazara/Utility.hpp b/include/Nazara/Utility.hpp index 486411760..54b2fa2b5 100644 --- a/include/Nazara/Utility.hpp +++ b/include/Nazara/Utility.hpp @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Utility/AbstractAtlas.hpp b/include/Nazara/Utility/AbstractAtlas.hpp index 8f702aa8a..3309830d7 100644 --- a/include/Nazara/Utility/AbstractAtlas.hpp +++ b/include/Nazara/Utility/AbstractAtlas.hpp @@ -8,11 +8,12 @@ #define NAZARA_UTILITY_ABSTRACTATLAS_HPP #include -#include -#include +#include #include #include #include +#include +#include namespace Nz { diff --git a/include/Nazara/Utility/Algorithm.hpp b/include/Nazara/Utility/Algorithm.hpp index 459e677c6..6a91d3fd9 100644 --- a/include/Nazara/Utility/Algorithm.hpp +++ b/include/Nazara/Utility/Algorithm.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -17,6 +16,7 @@ #include #include #include +#include namespace Nz { diff --git a/include/Nazara/Utility/Animation.hpp b/include/Nazara/Utility/Animation.hpp index e0c319964..04056409a 100644 --- a/include/Nazara/Utility/Animation.hpp +++ b/include/Nazara/Utility/Animation.hpp @@ -8,15 +8,15 @@ #define NAZARA_UTILITY_ANIMATION_HPP #include -#include #include #include #include #include #include -#include #include #include +#include +#include #include namespace Nz diff --git a/include/Nazara/Utility/Enums.hpp b/include/Nazara/Utility/Enums.hpp index 536dbf5a4..897187dbf 100644 --- a/include/Nazara/Utility/Enums.hpp +++ b/include/Nazara/Utility/Enums.hpp @@ -7,7 +7,7 @@ #ifndef NAZARA_UTILITY_ENUMS_HPP #define NAZARA_UTILITY_ENUMS_HPP -#include +#include namespace Nz { diff --git a/include/Nazara/Utility/Image.hpp b/include/Nazara/Utility/Image.hpp index 25cce5222..ed4feebf3 100644 --- a/include/Nazara/Utility/Image.hpp +++ b/include/Nazara/Utility/Image.hpp @@ -9,16 +9,16 @@ #include #include -#include #include #include #include #include #include #include -#include #include #include +#include +#include #include ///TODO: Filtres diff --git a/include/Nazara/Utility/Node.hpp b/include/Nazara/Utility/Node.hpp index bbeeea820..00bab2280 100644 --- a/include/Nazara/Utility/Node.hpp +++ b/include/Nazara/Utility/Node.hpp @@ -8,12 +8,13 @@ #define NAZARA_UTILITY_NODE_HPP #include -#include +#include #include #include #include #include #include +#include #include namespace Nz diff --git a/include/Nazara/Utility/PixelFormat.hpp b/include/Nazara/Utility/PixelFormat.hpp index 4fbe56500..a57c04f84 100644 --- a/include/Nazara/Utility/PixelFormat.hpp +++ b/include/Nazara/Utility/PixelFormat.hpp @@ -8,9 +8,10 @@ #define NAZARA_UTILITY_PIXELFORMAT_HPP #include -#include +#include #include #include +#include #include #include diff --git a/include/Nazara/Utility/Skeleton.hpp b/include/Nazara/Utility/Skeleton.hpp index 7f921d161..0c5b14e7b 100644 --- a/include/Nazara/Utility/Skeleton.hpp +++ b/include/Nazara/Utility/Skeleton.hpp @@ -9,9 +9,9 @@ #include #include -#include #include #include +#include #include namespace Nz diff --git a/include/Nazara/Utility/SubMesh.hpp b/include/Nazara/Utility/SubMesh.hpp index 3d547e6e2..1b5815086 100644 --- a/include/Nazara/Utility/SubMesh.hpp +++ b/include/Nazara/Utility/SubMesh.hpp @@ -8,11 +8,12 @@ #define NAZARA_UTILITY_SUBMESH_HPP #include -#include +#include #include #include #include #include +#include namespace Nz { diff --git a/include/Nazara/Utility/VertexDeclaration.hpp b/include/Nazara/Utility/VertexDeclaration.hpp index 316ba3d96..6562b5008 100644 --- a/include/Nazara/Utility/VertexDeclaration.hpp +++ b/include/Nazara/Utility/VertexDeclaration.hpp @@ -9,9 +9,9 @@ #include #include -#include #include #include +#include #include #include diff --git a/include/Nazara/Utility/VertexMapper.hpp b/include/Nazara/Utility/VertexMapper.hpp index 779d24e44..7387e48fa 100644 --- a/include/Nazara/Utility/VertexMapper.hpp +++ b/include/Nazara/Utility/VertexMapper.hpp @@ -8,10 +8,10 @@ #define NAZARA_UTILITY_VERTEXMAPPER_HPP #include -#include #include #include #include +#include namespace Nz { diff --git a/include/Nazara/VulkanRenderer/Utils.hpp b/include/Nazara/VulkanRenderer/Utils.hpp index 70633f67b..e71dd549b 100644 --- a/include/Nazara/VulkanRenderer/Utils.hpp +++ b/include/Nazara/VulkanRenderer/Utils.hpp @@ -9,9 +9,9 @@ #include #include -#include #include #include +#include #include #include @@ -39,8 +39,8 @@ namespace Nz inline VkSamplerMipmapMode ToVulkan(SamplerMipmapMode samplerMipmap); inline VkSamplerAddressMode ToVulkan(SamplerWrap samplerWrap); inline VkDescriptorType ToVulkan(ShaderBindingType bindingType); - inline VkShaderStageFlagBits ToVulkan(ShaderStageType stageType); - inline VkShaderStageFlags ToVulkan(ShaderStageTypeFlags stageType); + inline VkShaderStageFlagBits ToVulkan(nzsl::ShaderStageType stageType); + inline VkShaderStageFlags ToVulkan(nzsl::ShaderStageTypeFlags stageType); inline VkStencilOp ToVulkan(StencilOperation stencilOp); inline VkImageLayout ToVulkan(TextureLayout textureLayout); inline VkImageUsageFlagBits ToVulkan(TextureUsage textureLayout); diff --git a/include/Nazara/VulkanRenderer/Utils.inl b/include/Nazara/VulkanRenderer/Utils.inl index fc99c173c..ead7a939f 100644 --- a/include/Nazara/VulkanRenderer/Utils.inl +++ b/include/Nazara/VulkanRenderer/Utils.inl @@ -389,24 +389,24 @@ namespace Nz return VK_DESCRIPTOR_TYPE_SAMPLER; } - inline VkShaderStageFlagBits ToVulkan(ShaderStageType stageType) + inline VkShaderStageFlagBits ToVulkan(nzsl::ShaderStageType stageType) { switch (stageType) { - case ShaderStageType::Fragment: return VK_SHADER_STAGE_FRAGMENT_BIT; - case ShaderStageType::Vertex: return VK_SHADER_STAGE_VERTEX_BIT; + case nzsl::ShaderStageType::Fragment: return VK_SHADER_STAGE_FRAGMENT_BIT; + case nzsl::ShaderStageType::Vertex: return VK_SHADER_STAGE_VERTEX_BIT; } - NazaraError("Unhandled ShaderStageType 0x" + NumberToString(UnderlyingCast(stageType), 16)); + NazaraError("Unhandled nzsl::ShaderStageType 0x" + NumberToString(UnderlyingCast(stageType), 16)); return {}; } - inline VkShaderStageFlags ToVulkan(ShaderStageTypeFlags stageType) + inline VkShaderStageFlags ToVulkan(nzsl::ShaderStageTypeFlags stageType) { VkShaderStageFlags shaderStageBits = 0; - for (int i = 0; i <= UnderlyingCast(ShaderStageType::Max); ++i) + for (int i = 0; i <= UnderlyingCast(nzsl::ShaderStageType::Max); ++i) { - ShaderStageType shaderStage = static_cast(i); + nzsl::ShaderStageType shaderStage = static_cast(i); if (stageType.Test(shaderStage)) shaderStageBits |= ToVulkan(shaderStage); } diff --git a/include/Nazara/VulkanRenderer/VulkanCommandPool.hpp b/include/Nazara/VulkanRenderer/VulkanCommandPool.hpp index a92f11074..7c226a24a 100644 --- a/include/Nazara/VulkanRenderer/VulkanCommandPool.hpp +++ b/include/Nazara/VulkanRenderer/VulkanCommandPool.hpp @@ -8,11 +8,11 @@ #define NAZARA_VULKANRENDERER_VULKANCOMMANDPOOL_HPP #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/include/Nazara/VulkanRenderer/VulkanDevice.hpp b/include/Nazara/VulkanRenderer/VulkanDevice.hpp index cfbf64c4d..ddb2fad56 100644 --- a/include/Nazara/VulkanRenderer/VulkanDevice.hpp +++ b/include/Nazara/VulkanRenderer/VulkanDevice.hpp @@ -32,8 +32,8 @@ namespace Nz std::shared_ptr InstantiateRenderPass(std::vector attachments, std::vector subpassDescriptions, std::vector subpassDependencies) override; std::shared_ptr InstantiateRenderPipeline(RenderPipelineInfo pipelineInfo) override; std::shared_ptr InstantiateRenderPipelineLayout(RenderPipelineLayoutInfo pipelineLayoutInfo) override; - std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags stages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) override; - std::shared_ptr InstantiateShaderModule(ShaderStageTypeFlags stages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) override; + std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags stages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) override; + std::shared_ptr InstantiateShaderModule(nzsl::ShaderStageTypeFlags stages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) override; std::shared_ptr InstantiateTexture(const TextureInfo& params) override; std::shared_ptr InstantiateTextureSampler(const TextureSamplerInfo& params) override; diff --git a/include/Nazara/VulkanRenderer/VulkanRenderPass.hpp b/include/Nazara/VulkanRenderer/VulkanRenderPass.hpp index 3263cf121..f58754b7f 100644 --- a/include/Nazara/VulkanRenderer/VulkanRenderPass.hpp +++ b/include/Nazara/VulkanRenderer/VulkanRenderPass.hpp @@ -8,10 +8,10 @@ #define NAZARA_VULKANRENDERER_VULKANRENDERPASS_HPP #include -#include #include #include #include +#include #include namespace Nz diff --git a/include/Nazara/VulkanRenderer/VulkanRenderPipeline.hpp b/include/Nazara/VulkanRenderer/VulkanRenderPipeline.hpp index 9470524af..4f0ed78a4 100644 --- a/include/Nazara/VulkanRenderer/VulkanRenderPipeline.hpp +++ b/include/Nazara/VulkanRenderer/VulkanRenderPipeline.hpp @@ -9,12 +9,12 @@ #include #include -#include #include #include #include #include #include +#include #include namespace Nz diff --git a/include/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.hpp b/include/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.hpp index e239c74be..41a303504 100644 --- a/include/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.hpp +++ b/include/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.hpp @@ -8,7 +8,6 @@ #define NAZARA_VULKANRENDERER_VULKANRENDERPIPELINELAYOUT_HPP #include -#include #include #include #include @@ -17,6 +16,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/VulkanRenderer/VulkanShaderModule.hpp b/include/Nazara/VulkanRenderer/VulkanShaderModule.hpp index 14dd7c627..c059ec3ea 100644 --- a/include/Nazara/VulkanRenderer/VulkanShaderModule.hpp +++ b/include/Nazara/VulkanRenderer/VulkanShaderModule.hpp @@ -10,9 +10,9 @@ #include #include #include -#include -#include #include +#include +#include #include namespace Nz @@ -27,8 +27,8 @@ namespace Nz VulkanShaderModule(VulkanShaderModule&&) = delete; ~VulkanShaderModule() = default; - bool Create(Vk::Device& device, ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states); - bool Create(Vk::Device& device, ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states); + bool Create(Vk::Device& device, nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states); + bool Create(Vk::Device& device, nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states); inline const Vk::ShaderModule& GetHandle() const; inline const std::vector& GetStages() const; @@ -38,7 +38,7 @@ namespace Nz struct Stage { - ShaderStageType stage; + nzsl::ShaderStageType stage; std::string name; }; diff --git a/include/Nazara/VulkanRenderer/VulkanUploadPool.hpp b/include/Nazara/VulkanRenderer/VulkanUploadPool.hpp index de6612b45..5a417e31c 100644 --- a/include/Nazara/VulkanRenderer/VulkanUploadPool.hpp +++ b/include/Nazara/VulkanRenderer/VulkanUploadPool.hpp @@ -8,10 +8,10 @@ #define NAZARA_VULKANRENDERER_VULKANUPLOADPOOL_HPP #include -#include #include #include #include +#include #include #include diff --git a/include/Nazara/VulkanRenderer/Wrapper/DeviceMemory.hpp b/include/Nazara/VulkanRenderer/Wrapper/DeviceMemory.hpp index d83071f60..bf53d176a 100644 --- a/include/Nazara/VulkanRenderer/Wrapper/DeviceMemory.hpp +++ b/include/Nazara/VulkanRenderer/Wrapper/DeviceMemory.hpp @@ -8,8 +8,8 @@ #define NAZARA_VULKANRENDERER_WRAPPER_DEVICEMEMORY_HPP #include -#include #include +#include namespace Nz { diff --git a/include/Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp b/include/Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp index c659547b5..70949c18c 100644 --- a/include/Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp +++ b/include/Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp @@ -8,8 +8,8 @@ #define NAZARA_VULKANRENDERER_WRAPPER_DEVICEOBJECT_HPP #include -#include #include +#include #include #include diff --git a/include/Nazara/VulkanRenderer/Wrapper/InstanceObject.hpp b/include/Nazara/VulkanRenderer/Wrapper/InstanceObject.hpp index fcc80f1a7..c5f4e74d2 100644 --- a/include/Nazara/VulkanRenderer/Wrapper/InstanceObject.hpp +++ b/include/Nazara/VulkanRenderer/Wrapper/InstanceObject.hpp @@ -8,8 +8,8 @@ #define NAZARA_VULKANRENDERER_WRAPPER_INSTANCEOBJECT_HPP #include -#include #include +#include #include #include diff --git a/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.hpp b/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.hpp index e114312a7..3ab0fa9ca 100644 --- a/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.hpp +++ b/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.hpp @@ -8,8 +8,8 @@ #define NAZARA_VULKANRENDERER_WRAPPER_QUEUEHANDLE_HPP #include -#include #include +#include #include namespace Nz diff --git a/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.inl b/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.inl index 7cd9eb002..949d89250 100644 --- a/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.inl +++ b/include/Nazara/VulkanRenderer/Wrapper/QueueHandle.inl @@ -4,8 +4,8 @@ #include #include -#include #include +#include #include namespace Nz diff --git a/plugins/Assimp/Plugin.cpp b/plugins/Assimp/Plugin.cpp index c17e98d75..58341392c 100644 --- a/plugins/Assimp/Plugin.cpp +++ b/plugins/Assimp/Plugin.cpp @@ -23,7 +23,7 @@ SOFTWARE. */ #include -#include +#include #include #include #include diff --git a/src/Nazara/Audio/Audio.cpp b/src/Nazara/Audio/Audio.cpp index 8bd3d5b0b..153c9f585 100644 --- a/src/Nazara/Audio/Audio.cpp +++ b/src/Nazara/Audio/Audio.cpp @@ -13,10 +13,10 @@ #include #include #include -#include #include #include #include +#include #include #include diff --git a/src/Nazara/Audio/DummyAudioSource.cpp b/src/Nazara/Audio/DummyAudioSource.cpp index ac3d969f5..0af5aec88 100644 --- a/src/Nazara/Audio/DummyAudioSource.cpp +++ b/src/Nazara/Audio/DummyAudioSource.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/Nazara/Audio/Formats/drwavLoader.cpp b/src/Nazara/Audio/Formats/drwavLoader.cpp index 6d775b3a7..5ca13640a 100644 --- a/src/Nazara/Audio/Formats/drwavLoader.cpp +++ b/src/Nazara/Audio/Formats/drwavLoader.cpp @@ -8,12 +8,12 @@ #include #include #include -#include -#include #include #include #include #include +#include +#include #include #define DR_WAV_IMPLEMENTATION diff --git a/src/Nazara/Audio/Formats/libflacLoader.cpp b/src/Nazara/Audio/Formats/libflacLoader.cpp index b71d576fe..e1dc11c3c 100644 --- a/src/Nazara/Audio/Formats/libflacLoader.cpp +++ b/src/Nazara/Audio/Formats/libflacLoader.cpp @@ -8,12 +8,12 @@ #include #include #include -#include -#include #include #include #include #include +#include +#include #include #include #include diff --git a/src/Nazara/Audio/Formats/libvorbisLoader.cpp b/src/Nazara/Audio/Formats/libvorbisLoader.cpp index d2bf26f75..3b6ba7841 100644 --- a/src/Nazara/Audio/Formats/libvorbisLoader.cpp +++ b/src/Nazara/Audio/Formats/libvorbisLoader.cpp @@ -8,12 +8,12 @@ #include #include #include -#include -#include #include #include #include #include +#include +#include #include #include diff --git a/src/Nazara/Audio/Formats/minimp3Loader.cpp b/src/Nazara/Audio/Formats/minimp3Loader.cpp index fa5b02f48..222877584 100644 --- a/src/Nazara/Audio/Formats/minimp3Loader.cpp +++ b/src/Nazara/Audio/Formats/minimp3Loader.cpp @@ -8,11 +8,11 @@ #include #include #include -#include #include #include #include #include +#include #include #define MINIMP3_IMPLEMENTATION diff --git a/src/Nazara/Audio/Music.cpp b/src/Nazara/Audio/Music.cpp index 5742bc7a4..7bda5a05f 100644 --- a/src/Nazara/Audio/Music.cpp +++ b/src/Nazara/Audio/Music.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/Nazara/Audio/OpenALLibrary.cpp b/src/Nazara/Audio/OpenALLibrary.cpp index 7ab0c5ea6..e9380a68e 100644 --- a/src/Nazara/Audio/OpenALLibrary.cpp +++ b/src/Nazara/Audio/OpenALLibrary.cpp @@ -4,11 +4,11 @@ #include #include -#include #include #include #include #include +#include #include #include #include diff --git a/src/Nazara/Audio/OpenALSource.cpp b/src/Nazara/Audio/OpenALSource.cpp index 8064dd894..d4bf7a808 100644 --- a/src/Nazara/Audio/OpenALSource.cpp +++ b/src/Nazara/Audio/OpenALSource.cpp @@ -7,7 +7,7 @@ #include #include #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Core/AlgorithmCore.cpp b/src/Nazara/Core/AlgorithmCore.cpp deleted file mode 100644 index 23aaa5a17..000000000 --- a/src/Nazara/Core/AlgorithmCore.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - namespace Detail - { - const UInt8 BitReverseTable256[256] = - { - 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, - 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, - 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, - 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, - 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, - 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, - 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, - 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, - 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, - 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, - 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, - 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, - 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, - 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, - 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, - 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF - }; - } -} - -#include diff --git a/src/Nazara/Core/AntiX11.hpp b/src/Nazara/Core/AntiX11.hpp index 74c4ce15c..dd023aced 100644 --- a/src/Nazara/Core/AntiX11.hpp +++ b/src/Nazara/Core/AntiX11.hpp @@ -8,5 +8,8 @@ #error This header should only be included after including X11/Xlib.h directly or indirectly in a .cpp #endif +#undef Always #undef Bool +#undef False #undef None +#undef True diff --git a/src/Nazara/Core/Error.cpp b/src/Nazara/Core/Error.cpp index 6e1aa6cd2..a899903f2 100644 --- a/src/Nazara/Core/Error.cpp +++ b/src/Nazara/Core/Error.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include +#include #include #include diff --git a/src/Nazara/Core/FileLogger.cpp b/src/Nazara/Core/FileLogger.cpp index df275d4fa..626005c75 100644 --- a/src/Nazara/Core/FileLogger.cpp +++ b/src/Nazara/Core/FileLogger.cpp @@ -3,8 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include +#include #include #include #include diff --git a/src/Nazara/Core/GuillotineBinPack.cpp b/src/Nazara/Core/GuillotineBinPack.cpp index 3c393892d..559b8d5e6 100644 --- a/src/Nazara/Core/GuillotineBinPack.cpp +++ b/src/Nazara/Core/GuillotineBinPack.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/Nazara/Core/Hash/CRC32.cpp b/src/Nazara/Core/Hash/CRC32.cpp index ab6ae3ef1..76965a4c7 100644 --- a/src/Nazara/Core/Hash/CRC32.cpp +++ b/src/Nazara/Core/Hash/CRC32.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Core/Hash/CRC64.cpp b/src/Nazara/Core/Hash/CRC64.cpp index 574a40c3e..5ee3b39d9 100644 --- a/src/Nazara/Core/Hash/CRC64.cpp +++ b/src/Nazara/Core/Hash/CRC64.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Core/Hash/Fletcher16.cpp b/src/Nazara/Core/Hash/Fletcher16.cpp index 2a49df73a..682822fb6 100644 --- a/src/Nazara/Core/Hash/Fletcher16.cpp +++ b/src/Nazara/Core/Hash/Fletcher16.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Core/Hash/MD5.cpp b/src/Nazara/Core/Hash/MD5.cpp index a0c1672f6..f6c59ad73 100644 --- a/src/Nazara/Core/Hash/MD5.cpp +++ b/src/Nazara/Core/Hash/MD5.cpp @@ -27,7 +27,7 @@ */ #include -#include +#include #include #include diff --git a/src/Nazara/Core/Hash/SHA/Internal.cpp b/src/Nazara/Core/Hash/SHA/Internal.cpp index 9299a6064..1bcde9973 100644 --- a/src/Nazara/Core/Hash/SHA/Internal.cpp +++ b/src/Nazara/Core/Hash/SHA/Internal.cpp @@ -38,7 +38,7 @@ */ #include -#include +#include #include #include diff --git a/src/Nazara/Core/Hash/SHA/Internal.hpp b/src/Nazara/Core/Hash/SHA/Internal.hpp index edc7f1d0d..603b8ff81 100644 --- a/src/Nazara/Core/Hash/SHA/Internal.hpp +++ b/src/Nazara/Core/Hash/SHA/Internal.hpp @@ -43,6 +43,7 @@ #define NAZARA_CORE_HASH_SHA_INTERNAL_HPP #include +#include /* Digest lengths for SHA-1/224/256/384/512 */ #define SHA1_DIGEST_LENGTH 20 diff --git a/src/Nazara/Core/ParameterList.cpp b/src/Nazara/Core/ParameterList.cpp index 41ac424c4..3803d7870 100644 --- a/src/Nazara/Core/ParameterList.cpp +++ b/src/Nazara/Core/ParameterList.cpp @@ -5,8 +5,8 @@ #include #include #include -#include #include +#include #include #include diff --git a/src/Nazara/Core/Win32/FileImpl.cpp b/src/Nazara/Core/Win32/FileImpl.cpp index 6f63146de..275b8afdf 100644 --- a/src/Nazara/Core/Win32/FileImpl.cpp +++ b/src/Nazara/Core/Win32/FileImpl.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include #include diff --git a/src/Nazara/Graphics/BasicMaterial.cpp b/src/Nazara/Graphics/BasicMaterial.cpp index ece138aa3..830b0768f 100644 --- a/src/Nazara/Graphics/BasicMaterial.cpp +++ b/src/Nazara/Graphics/BasicMaterial.cpp @@ -8,10 +8,10 @@ #include #include #include -#include -#include #include #include +#include +#include #include #include @@ -158,8 +158,8 @@ namespace Nz ImageType::E2D }); - settings.sharedUniformBlocks.push_back(PredefinedInstanceData::GetUniformBlock(4, ShaderStageType::Vertex)); - settings.sharedUniformBlocks.push_back(PredefinedViewerData::GetUniformBlock(5, ShaderStageType_All)); + settings.sharedUniformBlocks.push_back(PredefinedInstanceData::GetUniformBlock(4, nzsl::ShaderStageType::Vertex)); + settings.sharedUniformBlocks.push_back(PredefinedViewerData::GetUniformBlock(5, nzsl::ShaderStageType_All)); settings.predefinedBindings[UnderlyingCast(PredefinedShaderBinding::InstanceDataUbo)] = 4; settings.predefinedBindings[UnderlyingCast(PredefinedShaderBinding::OverlayTexture)] = 3; @@ -229,18 +229,18 @@ namespace Nz std::vector> BasicMaterial::BuildShaders() { - auto shader = std::make_shared(ShaderStageType::Fragment | ShaderStageType::Vertex, "BasicMaterial"); + auto shader = std::make_shared(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, "BasicMaterial"); return { std::move(shader) }; } - auto BasicMaterial::BuildUniformOffsets() -> std::pair + auto BasicMaterial::BuildUniformOffsets() -> std::pair { - FieldOffsets fieldOffsets(StructLayout::Std140); + nzsl::FieldOffsets fieldOffsets(nzsl::StructLayout::Std140); BasicUniformOffsets uniformOffsets; - uniformOffsets.alphaThreshold = fieldOffsets.AddField(StructFieldType::Float1); - uniformOffsets.diffuseColor = fieldOffsets.AddField(StructFieldType::Float4); + uniformOffsets.alphaThreshold = fieldOffsets.AddField(nzsl::StructFieldType::Float1); + uniformOffsets.diffuseColor = fieldOffsets.AddField(nzsl::StructFieldType::Float4); uniformOffsets.totalSize = fieldOffsets.GetAlignedSize(); return std::make_pair(std::move(uniformOffsets), std::move(fieldOffsets)); diff --git a/src/Nazara/Graphics/DepthMaterial.cpp b/src/Nazara/Graphics/DepthMaterial.cpp index 5e6db970f..b92b5c2ae 100644 --- a/src/Nazara/Graphics/DepthMaterial.cpp +++ b/src/Nazara/Graphics/DepthMaterial.cpp @@ -3,15 +3,15 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include +#include +#include #include namespace Nz { std::vector> DepthMaterial::BuildShaders() { - auto shader = std::make_shared(ShaderStageType::Fragment | ShaderStageType::Vertex, "DepthMaterial"); + auto shader = std::make_shared(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, "DepthMaterial"); return { std::move(shader) }; } diff --git a/src/Nazara/Graphics/ForwardFramePipeline.cpp b/src/Nazara/Graphics/ForwardFramePipeline.cpp index ad6916161..9e8a113a4 100644 --- a/src/Nazara/Graphics/ForwardFramePipeline.cpp +++ b/src/Nazara/Graphics/ForwardFramePipeline.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -21,6 +20,7 @@ #include #include #include +#include #include #include diff --git a/src/Nazara/Graphics/FrameGraph.cpp b/src/Nazara/Graphics/FrameGraph.cpp index bce73f7c3..8f2461dc1 100644 --- a/src/Nazara/Graphics/FrameGraph.cpp +++ b/src/Nazara/Graphics/FrameGraph.cpp @@ -7,8 +7,8 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/Nazara/Graphics/Graphics.cpp b/src/Nazara/Graphics/Graphics.cpp index b796caf85..8b05adec4 100644 --- a/src/Nazara/Graphics/Graphics.cpp +++ b/src/Nazara/Graphics/Graphics.cpp @@ -6,9 +6,9 @@ #include #include #include -#include -#include #include +#include +#include #include #include #include @@ -145,7 +145,7 @@ namespace Nz { 0, 0, ShaderBindingType::Texture, - ShaderStageType::Fragment + nzsl::ShaderStageType::Fragment } }); @@ -153,12 +153,12 @@ namespace Nz if (!m_blitPipelineLayout) throw std::runtime_error("failed to instantiate fullscreen renderpipeline layout"); - ShaderAst::ModulePtr blitShaderModule = m_shaderModuleResolver->Resolve("TextureBlit"); + nzsl::Ast::ModulePtr blitShaderModule = m_shaderModuleResolver->Resolve("TextureBlit"); - ShaderWriter::States states; + nzsl::ShaderWriter::States states; states.shaderModuleResolver = m_shaderModuleResolver; - auto blitShader = m_renderDevice->InstantiateShaderModule(ShaderStageType::Fragment | ShaderStageType::Vertex, *blitShaderModule, states); + auto blitShader = m_renderDevice->InstantiateShaderModule(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, *blitShaderModule, states); if (!blitShader) throw std::runtime_error("failed to instantiate blit shader"); @@ -238,7 +238,7 @@ namespace Nz void Graphics::RegisterShaderModules() { - m_shaderModuleResolver = std::make_shared(); + m_shaderModuleResolver = std::make_shared(); RegisterEmbedShaderModule(r_basicMaterialShader); RegisterEmbedShaderModule(r_depthMaterialShader); RegisterEmbedShaderModule(r_phongMaterialShader); @@ -261,7 +261,8 @@ namespace Nz template void Graphics::RegisterEmbedShaderModule(const UInt8(&content)[N]) { - m_shaderModuleResolver->RegisterModule(ShaderAst::UnserializeShader(content, N)); + nzsl::Unserializer unserializer(content, N); + m_shaderModuleResolver->RegisterModule(nzsl::Ast::UnserializeShader(unserializer)); } void Graphics::SelectDepthStencilFormats() diff --git a/src/Nazara/Graphics/MaterialPass.cpp b/src/Nazara/Graphics/MaterialPass.cpp index c72780738..9b6207cdc 100644 --- a/src/Nazara/Graphics/MaterialPass.cpp +++ b/src/Nazara/Graphics/MaterialPass.cpp @@ -140,7 +140,7 @@ namespace Nz const auto& options = m_settings->GetOptions(); for (std::size_t optionIndex = 0; optionIndex < options.size(); ++optionIndex) { - if (!std::holds_alternative(m_optionValues[optionIndex])) + if (!std::holds_alternative(m_optionValues[optionIndex])) { auto& optionValue = m_pipelineInfo.optionValues[m_pipelineInfo.optionCount]; optionValue.hash = options[optionIndex].hash; diff --git a/src/Nazara/Graphics/MaterialPipeline.cpp b/src/Nazara/Graphics/MaterialPipeline.cpp index 47306eb30..ee9221845 100644 --- a/src/Nazara/Graphics/MaterialPipeline.cpp +++ b/src/Nazara/Graphics/MaterialPipeline.cpp @@ -49,7 +49,7 @@ namespace Nz renderPipelineInfo.pipelineLayout = m_pipelineInfo.settings->GetRenderPipelineLayout(); - std::unordered_map optionValues; + std::unordered_map optionValues; for (std::size_t i = 0; i < m_pipelineInfo.optionCount; ++i) { const auto& option = m_pipelineInfo.optionValues[i]; diff --git a/src/Nazara/Graphics/PhongLightingMaterial.cpp b/src/Nazara/Graphics/PhongLightingMaterial.cpp index 927757cec..1a1b9f5d4 100644 --- a/src/Nazara/Graphics/PhongLightingMaterial.cpp +++ b/src/Nazara/Graphics/PhongLightingMaterial.cpp @@ -7,10 +7,10 @@ #include #include #include -#include -#include #include #include +#include +#include #include #include #include @@ -229,7 +229,7 @@ namespace Nz options.defaultValues }); - settings.sharedUniformBlocks.push_back(PredefinedLightData::GetUniformBlock(6, ShaderStageType::Fragment)); + settings.sharedUniformBlocks.push_back(PredefinedLightData::GetUniformBlock(6, nzsl::ShaderStageType::Fragment)); settings.predefinedBindings[UnderlyingCast(PredefinedShaderBinding::LightDataUbo)] = 6; settings.shaders = options.shaders; @@ -310,20 +310,20 @@ namespace Nz std::vector> PhongLightingMaterial::BuildShaders() { - auto shader = std::make_shared(ShaderStageType::Fragment | ShaderStageType::Vertex, "PhongMaterial"); + auto shader = std::make_shared(nzsl::ShaderStageType::Fragment | nzsl::ShaderStageType::Vertex, "PhongMaterial"); return { std::move(shader) }; } - auto PhongLightingMaterial::BuildUniformOffsets() -> std::pair + auto PhongLightingMaterial::BuildUniformOffsets() -> std::pair { auto basicOffsets = BasicMaterial::BuildUniformOffsets(); - FieldOffsets fieldOffsets = basicOffsets.second; + nzsl::FieldOffsets fieldOffsets = basicOffsets.second; PhongUniformOffsets uniformOffsets; - uniformOffsets.ambientColor = fieldOffsets.AddField(StructFieldType::Float3); - uniformOffsets.specularColor = fieldOffsets.AddField(StructFieldType::Float3); - uniformOffsets.shininess = fieldOffsets.AddField(StructFieldType::Float1); + uniformOffsets.ambientColor = fieldOffsets.AddField(nzsl::StructFieldType::Float3); + uniformOffsets.specularColor = fieldOffsets.AddField(nzsl::StructFieldType::Float3); + uniformOffsets.shininess = fieldOffsets.AddField(nzsl::StructFieldType::Float1); uniformOffsets.totalSize = fieldOffsets.GetAlignedSize(); diff --git a/src/Nazara/Graphics/PredefinedShaderStructs.cpp b/src/Nazara/Graphics/PredefinedShaderStructs.cpp index c81e06ffb..a1d03bf13 100644 --- a/src/Nazara/Graphics/PredefinedShaderStructs.cpp +++ b/src/Nazara/Graphics/PredefinedShaderStructs.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz @@ -12,27 +12,27 @@ namespace Nz { PredefinedLightData lightData; - FieldOffsets lightStruct(StructLayout::Std140); - lightData.lightMemberOffsets.type = lightStruct.AddField(StructFieldType::Int1); - lightData.lightMemberOffsets.color = lightStruct.AddField(StructFieldType::Float4); - lightData.lightMemberOffsets.factor = lightStruct.AddField(StructFieldType::Float2); - lightData.lightMemberOffsets.parameter1 = lightStruct.AddField(StructFieldType::Float4); - lightData.lightMemberOffsets.parameter2 = lightStruct.AddField(StructFieldType::Float4); - lightData.lightMemberOffsets.parameter3 = lightStruct.AddField(StructFieldType::Float4); - lightData.lightMemberOffsets.shadowMappingFlag = lightStruct.AddField(StructFieldType::Bool1); + nzsl::FieldOffsets lightStruct(nzsl::StructLayout::Std140); + lightData.lightMemberOffsets.type = lightStruct.AddField(nzsl::StructFieldType::Int1); + lightData.lightMemberOffsets.color = lightStruct.AddField(nzsl::StructFieldType::Float4); + lightData.lightMemberOffsets.factor = lightStruct.AddField(nzsl::StructFieldType::Float2); + lightData.lightMemberOffsets.parameter1 = lightStruct.AddField(nzsl::StructFieldType::Float4); + lightData.lightMemberOffsets.parameter2 = lightStruct.AddField(nzsl::StructFieldType::Float4); + lightData.lightMemberOffsets.parameter3 = lightStruct.AddField(nzsl::StructFieldType::Float4); + lightData.lightMemberOffsets.shadowMappingFlag = lightStruct.AddField(nzsl::StructFieldType::Bool1); lightData.lightSize = lightStruct.GetAlignedSize(); - FieldOffsets lightDataStruct(StructLayout::Std140); + nzsl::FieldOffsets lightDataStruct(nzsl::StructLayout::Std140); lightData.lightsOffset = lightDataStruct.AddStructArray(lightStruct, MaxLightCount); - lightData.lightCountOffset = lightDataStruct.AddField(StructFieldType::UInt1); + lightData.lightCountOffset = lightDataStruct.AddField(nzsl::StructFieldType::UInt1); lightData.totalSize = lightDataStruct.GetAlignedSize(); return lightData; } - MaterialSettings::SharedUniformBlock PredefinedLightData::GetUniformBlock(UInt32 bindingIndex, ShaderStageTypeFlags shaderStages) + MaterialSettings::SharedUniformBlock PredefinedLightData::GetUniformBlock(UInt32 bindingIndex, nzsl::ShaderStageTypeFlags shaderStages) { PredefinedLightData lightData = GetOffsets(); @@ -53,18 +53,18 @@ namespace Nz PredefinedInstanceData PredefinedInstanceData::GetOffsets() { - FieldOffsets viewerStruct(StructLayout::Std140); + nzsl::FieldOffsets viewerStruct(nzsl::StructLayout::Std140); PredefinedInstanceData instanceData; - instanceData.worldMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - instanceData.invWorldMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); + instanceData.worldMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + instanceData.invWorldMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); instanceData.totalSize = viewerStruct.GetAlignedSize(); return instanceData; } - MaterialSettings::SharedUniformBlock PredefinedInstanceData::GetUniformBlock(UInt32 bindingIndex, ShaderStageTypeFlags shaderStages) + MaterialSettings::SharedUniformBlock PredefinedInstanceData::GetUniformBlock(UInt32 bindingIndex, nzsl::ShaderStageTypeFlags shaderStages) { PredefinedInstanceData instanceData = GetOffsets(); @@ -87,25 +87,25 @@ namespace Nz PredefinedViewerData PredefinedViewerData::GetOffsets() { - FieldOffsets viewerStruct(StructLayout::Std140); + nzsl::FieldOffsets viewerStruct(nzsl::StructLayout::Std140); PredefinedViewerData viewerData; - viewerData.projMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - viewerData.invProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - viewerData.viewMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - viewerData.invViewMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - viewerData.viewProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - viewerData.invViewProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true); - viewerData.targetSizeOffset = viewerStruct.AddField(StructFieldType::Float2); - viewerData.invTargetSizeOffset = viewerStruct.AddField(StructFieldType::Float2); - viewerData.eyePositionOffset = viewerStruct.AddField(StructFieldType::Float3); + viewerData.projMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + viewerData.invProjMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + viewerData.viewMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + viewerData.invViewMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + viewerData.viewProjMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + viewerData.invViewProjMatrixOffset = viewerStruct.AddMatrix(nzsl::StructFieldType::Float1, 4, 4, true); + viewerData.targetSizeOffset = viewerStruct.AddField(nzsl::StructFieldType::Float2); + viewerData.invTargetSizeOffset = viewerStruct.AddField(nzsl::StructFieldType::Float2); + viewerData.eyePositionOffset = viewerStruct.AddField(nzsl::StructFieldType::Float3); viewerData.totalSize = viewerStruct.GetAlignedSize(); return viewerData; } - MaterialSettings::SharedUniformBlock PredefinedViewerData::GetUniformBlock(UInt32 bindingIndex, ShaderStageTypeFlags shaderStages) + MaterialSettings::SharedUniformBlock PredefinedViewerData::GetUniformBlock(UInt32 bindingIndex, nzsl::ShaderStageTypeFlags shaderStages) { PredefinedViewerData viewerData = GetOffsets(); diff --git a/src/Nazara/Graphics/TextSprite.cpp b/src/Nazara/Graphics/TextSprite.cpp index 89e8cbb28..080d0d54a 100644 --- a/src/Nazara/Graphics/TextSprite.cpp +++ b/src/Nazara/Graphics/TextSprite.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/UberShader.cpp b/src/Nazara/Graphics/UberShader.cpp index 205738b5c..f86e7a813 100644 --- a/src/Nazara/Graphics/UberShader.cpp +++ b/src/Nazara/Graphics/UberShader.cpp @@ -6,20 +6,20 @@ #include #include #include -#include -#include +#include +#include #include #include #include namespace Nz { - UberShader::UberShader(ShaderStageTypeFlags shaderStages, std::string moduleName) : + UberShader::UberShader(nzsl::ShaderStageTypeFlags shaderStages, std::string moduleName) : UberShader(shaderStages, *Graphics::Instance()->GetShaderModuleResolver(), std::move(moduleName)) { } - UberShader::UberShader(ShaderStageTypeFlags shaderStages, ShaderModuleResolver& moduleResolver, std::string moduleName) : + UberShader::UberShader(nzsl::ShaderStageTypeFlags shaderStages, nzsl::ShaderModuleResolver& moduleResolver, std::string moduleName) : m_shaderStages(shaderStages) { m_shaderModule = moduleResolver.Resolve(moduleName); @@ -27,12 +27,12 @@ namespace Nz m_shaderModule = Validate(*m_shaderModule, &m_optionIndexByName); - m_onShaderModuleUpdated.Connect(moduleResolver.OnModuleUpdated, [this, name = std::move(moduleName)](ShaderModuleResolver* resolver, const std::string& updatedModuleName) + m_onShaderModuleUpdated.Connect(moduleResolver.OnModuleUpdated, [this, name = std::move(moduleName)](nzsl::ShaderModuleResolver* resolver, const std::string& updatedModuleName) { if (updatedModuleName != name) return; - ShaderAst::ModulePtr newShaderModule = resolver->Resolve(name); + nzsl::Ast::ModulePtr newShaderModule = resolver->Resolve(name); if (!newShaderModule) { NazaraError("failed to retrieve updated shader module " + name); @@ -56,7 +56,7 @@ namespace Nz }); } - UberShader::UberShader(ShaderStageTypeFlags shaderStages, ShaderAst::ModulePtr shaderModule) : + UberShader::UberShader(nzsl::ShaderStageTypeFlags shaderStages, nzsl::Ast::ModulePtr shaderModule) : m_shaderModule(std::move(shaderModule)), m_shaderStages(shaderStages) { @@ -70,7 +70,7 @@ namespace Nz auto it = m_combinations.find(config); if (it == m_combinations.end()) { - ShaderWriter::States states; + nzsl::ShaderWriter::States states; states.optionValues = config.optionValues; states.shaderModuleResolver = Graphics::Instance()->GetShaderModuleResolver(); @@ -82,28 +82,28 @@ namespace Nz return it->second; } - ShaderAst::ModulePtr UberShader::Validate(const ShaderAst::Module& module, std::unordered_map* options) + nzsl::Ast::ModulePtr UberShader::Validate(const nzsl::Ast::Module& module, std::unordered_map* options) { NazaraAssert(m_shaderStages != 0, "there must be at least one shader stage"); assert(options); // Try to partially sanitize shader - ShaderAst::SanitizeVisitor::Options sanitizeOptions; + nzsl::Ast::SanitizeVisitor::Options sanitizeOptions; sanitizeOptions.allowPartialSanitization = true; - ShaderAst::ModulePtr sanitizedModule = ShaderAst::Sanitize(module, sanitizeOptions); + nzsl::Ast::ModulePtr sanitizedModule = nzsl::Ast::Sanitize(module, sanitizeOptions); - ShaderStageTypeFlags supportedStageType; + nzsl::ShaderStageTypeFlags supportedStageType; - ShaderAst::AstReflect::Callbacks callbacks; - callbacks.onEntryPointDeclaration = [&](ShaderStageType stageType, const std::string& /*name*/) + nzsl::Ast::ReflectVisitor::Callbacks callbacks; + callbacks.onEntryPointDeclaration = [&](nzsl::ShaderStageType stageType, const std::string& /*name*/) { supportedStageType |= stageType; }; std::unordered_map optionByName; - callbacks.onOptionDeclaration = [&](const ShaderAst::DeclareOptionStatement& option) + callbacks.onOptionDeclaration = [&](const nzsl::Ast::DeclareOptionStatement& option) { //TODO: Check optionType @@ -112,7 +112,7 @@ namespace Nz }; }; - ShaderAst::AstReflect reflect; + nzsl::Ast::ReflectVisitor reflect; reflect.Reflect(*sanitizedModule->rootNode, callbacks); if ((m_shaderStages & supportedStageType) != m_shaderStages) diff --git a/src/Nazara/Graphics/ViewerInstance.cpp b/src/Nazara/Graphics/ViewerInstance.cpp index 478a23c4b..9c7dfa8fb 100644 --- a/src/Nazara/Graphics/ViewerInstance.cpp +++ b/src/Nazara/Graphics/ViewerInstance.cpp @@ -3,12 +3,12 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/WorldInstance.cpp b/src/Nazara/Graphics/WorldInstance.cpp index 749026314..de03e49b0 100644 --- a/src/Nazara/Graphics/WorldInstance.cpp +++ b/src/Nazara/Graphics/WorldInstance.cpp @@ -3,12 +3,12 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Network/ENetHost.cpp b/src/Nazara/Network/ENetHost.cpp index 457f5242f..8d1cdd963 100644 --- a/src/Nazara/Network/ENetHost.cpp +++ b/src/Nazara/Network/ENetHost.cpp @@ -13,10 +13,11 @@ */ #include -#include +#include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Network/ENetPacket.cpp b/src/Nazara/Network/ENetPacket.cpp index cd7ad8509..7da72685d 100644 --- a/src/Nazara/Network/ENetPacket.cpp +++ b/src/Nazara/Network/ENetPacket.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Network/Network.cpp b/src/Nazara/Network/Network.cpp index 73ba8240f..0a7ec5536 100644 --- a/src/Nazara/Network/Network.cpp +++ b/src/Nazara/Network/Network.cpp @@ -3,12 +3,12 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include +#include #if defined(NAZARA_PLATFORM_WINDOWS) #include diff --git a/src/Nazara/Network/Posix/IpAddressImpl.cpp b/src/Nazara/Network/Posix/IpAddressImpl.cpp index 0f82e8d1e..f85253236 100644 --- a/src/Nazara/Network/Posix/IpAddressImpl.cpp +++ b/src/Nazara/Network/Posix/IpAddressImpl.cpp @@ -4,10 +4,10 @@ #include #include -#include #include #include #include +#include #include #include diff --git a/src/Nazara/Network/Posix/SocketImpl.cpp b/src/Nazara/Network/Posix/SocketImpl.cpp index f9ae97c1d..296176ac2 100644 --- a/src/Nazara/Network/Posix/SocketImpl.cpp +++ b/src/Nazara/Network/Posix/SocketImpl.cpp @@ -5,11 +5,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include diff --git a/src/Nazara/Network/SystemSocket.hpp b/src/Nazara/Network/SystemSocket.hpp index 7b1559dd0..ccf80ee76 100644 --- a/src/Nazara/Network/SystemSocket.hpp +++ b/src/Nazara/Network/SystemSocket.hpp @@ -5,8 +5,8 @@ // no header guards #ifdef NAZARA_PLATFORM_WINDOWS -#include -#include +#include +#include #elif defined(NAZARA_PLATFORM_POSIX) #include #endif diff --git a/src/Nazara/Network/TcpClient.cpp b/src/Nazara/Network/TcpClient.cpp index 455f14238..40ca2f1f4 100644 --- a/src/Nazara/Network/TcpClient.cpp +++ b/src/Nazara/Network/TcpClient.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include #if defined(NAZARA_PLATFORM_WINDOWS) diff --git a/src/Nazara/Network/Win32/IpAddressImpl.cpp b/src/Nazara/Network/Win32/IpAddressImpl.cpp index b0cb828e2..5e60a064e 100644 --- a/src/Nazara/Network/Win32/IpAddressImpl.cpp +++ b/src/Nazara/Network/Win32/IpAddressImpl.cpp @@ -4,10 +4,10 @@ #include #include -#include #include #include #include +#include #include #include @@ -24,7 +24,7 @@ namespace Nz { namespace Detail { - #if NAZARA_CORE_WINDOWS_NT6 + #if NAZARA_UTILS_WINDOWS_NT6 using addrinfoImpl = addrinfoW; int GetAddressInfo(const std::string& hostname, const std::string& service, const addrinfoImpl* hints, addrinfoImpl** results) @@ -119,7 +119,7 @@ namespace Nz return IpAddress::Invalid; } - #if NAZARA_CORE_WINDOWS_NT6 + #if NAZARA_UTILS_WINDOWS_NT6 IpAddress IpAddressImpl::FromAddrinfo(const addrinfoW* info) { switch (info->ai_family) diff --git a/src/Nazara/Network/Win32/IpAddressImpl.hpp b/src/Nazara/Network/Win32/IpAddressImpl.hpp index 0a9ce60d2..61019e378 100644 --- a/src/Nazara/Network/Win32/IpAddressImpl.hpp +++ b/src/Nazara/Network/Win32/IpAddressImpl.hpp @@ -8,8 +8,8 @@ #define NAZARA_NETWORK_WIN32_IPADDRESSIMPL_HPP #include -#include -#include +#include +#include #include namespace Nz @@ -23,7 +23,7 @@ namespace Nz ~IpAddressImpl() = delete; static IpAddress FromAddrinfo(const addrinfo* info); - #if NAZARA_CORE_WINDOWS_NT6 + #if NAZARA_UTILS_WINDOWS_NT6 static IpAddress FromAddrinfo(const addrinfoW* info); #endif static IpAddress FromSockAddr(const sockaddr* address); diff --git a/src/Nazara/Network/Win32/SocketImpl.cpp b/src/Nazara/Network/Win32/SocketImpl.cpp index f85ae7242..0fdfe8149 100644 --- a/src/Nazara/Network/Win32/SocketImpl.cpp +++ b/src/Nazara/Network/Win32/SocketImpl.cpp @@ -6,9 +6,9 @@ #include #include #include -#include #include #include +#include // Some compilers (older versions of MinGW) lack Mstcpip.h which defines some structs/defines #if defined(__has_include) @@ -31,8 +31,6 @@ struct tcp_keepalive #define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4) #endif -#include - #include namespace Nz @@ -824,7 +822,7 @@ namespace Nz bool SocketImpl::SetIPv6Only(SocketHandle handle, bool ipv6Only, SocketError* error) { -#if NAZARA_CORE_WINDOWS_NT6 +#if NAZARA_UTILS_WINDOWS_NT6 NazaraAssert(handle != InvalidHandle, "Invalid handle"); DWORD option = ipv6Only; diff --git a/src/Nazara/Network/Win32/SocketImpl.hpp b/src/Nazara/Network/Win32/SocketImpl.hpp index bb5d4ae4b..c60d7b382 100644 --- a/src/Nazara/Network/Win32/SocketImpl.hpp +++ b/src/Nazara/Network/Win32/SocketImpl.hpp @@ -11,9 +11,9 @@ #include #include #include -#include +#include -#define NAZARA_NETWORK_POLL_SUPPORT NAZARA_CORE_WINDOWS_NT6 +#define NAZARA_NETWORK_POLL_SUPPORT NAZARA_UTILS_WINDOWS_NT6 namespace Nz { diff --git a/src/Nazara/Network/Win32/SocketPollerImpl.hpp b/src/Nazara/Network/Win32/SocketPollerImpl.hpp index 4c9245cc3..892248932 100644 --- a/src/Nazara/Network/Win32/SocketPollerImpl.hpp +++ b/src/Nazara/Network/Win32/SocketPollerImpl.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/Nazara/OpenGLRenderer/OpenGLBuffer.cpp b/src/Nazara/OpenGLRenderer/OpenGLBuffer.cpp index 2030d9e52..fa8f91f78 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLBuffer.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLBuffer.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include #include diff --git a/src/Nazara/OpenGLRenderer/OpenGLCommandBuffer.cpp b/src/Nazara/OpenGLRenderer/OpenGLCommandBuffer.cpp index a92a08d93..81916fb1c 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLCommandBuffer.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLCommandBuffer.cpp @@ -3,14 +3,14 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include #include #include #include #include #include +#include +#include #include namespace Nz diff --git a/src/Nazara/OpenGLRenderer/OpenGLCommandBufferBuilder.cpp b/src/Nazara/OpenGLRenderer/OpenGLCommandBufferBuilder.cpp index 27d7cd612..658cf1a77 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLCommandBufferBuilder.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLCommandBufferBuilder.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -11,6 +10,7 @@ #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/OpenGLRenderer/OpenGLCommandPool.cpp b/src/Nazara/OpenGLRenderer/OpenGLCommandPool.cpp index 1b100687d..97e603be7 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLCommandPool.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLCommandPool.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include +#include #include namespace Nz diff --git a/src/Nazara/OpenGLRenderer/OpenGLDevice.cpp b/src/Nazara/OpenGLRenderer/OpenGLDevice.cpp index 4520d5ce2..b66dbb97f 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLDevice.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLDevice.cpp @@ -144,12 +144,12 @@ namespace Nz return std::make_shared(std::move(pipelineLayoutInfo)); } - std::shared_ptr OpenGLDevice::InstantiateShaderModule(ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) + std::shared_ptr OpenGLDevice::InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) { return std::make_shared(*this, shaderStages, shaderModule, states); } - std::shared_ptr OpenGLDevice::InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) + std::shared_ptr OpenGLDevice::InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) { return std::make_shared(*this, shaderStages, lang, source, sourceSize, states); } diff --git a/src/Nazara/OpenGLRenderer/OpenGLRenderPipeline.cpp b/src/Nazara/OpenGLRenderer/OpenGLRenderPipeline.cpp index 9d4399fda..55ef5bb3f 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLRenderPipeline.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLRenderPipeline.cpp @@ -7,9 +7,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include #include @@ -33,7 +33,7 @@ namespace Nz // Enable pipeline states before compiling and linking the program, for drivers which embed some pipeline states into the shader binary (to avoid recompilation later) activeContext->UpdateStates(m_pipelineInfo, false); - ShaderStageTypeFlags stageFlags; + nzsl::ShaderStageTypeFlags stageFlags; for (const auto& shaderModulePtr : m_pipelineInfo.shaderModules) { @@ -44,21 +44,21 @@ namespace Nz // OpenGL ES programs must have both vertex and fragment shaders or a compute shader or a mesh and fragment shader. if (device.GetReferenceContext().GetParams().type == GL::ContextType::OpenGL_ES) { - auto GenerateIfMissing = [&](ShaderStageType stage) + auto GenerateIfMissing = [&](nzsl::ShaderStageType stage) { if (!stageFlags.Test(stage)) { - ShaderAst::Module dummyModule(100); - dummyModule.rootNode = ShaderBuilder::MultiStatement(); - dummyModule.rootNode->statements.push_back(ShaderBuilder::DeclareFunction(stage, "main", {}, {})); + nzsl::Ast::Module dummyModule(100); + dummyModule.rootNode = nzsl::ShaderBuilder::MultiStatement(); + dummyModule.rootNode->statements.push_back(nzsl::ShaderBuilder::DeclareFunction(stage, "main", {}, {})); OpenGLShaderModule shaderModule(device, stage, dummyModule); stageFlags |= shaderModule.Attach(m_program, pipelineLayout.GetBindingMapping()); } }; - GenerateIfMissing(ShaderStageType::Fragment); - GenerateIfMissing(ShaderStageType::Vertex); + GenerateIfMissing(nzsl::ShaderStageType::Fragment); + GenerateIfMissing(nzsl::ShaderStageType::Vertex); } m_program.Link(); @@ -67,7 +67,7 @@ namespace Nz if (!m_program.GetLinkStatus(&errLog)) throw std::runtime_error("failed to link program: " + errLog); - m_flipYUniformLocation = m_program.GetUniformLocation(GlslWriter::GetFlipYUniformName()); + m_flipYUniformLocation = m_program.GetUniformLocation(nzsl::GlslWriter::GetFlipYUniformName()); if (m_flipYUniformLocation != -1) m_program.Uniform(m_flipYUniformLocation, 1.f); } diff --git a/src/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.cpp b/src/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.cpp index 5b02dec7c..f2dbc70f5 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLRenderPipelineLayout.cpp @@ -4,9 +4,9 @@ #include #include -#include -#include #include +#include +#include #include #include #include diff --git a/src/Nazara/OpenGLRenderer/OpenGLShaderBinding.cpp b/src/Nazara/OpenGLRenderer/OpenGLShaderBinding.cpp index f38dc1873..c4203d109 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLShaderBinding.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLShaderBinding.cpp @@ -4,11 +4,11 @@ #include #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/OpenGLRenderer/OpenGLShaderModule.cpp b/src/Nazara/OpenGLRenderer/OpenGLShaderModule.cpp index ccec2380a..ce5fa9317 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLShaderModule.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLShaderModule.cpp @@ -5,22 +5,22 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include namespace Nz { - OpenGLShaderModule::OpenGLShaderModule(OpenGLDevice& device, ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) : + OpenGLShaderModule::OpenGLShaderModule(OpenGLDevice& device, nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) : m_device(device) { NazaraAssert(shaderStages != 0, "at least one shader stage must be specified"); Create(device, shaderStages, shaderModule, states); } - OpenGLShaderModule::OpenGLShaderModule(OpenGLDevice& device, ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) : + OpenGLShaderModule::OpenGLShaderModule(OpenGLDevice& device, nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) : m_device(device) { NazaraAssert(shaderStages != 0, "at least one shader stage must be specified"); @@ -29,9 +29,9 @@ namespace Nz { case ShaderLanguage::GLSL: { - for (std::size_t i = 0; i < ShaderStageTypeCount; ++i) + for (std::size_t i = 0; i < nzsl::ShaderStageTypeCount; ++i) { - ShaderStageType shaderStage = static_cast(i); + nzsl::ShaderStageType shaderStage = static_cast(i); if (shaderStages.Test(shaderStage)) { NazaraAssert(shaderStages == shaderStage, "when supplying GLSL, only one shader stage type can be specified"); @@ -48,18 +48,19 @@ namespace Nz case ShaderLanguage::NazaraBinary: { - auto shader = ShaderAst::UnserializeShader(source, sourceSize); + nzsl::Unserializer unserializer(source, sourceSize); + auto shader = nzsl::Ast::UnserializeShader(unserializer); Create(device, shaderStages, *shader, states); break; } case ShaderLanguage::NazaraShader: { - std::vector tokens = Nz::ShaderLang::Tokenize(std::string_view(static_cast(source), sourceSize)); + std::vector tokens = nzsl::Tokenize(std::string_view(static_cast(source), sourceSize)); - Nz::ShaderLang::Parser parser; - Nz::ShaderAst::ModulePtr shaderAst = parser.Parse(tokens); - Create(device, shaderStages, *shaderAst, states); + nzsl::Parser parser; + nzsl::Ast::ModulePtr module = parser.Parse(tokens); + Create(device, shaderStages, *module, states); break; } @@ -82,12 +83,12 @@ namespace Nz } } - ShaderStageTypeFlags OpenGLShaderModule::Attach(GL::Program& program, const GlslWriter::BindingMapping& bindingMapping) const + nzsl::ShaderStageTypeFlags OpenGLShaderModule::Attach(GL::Program& program, const nzsl::GlslWriter::BindingMapping& bindingMapping) const { const auto& context = m_device.GetReferenceContext(); const auto& contextParams = context.GetParams(); - GlslWriter::Environment env; + nzsl::GlslWriter::Environment env; env.glES = (contextParams.type == GL::ContextType::OpenGL_ES); env.glMajorVersion = contextParams.glMajorVersion; env.glMinorVersion = contextParams.glMinorVersion; @@ -98,10 +99,10 @@ namespace Nz env.flipYPosition = true; env.remapZPosition = true; - GlslWriter writer; + nzsl::GlslWriter writer; writer.SetEnv(env); - ShaderStageTypeFlags stageFlags; + nzsl::ShaderStageTypeFlags stageFlags; for (const auto& shaderEntry : m_shaders) { GL::Shader shader; @@ -137,20 +138,20 @@ namespace Nz return stageFlags; } - void OpenGLShaderModule::Create(OpenGLDevice& /*device*/, ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) + void OpenGLShaderModule::Create(OpenGLDevice& /*device*/, nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) { m_states = states; m_states.sanitized = true; //< Shader is always sanitized (because of keywords) - ShaderAst::SanitizeVisitor::Options options = GlslWriter::GetSanitizeOptions(); + nzsl::Ast::SanitizeVisitor::Options options = nzsl::GlslWriter::GetSanitizeOptions(); options.optionValues = states.optionValues; options.moduleResolver = states.shaderModuleResolver; - ShaderAst::ModulePtr sanitized = ShaderAst::Sanitize(shaderModule, options); + nzsl::Ast::ModulePtr sanitized = nzsl::Ast::Sanitize(shaderModule, options); - for (std::size_t i = 0; i < ShaderStageTypeCount; ++i) + for (std::size_t i = 0; i < nzsl::ShaderStageTypeCount; ++i) { - ShaderStageType shaderStage = static_cast(i); + nzsl::ShaderStageType shaderStage = static_cast(i); if (shaderStages.Test(shaderStage)) { auto& entry = m_shaders.emplace_back(); diff --git a/src/Nazara/OpenGLRenderer/OpenGLTexture.cpp b/src/Nazara/OpenGLRenderer/OpenGLTexture.cpp index 7d0109e43..faad05460 100644 --- a/src/Nazara/OpenGLRenderer/OpenGLTexture.cpp +++ b/src/Nazara/OpenGLRenderer/OpenGLTexture.cpp @@ -3,8 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include +#include #include #include diff --git a/src/Nazara/OpenGLRenderer/Wrapper/Context.cpp b/src/Nazara/OpenGLRenderer/Wrapper/Context.cpp index 7cf525e60..3d3542add 100644 --- a/src/Nazara/OpenGLRenderer/Wrapper/Context.cpp +++ b/src/Nazara/OpenGLRenderer/Wrapper/Context.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -11,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.cpp b/src/Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.cpp index bdf2a7083..1372b87a8 100644 --- a/src/Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.cpp +++ b/src/Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include #include #include diff --git a/src/Nazara/OpenGLRenderer/Wrapper/WGL/WGLContext.cpp b/src/Nazara/OpenGLRenderer/Wrapper/WGL/WGLContext.cpp index d3ef15db0..f043e3ea9 100644 --- a/src/Nazara/OpenGLRenderer/Wrapper/WGL/WGLContext.cpp +++ b/src/Nazara/OpenGLRenderer/Wrapper/WGL/WGLContext.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include +#include #include #include #include diff --git a/src/Nazara/Physics2D/Collider2D.cpp b/src/Nazara/Physics2D/Collider2D.cpp index c0b8bb810..aaab86211 100644 --- a/src/Nazara/Physics2D/Collider2D.cpp +++ b/src/Nazara/Physics2D/Collider2D.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include #include #include +#include +#include #include #include #include diff --git a/src/Nazara/Physics2D/PhysWorld2D.cpp b/src/Nazara/Physics2D/PhysWorld2D.cpp index 97ce25957..5d9d58039 100644 --- a/src/Nazara/Physics2D/PhysWorld2D.cpp +++ b/src/Nazara/Physics2D/PhysWorld2D.cpp @@ -3,8 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include +#include #include #include diff --git a/src/Nazara/Physics3D/PhysWorld3D.cpp b/src/Nazara/Physics3D/PhysWorld3D.cpp index 33dc290d3..f7c18d6f4 100644 --- a/src/Nazara/Physics3D/PhysWorld3D.cpp +++ b/src/Nazara/Physics3D/PhysWorld3D.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include #include #include diff --git a/src/Nazara/Platform/Platform.cpp b/src/Nazara/Platform/Platform.cpp index 117074cbb..2b0eda206 100644 --- a/src/Nazara/Platform/Platform.cpp +++ b/src/Nazara/Platform/Platform.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Platform/SDL2/CursorImpl.hpp b/src/Nazara/Platform/SDL2/CursorImpl.hpp index dd25fa374..43c6b3de7 100644 --- a/src/Nazara/Platform/SDL2/CursorImpl.hpp +++ b/src/Nazara/Platform/SDL2/CursorImpl.hpp @@ -8,10 +8,10 @@ #define NAZARA_PLATFORM_SDL2_CURSORIMPL_HPP #include -#include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Platform/SDL2/IconImpl.hpp b/src/Nazara/Platform/SDL2/IconImpl.hpp index 11576f7d7..930e01857 100644 --- a/src/Nazara/Platform/SDL2/IconImpl.hpp +++ b/src/Nazara/Platform/SDL2/IconImpl.hpp @@ -8,8 +8,8 @@ #define NAZARA_PLATFORM_SDL2_ICONIMPL_HPP #include -#include #include +#include #include namespace Nz diff --git a/src/Nazara/Platform/SDL2/InputImpl.cpp b/src/Nazara/Platform/SDL2/InputImpl.cpp index e6d5a8368..e5a050b60 100644 --- a/src/Nazara/Platform/SDL2/InputImpl.cpp +++ b/src/Nazara/Platform/SDL2/InputImpl.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include +#include #include #include #include diff --git a/src/Nazara/Platform/Window.cpp b/src/Nazara/Platform/Window.cpp index 11d4559a2..d1c99abbd 100644 --- a/src/Nazara/Platform/Window.cpp +++ b/src/Nazara/Platform/Window.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Renderer/RenderDevice.cpp b/src/Nazara/Renderer/RenderDevice.cpp index 40bfd3b62..a9ed230e7 100644 --- a/src/Nazara/Renderer/RenderDevice.cpp +++ b/src/Nazara/Renderer/RenderDevice.cpp @@ -11,7 +11,7 @@ namespace Nz { RenderDevice::~RenderDevice() = default; - std::shared_ptr RenderDevice::InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const std::filesystem::path& sourcePath, const ShaderWriter::States& states) + std::shared_ptr RenderDevice::InstantiateShaderModule(nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const std::filesystem::path& sourcePath, const nzsl::ShaderWriter::States& states) { File file(sourcePath); if (!file.Open(OpenMode::ReadOnly | OpenMode::Text)) diff --git a/src/Nazara/Renderer/Renderer.cpp b/src/Nazara/Renderer/Renderer.cpp index 560e489e2..2b1c164bd 100644 --- a/src/Nazara/Renderer/Renderer.cpp +++ b/src/Nazara/Renderer/Renderer.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -12,6 +11,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Nazara/Shader/Ast/AstCloner.cpp b/src/Nazara/Shader/Ast/AstCloner.cpp deleted file mode 100644 index 911a170a6..000000000 --- a/src/Nazara/Shader/Ast/AstCloner.cpp +++ /dev/null @@ -1,624 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - ExpressionPtr AstCloner::Clone(Expression& expr) - { - expr.Visit(*this); - - assert(m_statementStack.empty() && m_expressionStack.size() == 1); - return PopExpression(); - } - - StatementPtr AstCloner::Clone(Statement& statement) - { - statement.Visit(*this); - - assert(m_expressionStack.empty() && m_statementStack.size() == 1); - return PopStatement(); - } - - ExpressionPtr AstCloner::CloneExpression(Expression& expr) - { - expr.Visit(*this); - return PopExpression(); - } - - StatementPtr AstCloner::CloneStatement(Statement& statement) - { - statement.Visit(*this); - return PopStatement(); - } - - ExpressionValue AstCloner::CloneType(const ExpressionValue& exprType) - { - if (!exprType.HasValue()) - return {}; - - if (exprType.IsExpression()) - return CloneExpression(exprType.GetExpression()); - else - { - assert(exprType.IsResultingValue()); - return exprType.GetResultingValue(); - } - } - - StatementPtr AstCloner::Clone(BranchStatement& node) - { - auto clone = std::make_unique(); - clone->condStatements.reserve(node.condStatements.size()); - clone->isConst = node.isConst; - - for (auto& cond : node.condStatements) - { - auto& condStatement = clone->condStatements.emplace_back(); - condStatement.condition = CloneExpression(cond.condition); - condStatement.statement = CloneStatement(cond.statement); - } - - clone->elseStatement = CloneStatement(node.elseStatement); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ConditionalStatement& node) - { - auto clone = std::make_unique(); - clone->condition = CloneExpression(node.condition); - clone->statement = CloneStatement(node.statement); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareAliasStatement& node) - { - auto clone = std::make_unique(); - clone->aliasIndex = node.aliasIndex; - clone->name = node.name; - clone->expression = CloneExpression(node.expression); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareConstStatement& node) - { - auto clone = std::make_unique(); - clone->constIndex = node.constIndex; - clone->name = node.name; - clone->type = Clone(node.type); - clone->expression = CloneExpression(node.expression); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareExternalStatement& node) - { - auto clone = std::make_unique(); - clone->bindingSet = Clone(node.bindingSet); - - clone->externalVars.reserve(node.externalVars.size()); - for (const auto& var : node.externalVars) - { - auto& cloneVar = clone->externalVars.emplace_back(); - cloneVar.name = var.name; - cloneVar.varIndex = var.varIndex; - cloneVar.type = Clone(var.type); - cloneVar.bindingIndex = Clone(var.bindingIndex); - cloneVar.bindingSet = Clone(var.bindingSet); - - cloneVar.sourceLocation = var.sourceLocation; - } - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareFunctionStatement& node) - { - auto clone = std::make_unique(); - clone->depthWrite = Clone(node.depthWrite); - clone->earlyFragmentTests = Clone(node.earlyFragmentTests); - clone->entryStage = Clone(node.entryStage); - clone->funcIndex = node.funcIndex; - clone->isExported = Clone(node.isExported); - clone->name = node.name; - clone->returnType = Clone(node.returnType); - - clone->parameters.reserve(node.parameters.size()); - for (auto& parameter : node.parameters) - { - auto& cloneParam = clone->parameters.emplace_back(); - cloneParam.name = parameter.name; - cloneParam.type = Clone(parameter.type); - cloneParam.varIndex = parameter.varIndex; - - cloneParam.sourceLocation = parameter.sourceLocation; - } - - clone->statements.reserve(node.statements.size()); - for (auto& statement : node.statements) - clone->statements.push_back(CloneStatement(statement)); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareOptionStatement& node) - { - auto clone = std::make_unique(); - clone->defaultValue = CloneExpression(node.defaultValue); - clone->optIndex = node.optIndex; - clone->optName = node.optName; - clone->optType = Clone(node.optType); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareStructStatement& node) - { - auto clone = std::make_unique(); - clone->isExported = Clone(node.isExported); - clone->structIndex = node.structIndex; - - clone->description.layout = Clone(node.description.layout); - clone->description.name = node.description.name; - - clone->description.members.reserve(node.description.members.size()); - for (const auto& member : node.description.members) - { - auto& cloneMember = clone->description.members.emplace_back(); - cloneMember.name = member.name; - cloneMember.type = Clone(member.type); - cloneMember.builtin = Clone(member.builtin); - cloneMember.cond = Clone(member.cond); - cloneMember.locationIndex = Clone(member.locationIndex); - - cloneMember.sourceLocation = member.sourceLocation; - } - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DeclareVariableStatement& node) - { - auto clone = std::make_unique(); - clone->initialExpression = CloneExpression(node.initialExpression); - clone->varIndex = node.varIndex; - clone->varName = node.varName; - clone->varType = Clone(node.varType); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(DiscardStatement& node) - { - auto clone = std::make_unique(); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ExpressionStatement& node) - { - auto clone = std::make_unique(); - clone->expression = CloneExpression(node.expression); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ForStatement& node) - { - auto clone = std::make_unique(); - clone->fromExpr = CloneExpression(node.fromExpr); - clone->stepExpr = CloneExpression(node.stepExpr); - clone->toExpr = CloneExpression(node.toExpr); - clone->statement = CloneStatement(node.statement); - clone->unroll = Clone(node.unroll); - clone->varName = node.varName; - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ForEachStatement& node) - { - auto clone = std::make_unique(); - clone->expression = CloneExpression(node.expression); - clone->statement = CloneStatement(node.statement); - clone->unroll = Clone(node.unroll); - clone->varName = node.varName; - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ImportStatement& node) - { - auto clone = std::make_unique(); - clone->moduleName = node.moduleName; - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(MultiStatement& node) - { - auto clone = std::make_unique(); - clone->statements.reserve(node.statements.size()); - for (auto& statement : node.statements) - clone->statements.push_back(CloneStatement(statement)); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(NoOpStatement& node) - { - auto clone = std::make_unique(); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ReturnStatement& node) - { - auto clone = std::make_unique(); - clone->returnExpr = CloneExpression(node.returnExpr); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(ScopedStatement& node) - { - auto clone = std::make_unique(); - clone->statement = CloneStatement(node.statement); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - StatementPtr AstCloner::Clone(WhileStatement& node) - { - auto clone = std::make_unique(); - clone->condition = CloneExpression(node.condition); - clone->body = CloneStatement(node.body); - clone->unroll = Clone(node.unroll); - - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(AccessIdentifierExpression& node) - { - auto clone = std::make_unique(); - clone->identifiers = node.identifiers; - clone->expr = CloneExpression(node.expr); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(AccessIndexExpression& node) - { - auto clone = std::make_unique(); - clone->expr = CloneExpression(node.expr); - - clone->indices.reserve(node.indices.size()); - for (auto& parameter : node.indices) - clone->indices.push_back(CloneExpression(parameter)); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(AliasValueExpression& node) - { - auto clone = std::make_unique(); - clone->aliasId = node.aliasId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(AssignExpression& node) - { - auto clone = std::make_unique(); - clone->op = node.op; - clone->left = CloneExpression(node.left); - clone->right = CloneExpression(node.right); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(BinaryExpression& node) - { - auto clone = std::make_unique(); - clone->op = node.op; - clone->left = CloneExpression(node.left); - clone->right = CloneExpression(node.right); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(CallFunctionExpression& node) - { - auto clone = std::make_unique(); - clone->targetFunction = CloneExpression(node.targetFunction); - - clone->parameters.reserve(node.parameters.size()); - for (auto& parameter : node.parameters) - clone->parameters.push_back(CloneExpression(parameter)); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(CallMethodExpression& node) - { - auto clone = std::make_unique(); - clone->methodName = node.methodName; - - clone->object = CloneExpression(node.object); - - clone->parameters.reserve(node.parameters.size()); - for (auto& parameter : node.parameters) - clone->parameters.push_back(CloneExpression(parameter)); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(CastExpression& node) - { - auto clone = std::make_unique(); - clone->targetType = Clone(node.targetType); - - for (std::size_t expressionIndex = 0; expressionIndex < node.expressions.size(); ++expressionIndex) - { - auto& expr = node.expressions[expressionIndex]; - if (!expr) - break; - - clone->expressions[expressionIndex] = CloneExpression(expr); - } - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(ConditionalExpression& node) - { - auto clone = std::make_unique(); - clone->condition = CloneExpression(node.condition); - clone->falsePath = CloneExpression(node.falsePath); - clone->truePath = CloneExpression(node.truePath); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(ConstantExpression& node) - { - auto clone = std::make_unique(); - clone->constantId = node.constantId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(ConstantValueExpression& node) - { - auto clone = std::make_unique(); - clone->value = node.value; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(FunctionExpression& node) - { - auto clone = std::make_unique(); - clone->funcId = node.funcId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(IdentifierExpression& node) - { - auto clone = std::make_unique(); - clone->identifier = node.identifier; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(IntrinsicExpression& node) - { - auto clone = std::make_unique(); - clone->intrinsic = node.intrinsic; - - clone->parameters.reserve(node.parameters.size()); - for (auto& parameter : node.parameters) - clone->parameters.push_back(CloneExpression(parameter)); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(IntrinsicFunctionExpression& node) - { - auto clone = std::make_unique(); - clone->intrinsicId = node.intrinsicId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(StructTypeExpression& node) - { - auto clone = std::make_unique(); - clone->structTypeId = node.structTypeId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(SwizzleExpression& node) - { - auto clone = std::make_unique(); - clone->componentCount = node.componentCount; - clone->components = node.components; - clone->expression = CloneExpression(node.expression); - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(TypeExpression& node) - { - auto clone = std::make_unique(); - clone->typeId = node.typeId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(VariableValueExpression& node) - { - auto clone = std::make_unique(); - clone->variableId = node.variableId; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - - ExpressionPtr AstCloner::Clone(UnaryExpression& node) - { - auto clone = std::make_unique(); - clone->expression = CloneExpression(node.expression); - clone->op = node.op; - - clone->cachedExpressionType = node.cachedExpressionType; - clone->sourceLocation = node.sourceLocation; - - return clone; - } - -#define NAZARA_SHADERAST_EXPRESSION(NodeType) void AstCloner::Visit(NodeType& node) \ - { \ - PushExpression(Clone(node)); \ - } - -#define NAZARA_SHADERAST_STATEMENT(NodeType) void AstCloner::Visit(NodeType& node) \ - { \ - PushStatement(Clone(node)); \ - } - -#include - - void AstCloner::PushExpression(ExpressionPtr expression) - { - m_expressionStack.emplace_back(std::move(expression)); - } - - void AstCloner::PushStatement(StatementPtr statement) - { - m_statementStack.emplace_back(std::move(statement)); - } - - ExpressionPtr AstCloner::PopExpression() - { - assert(!m_expressionStack.empty()); - - ExpressionPtr expr = std::move(m_expressionStack.back()); - m_expressionStack.pop_back(); - - return expr; - } - - StatementPtr AstCloner::PopStatement() - { - assert(!m_statementStack.empty()); - - StatementPtr expr = std::move(m_statementStack.back()); - m_statementStack.pop_back(); - - return expr; - } -} diff --git a/src/Nazara/Shader/Ast/AstConstantPropagationVisitor.cpp b/src/Nazara/Shader/Ast/AstConstantPropagationVisitor.cpp deleted file mode 100644 index b622f9480..000000000 --- a/src/Nazara/Shader/Ast/AstConstantPropagationVisitor.cpp +++ /dev/null @@ -1,1304 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - namespace NAZARA_ANONYMOUS_NAMESPACE - { - template - struct is_complete_helper - { - // SFINAE: sizeof in an incomplete type is an error, but since there's another specialization it won't result in a compilation error - template - static auto test(U*) -> std::bool_constant; - - // less specialized overload - static auto test(...) -> std::false_type; - - using type = decltype(test(static_cast(nullptr))); - }; - - template - struct is_complete : is_complete_helper::type {}; - - template - inline constexpr bool is_complete_v = is_complete::value; - - template - struct VectorInfo - { - static constexpr std::size_t Dimensions = 1; - using Base = T; - }; - - template - struct VectorInfo> - { - static constexpr std::size_t Dimensions = 2; - using Base = T; - }; - - template - struct VectorInfo> - { - static constexpr std::size_t Dimensions = 3; - using Base = T; - }; - - template - struct VectorInfo> - { - static constexpr std::size_t Dimensions = 4; - using Base = T; - }; - - /*************************************************************************************************/ - - template - struct BinaryConstantPropagation; - - // CompEq - template - struct BinaryCompEqBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs == rhs); - } - }; - - template - struct BinaryCompEq; - - template - struct BinaryConstantPropagation - { - using Op = BinaryCompEq; - }; - - // CompGe - template - struct BinaryCompGeBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs >= rhs); - } - }; - - template - struct BinaryCompGe; - - template - struct BinaryConstantPropagation - { - using Op = BinaryCompGe; - }; - - // CompGt - template - struct BinaryCompGtBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs > rhs); - } - }; - - template - struct BinaryCompGt; - - template - struct BinaryConstantPropagation - { - using Op = BinaryCompGt; - }; - - // CompLe - template - struct BinaryCompLeBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs <= rhs); - } - }; - - template - struct BinaryCompLe; - - template - struct BinaryConstantPropagation - { - using Op = BinaryCompLe; - }; - - // CompLt - template - struct BinaryCompLtBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs < rhs); - } - }; - - template - struct BinaryCompLt; - - template - struct BinaryConstantPropagation - { - using Op = BinaryCompLe; - }; - - // CompNe - template - struct BinaryCompNeBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs != rhs); - } - }; - - template - struct BinaryCompNe; - - template - struct BinaryConstantPropagation - { - using Op = BinaryCompNe; - }; - - // LogicalAnd - template - struct BinaryLogicalAndBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs && rhs); - } - }; - - template - struct BinaryLogicalAnd; - - template - struct BinaryConstantPropagation - { - using Op = BinaryLogicalAnd; - }; - - // LogicalOr - template - struct BinaryLogicalOrBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs || rhs); - } - }; - - template - struct BinaryLogicalOr; - - template - struct BinaryConstantPropagation - { - using Op = BinaryLogicalOr; - }; - - // Addition - template - struct BinaryAdditionBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs + rhs); - } - }; - - template - struct BinaryAddition; - - template - struct BinaryConstantPropagation - { - using Op = BinaryAddition; - }; - - // Division - template - struct BinaryDivisionBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs / rhs); - } - }; - - template - struct BinaryDivision; - - template - struct BinaryConstantPropagation - { - using Op = BinaryDivision; - }; - - // Multiplication - template - struct BinaryMultiplicationBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs * rhs); - } - }; - - template - struct BinaryMultiplication; - - template - struct BinaryConstantPropagation - { - using Op = BinaryMultiplication; - }; - - // Subtraction - template - struct BinarySubtractionBase - { - std::unique_ptr operator()(const T1& lhs, const T2& rhs) - { - return ShaderBuilder::Constant(lhs - rhs); - } - }; - - template - struct BinarySubtraction; - - template - struct BinaryConstantPropagation - { - using Op = BinarySubtraction; - }; - - /*************************************************************************************************/ - - template - struct CastConstantBase - { - std::unique_ptr operator()(const Args&... args) - { - return ShaderBuilder::Constant(T(args...)); - } - }; - - template - struct CastConstant; - - /*************************************************************************************************/ - - template - struct SwizzlePropagationBase; - - template - struct SwizzlePropagationBase - { - std::unique_ptr operator()(const std::array& /*components*/, T value) - { - if constexpr (TargetComponentCount == 4) - return ShaderBuilder::Constant(Vector4(value, value, value, value)); - else if constexpr (TargetComponentCount == 3) - return ShaderBuilder::Constant(Vector3(value, value, value)); - else if constexpr (TargetComponentCount == 2) - return ShaderBuilder::Constant(Vector2(value, value)); - else if constexpr (TargetComponentCount == 1) - return ShaderBuilder::Constant(value); - else - static_assert(AlwaysFalse(), "unexpected TargetComponentCount"); - } - }; - - template - struct SwizzlePropagationBase - { - std::unique_ptr operator()(const std::array& components, const Vector2& value) - { - if constexpr (TargetComponentCount == 4) - return ShaderBuilder::Constant(Vector4(value[components[0]], value[components[1]], value[components[2]], value[components[3]])); - else if constexpr (TargetComponentCount == 3) - return ShaderBuilder::Constant(Vector3(value[components[0]], value[components[1]], value[components[2]])); - else if constexpr (TargetComponentCount == 2) - return ShaderBuilder::Constant(Vector2(value[components[0]], value[components[1]])); - else if constexpr (TargetComponentCount == 1) - return ShaderBuilder::Constant(value[components[0]]); - else - static_assert(AlwaysFalse(), "unexpected TargetComponentCount"); - } - }; - - template - struct SwizzlePropagationBase - { - std::unique_ptr operator()(const std::array& components, const Vector3& value) - { - if constexpr (TargetComponentCount == 4) - return ShaderBuilder::Constant(Vector4(value[components[0]], value[components[1]], value[components[2]], value[components[3]])); - else if constexpr (TargetComponentCount == 3) - return ShaderBuilder::Constant(Vector3(value[components[0]], value[components[1]], value[components[2]])); - else if constexpr (TargetComponentCount == 2) - return ShaderBuilder::Constant(Vector2(value[components[0]], value[components[1]])); - else if constexpr (TargetComponentCount == 1) - return ShaderBuilder::Constant(value[components[0]]); - else - static_assert(AlwaysFalse(), "unexpected TargetComponentCount"); - } - }; - - template - struct SwizzlePropagationBase - { - std::unique_ptr operator()(const std::array& components, const Vector4& value) - { - if constexpr (TargetComponentCount == 4) - return ShaderBuilder::Constant(Vector4(value[components[0]], value[components[1]], value[components[2]], value[components[3]])); - else if constexpr (TargetComponentCount == 3) - return ShaderBuilder::Constant(Vector3(value[components[0]], value[components[1]], value[components[2]])); - else if constexpr (TargetComponentCount == 2) - return ShaderBuilder::Constant(Vector2(value[components[0]], value[components[1]])); - else if constexpr (TargetComponentCount == 1) - return ShaderBuilder::Constant(value[components[0]]); - else - static_assert(AlwaysFalse(), "unexpected TargetComponentCount"); - } - }; - - template - struct SwizzlePropagation; - - /*************************************************************************************************/ - - template - struct UnaryConstantPropagation; - - // LogicalNot - template - struct UnaryLogicalNotBase - { - std::unique_ptr operator()(const T& arg) - { - return ShaderBuilder::Constant(!arg); - } - }; - - template - struct UnaryLogicalNot; - - template - struct UnaryConstantPropagation - { - using Op = UnaryLogicalNot; - }; - - // Minus - template - struct UnaryMinusBase - { - std::unique_ptr operator()(const T& arg) - { - return ShaderBuilder::Constant(-arg); - } - }; - - template - struct UnaryMinus; - - template - struct UnaryConstantPropagation - { - using Op = UnaryMinus; - }; - - // Plus - template - struct UnaryPlusBase - { - std::unique_ptr operator()(const T& arg) - { - return ShaderBuilder::Constant(arg); - } - }; - - template - struct UnaryPlus; - - template - struct UnaryConstantPropagation - { - using Op = UnaryPlus; - }; - -#define EnableOptimisation(Op, ...) template<> struct Op<__VA_ARGS__> : Op##Base<__VA_ARGS__> {} - - // Binary - - EnableOptimisation(BinaryCompEq, bool, bool); - EnableOptimisation(BinaryCompEq, double, double); - EnableOptimisation(BinaryCompEq, float, float); - EnableOptimisation(BinaryCompEq, Int32, Int32); - EnableOptimisation(BinaryCompEq, Vector2f, Vector2f); - EnableOptimisation(BinaryCompEq, Vector3f, Vector3f); - EnableOptimisation(BinaryCompEq, Vector4f, Vector4f); - EnableOptimisation(BinaryCompEq, Vector2i32, Vector2i32); - EnableOptimisation(BinaryCompEq, Vector3i32, Vector3i32); - EnableOptimisation(BinaryCompEq, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryCompGe, double, double); - EnableOptimisation(BinaryCompGe, float, float); - EnableOptimisation(BinaryCompGe, Int32, Int32); - EnableOptimisation(BinaryCompGe, Vector2f, Vector2f); - EnableOptimisation(BinaryCompGe, Vector3f, Vector3f); - EnableOptimisation(BinaryCompGe, Vector4f, Vector4f); - EnableOptimisation(BinaryCompGe, Vector2i32, Vector2i32); - EnableOptimisation(BinaryCompGe, Vector3i32, Vector3i32); - EnableOptimisation(BinaryCompGe, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryCompGt, double, double); - EnableOptimisation(BinaryCompGt, float, float); - EnableOptimisation(BinaryCompGt, Int32, Int32); - EnableOptimisation(BinaryCompGt, Vector2f, Vector2f); - EnableOptimisation(BinaryCompGt, Vector3f, Vector3f); - EnableOptimisation(BinaryCompGt, Vector4f, Vector4f); - EnableOptimisation(BinaryCompGt, Vector2i32, Vector2i32); - EnableOptimisation(BinaryCompGt, Vector3i32, Vector3i32); - EnableOptimisation(BinaryCompGt, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryCompLe, double, double); - EnableOptimisation(BinaryCompLe, float, float); - EnableOptimisation(BinaryCompLe, Int32, Int32); - EnableOptimisation(BinaryCompLe, Vector2f, Vector2f); - EnableOptimisation(BinaryCompLe, Vector3f, Vector3f); - EnableOptimisation(BinaryCompLe, Vector4f, Vector4f); - EnableOptimisation(BinaryCompLe, Vector2i32, Vector2i32); - EnableOptimisation(BinaryCompLe, Vector3i32, Vector3i32); - EnableOptimisation(BinaryCompLe, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryCompLt, double, double); - EnableOptimisation(BinaryCompLt, float, float); - EnableOptimisation(BinaryCompLt, Int32, Int32); - EnableOptimisation(BinaryCompLt, Vector2f, Vector2f); - EnableOptimisation(BinaryCompLt, Vector3f, Vector3f); - EnableOptimisation(BinaryCompLt, Vector4f, Vector4f); - EnableOptimisation(BinaryCompLt, Vector2i32, Vector2i32); - EnableOptimisation(BinaryCompLt, Vector3i32, Vector3i32); - EnableOptimisation(BinaryCompLt, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryCompNe, bool, bool); - EnableOptimisation(BinaryCompNe, double, double); - EnableOptimisation(BinaryCompNe, float, float); - EnableOptimisation(BinaryCompNe, Int32, Int32); - EnableOptimisation(BinaryCompNe, Vector2f, Vector2f); - EnableOptimisation(BinaryCompNe, Vector3f, Vector3f); - EnableOptimisation(BinaryCompNe, Vector4f, Vector4f); - EnableOptimisation(BinaryCompNe, Vector2i32, Vector2i32); - EnableOptimisation(BinaryCompNe, Vector3i32, Vector3i32); - EnableOptimisation(BinaryCompNe, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryLogicalAnd, bool, bool); - EnableOptimisation(BinaryLogicalOr, bool, bool); - - EnableOptimisation(BinaryAddition, double, double); - EnableOptimisation(BinaryAddition, float, float); - EnableOptimisation(BinaryAddition, Int32, Int32); - EnableOptimisation(BinaryAddition, Vector2f, Vector2f); - EnableOptimisation(BinaryAddition, Vector3f, Vector3f); - EnableOptimisation(BinaryAddition, Vector4f, Vector4f); - EnableOptimisation(BinaryAddition, Vector2i32, Vector2i32); - EnableOptimisation(BinaryAddition, Vector3i32, Vector3i32); - EnableOptimisation(BinaryAddition, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryDivision, double, double); - EnableOptimisation(BinaryDivision, double, Vector2d); - EnableOptimisation(BinaryDivision, double, Vector3d); - EnableOptimisation(BinaryDivision, double, Vector4d); - EnableOptimisation(BinaryDivision, float, float); - EnableOptimisation(BinaryDivision, float, Vector2f); - EnableOptimisation(BinaryDivision, float, Vector3f); - EnableOptimisation(BinaryDivision, float, Vector4f); - EnableOptimisation(BinaryDivision, Int32, Int32); - EnableOptimisation(BinaryDivision, Int32, Vector2i32); - EnableOptimisation(BinaryDivision, Int32, Vector3i32); - EnableOptimisation(BinaryDivision, Int32, Vector4i32); - EnableOptimisation(BinaryDivision, Vector2f, float); - EnableOptimisation(BinaryDivision, Vector2f, Vector2f); - EnableOptimisation(BinaryDivision, Vector3f, float); - EnableOptimisation(BinaryDivision, Vector3f, Vector3f); - EnableOptimisation(BinaryDivision, Vector4f, float); - EnableOptimisation(BinaryDivision, Vector4f, Vector4f); - EnableOptimisation(BinaryDivision, Vector2d, double); - EnableOptimisation(BinaryDivision, Vector2d, Vector2d); - EnableOptimisation(BinaryDivision, Vector3d, double); - EnableOptimisation(BinaryDivision, Vector3d, Vector3d); - EnableOptimisation(BinaryDivision, Vector4d, double); - EnableOptimisation(BinaryDivision, Vector4d, Vector4d); - EnableOptimisation(BinaryDivision, Vector2i32, Int32); - EnableOptimisation(BinaryDivision, Vector2i32, Vector2i32); - EnableOptimisation(BinaryDivision, Vector3i32, Int32); - EnableOptimisation(BinaryDivision, Vector3i32, Vector3i32); - EnableOptimisation(BinaryDivision, Vector4i32, Int32); - EnableOptimisation(BinaryDivision, Vector4i32, Vector4i32); - - EnableOptimisation(BinaryMultiplication, double, double); - EnableOptimisation(BinaryMultiplication, double, Vector2d); - EnableOptimisation(BinaryMultiplication, double, Vector3d); - EnableOptimisation(BinaryMultiplication, double, Vector4d); - EnableOptimisation(BinaryMultiplication, float, float); - EnableOptimisation(BinaryMultiplication, float, Vector2f); - EnableOptimisation(BinaryMultiplication, float, Vector3f); - EnableOptimisation(BinaryMultiplication, float, Vector4f); - EnableOptimisation(BinaryMultiplication, Int32, Int32); - EnableOptimisation(BinaryMultiplication, Int32, Vector2i32); - EnableOptimisation(BinaryMultiplication, Int32, Vector3i32); - EnableOptimisation(BinaryMultiplication, Int32, Vector4i32); - EnableOptimisation(BinaryMultiplication, Vector2f, float); - EnableOptimisation(BinaryMultiplication, Vector2f, Vector2f); - EnableOptimisation(BinaryMultiplication, Vector3f, float); - EnableOptimisation(BinaryMultiplication, Vector3f, Vector3f); - EnableOptimisation(BinaryMultiplication, Vector4f, float); - EnableOptimisation(BinaryMultiplication, Vector4f, Vector4f); - EnableOptimisation(BinaryMultiplication, Vector2d, double); - EnableOptimisation(BinaryMultiplication, Vector2d, Vector2d); - EnableOptimisation(BinaryMultiplication, Vector3d, double); - EnableOptimisation(BinaryMultiplication, Vector3d, Vector3d); - EnableOptimisation(BinaryMultiplication, Vector4d, double); - EnableOptimisation(BinaryMultiplication, Vector4d, Vector4d); - EnableOptimisation(BinaryMultiplication, Vector2i32, Int32); - EnableOptimisation(BinaryMultiplication, Vector2i32, Vector2i32); - EnableOptimisation(BinaryMultiplication, Vector3i32, Int32); - EnableOptimisation(BinaryMultiplication, Vector3i32, Vector3i32); - EnableOptimisation(BinaryMultiplication, Vector4i32, Int32); - EnableOptimisation(BinaryMultiplication, Vector4i32, Vector4i32); - - EnableOptimisation(BinarySubtraction, double, double); - EnableOptimisation(BinarySubtraction, float, float); - EnableOptimisation(BinarySubtraction, Int32, Int32); - EnableOptimisation(BinarySubtraction, Vector2f, Vector2f); - EnableOptimisation(BinarySubtraction, Vector3f, Vector3f); - EnableOptimisation(BinarySubtraction, Vector4f, Vector4f); - EnableOptimisation(BinarySubtraction, Vector2i32, Vector2i32); - EnableOptimisation(BinarySubtraction, Vector3i32, Vector3i32); - EnableOptimisation(BinarySubtraction, Vector4i32, Vector4i32); - - // Cast - - EnableOptimisation(CastConstant, bool, bool); - EnableOptimisation(CastConstant, bool, Int32); - EnableOptimisation(CastConstant, bool, UInt32); - - EnableOptimisation(CastConstant, double, double); - EnableOptimisation(CastConstant, double, float); - EnableOptimisation(CastConstant, double, Int32); - EnableOptimisation(CastConstant, double, UInt32); - - EnableOptimisation(CastConstant, float, double); - EnableOptimisation(CastConstant, float, float); - EnableOptimisation(CastConstant, float, Int32); - EnableOptimisation(CastConstant, float, UInt32); - - EnableOptimisation(CastConstant, Int32, double); - EnableOptimisation(CastConstant, Int32, float); - EnableOptimisation(CastConstant, Int32, Int32); - EnableOptimisation(CastConstant, Int32, UInt32); - - EnableOptimisation(CastConstant, UInt32, double); - EnableOptimisation(CastConstant, UInt32, float); - EnableOptimisation(CastConstant, UInt32, Int32); - EnableOptimisation(CastConstant, UInt32, UInt32); - - //EnableOptimisation(CastConstant, Vector2d, double, double); - //EnableOptimisation(CastConstant, Vector3d, double, double, double); - //EnableOptimisation(CastConstant, Vector4d, double, double, double, double); - - EnableOptimisation(CastConstant, Vector2f, float, float); - EnableOptimisation(CastConstant, Vector3f, float, float, float); - EnableOptimisation(CastConstant, Vector4f, float, float, float, float); - - EnableOptimisation(CastConstant, Vector2i32, Int32, Int32); - EnableOptimisation(CastConstant, Vector3i32, Int32, Int32, Int32); - EnableOptimisation(CastConstant, Vector4i32, Int32, Int32, Int32, Int32); - - //EnableOptimisation(CastConstant, Vector2ui32, UInt32, UInt32); - //EnableOptimisation(CastConstant, Vector3ui32, UInt32, UInt32, UInt32); - //EnableOptimisation(CastConstant, Vector4ui32, UInt32, UInt32, UInt32, UInt32); - - // Swizzle - EnableOptimisation(SwizzlePropagation, double, 1, 1); - EnableOptimisation(SwizzlePropagation, double, 1, 2); - EnableOptimisation(SwizzlePropagation, double, 1, 3); - EnableOptimisation(SwizzlePropagation, double, 1, 4); - - EnableOptimisation(SwizzlePropagation, double, 2, 1); - EnableOptimisation(SwizzlePropagation, double, 2, 2); - EnableOptimisation(SwizzlePropagation, double, 2, 3); - EnableOptimisation(SwizzlePropagation, double, 2, 4); - - EnableOptimisation(SwizzlePropagation, double, 3, 1); - EnableOptimisation(SwizzlePropagation, double, 3, 2); - EnableOptimisation(SwizzlePropagation, double, 3, 3); - EnableOptimisation(SwizzlePropagation, double, 3, 4); - - EnableOptimisation(SwizzlePropagation, double, 4, 1); - EnableOptimisation(SwizzlePropagation, double, 4, 2); - EnableOptimisation(SwizzlePropagation, double, 4, 3); - EnableOptimisation(SwizzlePropagation, double, 4, 4); - - EnableOptimisation(SwizzlePropagation, float, 1, 1); - EnableOptimisation(SwizzlePropagation, float, 1, 2); - EnableOptimisation(SwizzlePropagation, float, 1, 3); - EnableOptimisation(SwizzlePropagation, float, 1, 4); - - EnableOptimisation(SwizzlePropagation, float, 2, 1); - EnableOptimisation(SwizzlePropagation, float, 2, 2); - EnableOptimisation(SwizzlePropagation, float, 2, 3); - EnableOptimisation(SwizzlePropagation, float, 2, 4); - - EnableOptimisation(SwizzlePropagation, float, 3, 1); - EnableOptimisation(SwizzlePropagation, float, 3, 2); - EnableOptimisation(SwizzlePropagation, float, 3, 3); - EnableOptimisation(SwizzlePropagation, float, 3, 4); - - EnableOptimisation(SwizzlePropagation, float, 4, 1); - EnableOptimisation(SwizzlePropagation, float, 4, 2); - EnableOptimisation(SwizzlePropagation, float, 4, 3); - EnableOptimisation(SwizzlePropagation, float, 4, 4); - - EnableOptimisation(SwizzlePropagation, Int32, 1, 1); - EnableOptimisation(SwizzlePropagation, Int32, 1, 2); - EnableOptimisation(SwizzlePropagation, Int32, 1, 3); - EnableOptimisation(SwizzlePropagation, Int32, 1, 4); - - EnableOptimisation(SwizzlePropagation, Int32, 2, 1); - EnableOptimisation(SwizzlePropagation, Int32, 2, 2); - EnableOptimisation(SwizzlePropagation, Int32, 2, 3); - EnableOptimisation(SwizzlePropagation, Int32, 2, 4); - - EnableOptimisation(SwizzlePropagation, Int32, 3, 1); - EnableOptimisation(SwizzlePropagation, Int32, 3, 2); - EnableOptimisation(SwizzlePropagation, Int32, 3, 3); - EnableOptimisation(SwizzlePropagation, Int32, 3, 4); - - EnableOptimisation(SwizzlePropagation, Int32, 4, 1); - EnableOptimisation(SwizzlePropagation, Int32, 4, 2); - EnableOptimisation(SwizzlePropagation, Int32, 4, 3); - EnableOptimisation(SwizzlePropagation, Int32, 4, 4); - - // Unary - - EnableOptimisation(UnaryLogicalNot, bool); - - EnableOptimisation(UnaryMinus, double); - EnableOptimisation(UnaryMinus, float); - EnableOptimisation(UnaryMinus, Int32); - EnableOptimisation(UnaryMinus, Vector2f); - EnableOptimisation(UnaryMinus, Vector3f); - EnableOptimisation(UnaryMinus, Vector4f); - EnableOptimisation(UnaryMinus, Vector2i32); - EnableOptimisation(UnaryMinus, Vector3i32); - EnableOptimisation(UnaryMinus, Vector4i32); - - EnableOptimisation(UnaryPlus, double); - EnableOptimisation(UnaryPlus, float); - EnableOptimisation(UnaryPlus, Int32); - EnableOptimisation(UnaryPlus, Vector2f); - EnableOptimisation(UnaryPlus, Vector3f); - EnableOptimisation(UnaryPlus, Vector4f); - EnableOptimisation(UnaryPlus, Vector2i32); - EnableOptimisation(UnaryPlus, Vector3i32); - EnableOptimisation(UnaryPlus, Vector4i32); - -#undef EnableOptimisation - } - - ModulePtr AstConstantPropagationVisitor::Process(const Module& shaderModule) - { - auto rootnode = StaticUniquePointerCast(Process(*shaderModule.rootNode)); - - return std::make_shared(shaderModule.metadata, std::move(rootnode), shaderModule.importedModules); - } - - ModulePtr AstConstantPropagationVisitor::Process(const Module& shaderModule, const Options& options) - { - auto rootNode = StaticUniquePointerCast(Process(*shaderModule.rootNode, options)); - - return std::make_shared(shaderModule.metadata, std::move(rootNode), shaderModule.importedModules); - } - - ExpressionPtr AstConstantPropagationVisitor::Clone(BinaryExpression& node) - { - auto lhs = CloneExpression(node.left); - auto rhs = CloneExpression(node.right); - - if (lhs->GetType() == NodeType::ConstantValueExpression && rhs->GetType() == NodeType::ConstantValueExpression) - { - const ConstantValueExpression& lhsConstant = static_cast(*lhs); - const ConstantValueExpression& rhsConstant = static_cast(*rhs); - - ExpressionPtr optimized; - switch (node.op) - { - case BinaryType::Add: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::Subtract: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::Multiply: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::Divide: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::CompEq: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::CompGe: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::CompGt: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::CompLe: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::CompLt: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::CompNe: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::LogicalAnd: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - - case BinaryType::LogicalOr: - optimized = PropagateBinaryConstant(lhsConstant, rhsConstant); - break; - } - - if (optimized) - return optimized; - } - - auto binary = ShaderBuilder::Binary(node.op, std::move(lhs), std::move(rhs)); - binary->cachedExpressionType = node.cachedExpressionType; - binary->sourceLocation = node.sourceLocation; - - return binary; - } - - ExpressionPtr AstConstantPropagationVisitor::Clone(CastExpression& node) - { - std::array expressions; - - std::size_t expressionCount = 0; - for (const auto& expression : node.expressions) - { - if (!expression) - break; - - expressions[expressionCount] = CloneExpression(expression); - expressionCount++; - } - - ExpressionPtr optimized; - if (IsPrimitiveType(node.targetType.GetResultingValue())) - { - if (expressionCount == 1 && expressions.front()->GetType() == NodeType::ConstantValueExpression) - { - const ConstantValueExpression& constantExpr = static_cast(*expressions.front()); - - switch (std::get(node.targetType.GetResultingValue())) - { - case PrimitiveType::Boolean: optimized = PropagateSingleValueCast(constantExpr); break; - case PrimitiveType::Float32: optimized = PropagateSingleValueCast(constantExpr); break; - case PrimitiveType::Int32: optimized = PropagateSingleValueCast(constantExpr); break; - case PrimitiveType::UInt32: optimized = PropagateSingleValueCast(constantExpr); break; - case PrimitiveType::String: break; - } - } - } - else if (IsVectorType(node.targetType.GetResultingValue())) - { - const auto& vecType = std::get(node.targetType.GetResultingValue()); - - // Decompose vector into values (cast(vec3, float) => cast(float, float, float, float)) - std::vector constantValues; - for (std::size_t i = 0; i < expressionCount; ++i) - { - if (expressions[i]->GetType() != NodeType::ConstantValueExpression) - { - constantValues.clear(); - break; - } - - const auto& constantExpr = static_cast(*expressions[i]); - - if (!constantValues.empty() && GetConstantType(constantValues.front()) != GetConstantType(constantExpr.value)) - { - // Unhandled case, all cast parameters are expected to be of the same type - constantValues.clear(); - break; - } - - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - throw std::runtime_error("invalid type (value expected)"); - else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) - constantValues.push_back(arg); - else if constexpr (std::is_same_v || std::is_same_v) - { - constantValues.push_back(arg.x); - constantValues.push_back(arg.y); - } - else if constexpr (std::is_same_v || std::is_same_v) - { - constantValues.push_back(arg.x); - constantValues.push_back(arg.y); - constantValues.push_back(arg.z); - } - else if constexpr (std::is_same_v || std::is_same_v) - { - constantValues.push_back(arg.x); - constantValues.push_back(arg.y); - constantValues.push_back(arg.z); - constantValues.push_back(arg.w); - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, constantExpr.value); - } - - if (!constantValues.empty()) - { - assert(constantValues.size() == vecType.componentCount); - - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - switch (vecType.componentCount) - { - case 2: - optimized = PropagateVec2Cast(std::get(constantValues[0]), std::get(constantValues[1])); - break; - - case 3: - optimized = PropagateVec3Cast(std::get(constantValues[0]), std::get(constantValues[1]), std::get(constantValues[2])); - break; - - case 4: - optimized = PropagateVec4Cast(std::get(constantValues[0]), std::get(constantValues[1]), std::get(constantValues[2]), std::get(constantValues[3])); - break; - } - }, constantValues.front()); - } - } - - if (optimized) - return optimized; - - auto cast = ShaderBuilder::Cast(node.targetType.GetResultingValue(), std::move(expressions)); - cast->cachedExpressionType = node.cachedExpressionType; - cast->sourceLocation = node.sourceLocation; - - return cast; - } - - StatementPtr AstConstantPropagationVisitor::Clone(BranchStatement& node) - { - std::vector statements; - StatementPtr elseStatement; - - bool continuePropagation = true; - for (auto& condStatement : node.condStatements) - { - auto cond = CloneExpression(condStatement.condition); - - if (continuePropagation && cond->GetType() == NodeType::ConstantValueExpression) - { - auto& constant = static_cast(*cond); - - const ExpressionType* constantType = GetExpressionType(constant); - if (!constantType) - { - // unresolved type, can't continue propagating this branch - continuePropagation = false; - continue; - } - - if (!IsPrimitiveType(*constantType) || std::get(*constantType) != PrimitiveType::Boolean) - continue; - - bool cValue = std::get(constant.value); - if (!cValue) - continue; - - if (statements.empty()) - { - // First condition is true, dismiss the branch - return Unscope(AstCloner::Clone(*condStatement.statement)); - } - else - { - // Some condition after the first one is true, make it the else statement and stop there - elseStatement = CloneStatement(condStatement.statement); - break; - } - } - else - { - auto& c = statements.emplace_back(); - c.condition = std::move(cond); - c.statement = CloneStatement(condStatement.statement); - } - } - - if (statements.empty()) - { - // All conditions have been removed, replace by else statement or no-op - if (node.elseStatement) - return Unscope(AstCloner::Clone(*node.elseStatement)); - else - return ShaderBuilder::NoOp(); - } - - if (!elseStatement) - elseStatement = CloneStatement(node.elseStatement); - - auto branchStatement = ShaderBuilder::Branch(std::move(statements), std::move(elseStatement)); - branchStatement->sourceLocation = node.sourceLocation; - - return branchStatement; - } - - ExpressionPtr AstConstantPropagationVisitor::Clone(ConditionalExpression& node) - { - auto cond = CloneExpression(node.condition); - if (cond->GetType() != NodeType::ConstantValueExpression) - throw std::runtime_error("conditional expression condition must be a constant expression"); - - auto& constant = static_cast(*cond); - - assert(constant.cachedExpressionType); - const ExpressionType& constantType = constant.cachedExpressionType.value(); - - if (!IsPrimitiveType(constantType) || std::get(constantType) != PrimitiveType::Boolean) - throw std::runtime_error("conditional expression condition must resolve to a boolean"); - - bool cValue = std::get(constant.value); - if (cValue) - return AstCloner::Clone(*node.truePath); - else - return AstCloner::Clone(*node.falsePath); - } - - ExpressionPtr AstConstantPropagationVisitor::Clone(ConstantExpression& node) - { - if (!m_options.constantQueryCallback) - return AstCloner::Clone(node); - - const ConstantValue* constantValue = m_options.constantQueryCallback(node.constantId); - if (!constantValue) - return AstCloner::Clone(node); - - auto constant = ShaderBuilder::Constant(*constantValue); - constant->cachedExpressionType = GetConstantType(constant->value); - constant->sourceLocation = node.sourceLocation; - - return constant; - } - - ExpressionPtr AstConstantPropagationVisitor::Clone(SwizzleExpression& node) - { - auto expr = CloneExpression(node.expression); - - if (expr->GetType() == NodeType::ConstantValueExpression) - { - const ConstantValueExpression& constantExpr = static_cast(*expr); - - ExpressionPtr optimized; - switch (node.componentCount) - { - case 1: - optimized = PropagateConstantSwizzle<1>(node.components, constantExpr); - break; - - case 2: - optimized = PropagateConstantSwizzle<2>(node.components, constantExpr); - break; - - case 3: - optimized = PropagateConstantSwizzle<3>(node.components, constantExpr); - break; - - case 4: - optimized = PropagateConstantSwizzle<4>(node.components, constantExpr); - break; - } - - if (optimized) - return optimized; - } - else if (expr->GetType() == NodeType::SwizzleExpression) - { - SwizzleExpression& constantExpr = static_cast(*expr); - - std::array newComponents = {}; - for (std::size_t i = 0; i < node.componentCount; ++i) - newComponents[i] = constantExpr.components[node.components[i]]; - - constantExpr.componentCount = node.componentCount; - constantExpr.components = newComponents; - - return expr; - } - - auto swizzle = ShaderBuilder::Swizzle(std::move(expr), node.components, node.componentCount); - swizzle->cachedExpressionType = node.cachedExpressionType; - swizzle->sourceLocation = node.sourceLocation; - - return swizzle; - } - - ExpressionPtr AstConstantPropagationVisitor::Clone(UnaryExpression& node) - { - auto expr = CloneExpression(node.expression); - - if (expr->GetType() == NodeType::ConstantValueExpression) - { - const ConstantValueExpression& constantExpr = static_cast(*expr); - - ExpressionPtr optimized; - switch (node.op) - { - case UnaryType::LogicalNot: - optimized = PropagateUnaryConstant(constantExpr); - break; - - case UnaryType::Minus: - optimized = PropagateUnaryConstant(constantExpr); - break; - - case UnaryType::Plus: - optimized = PropagateUnaryConstant(constantExpr); - break; - } - - if (optimized) - return optimized; - } - - auto unary = ShaderBuilder::Unary(node.op, std::move(expr)); - unary->cachedExpressionType = node.cachedExpressionType; - unary->sourceLocation = node.sourceLocation; - - return unary; - } - - StatementPtr AstConstantPropagationVisitor::Clone(ConditionalStatement& node) - { - auto cond = CloneExpression(node.condition); - if (cond->GetType() != NodeType::ConstantValueExpression) - throw std::runtime_error("conditional expression condition must be a constant expression"); - - auto& constant = static_cast(*cond); - - assert(constant.cachedExpressionType); - const ExpressionType& constantType = constant.cachedExpressionType.value(); - - if (!IsPrimitiveType(constantType) || std::get(constantType) != PrimitiveType::Boolean) - throw std::runtime_error("conditional expression condition must resolve to a boolean"); - - bool cValue = std::get(constant.value); - if (cValue) - return AstCloner::Clone(node); - else - return ShaderBuilder::NoOp(); - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateBinaryConstant(const ConstantValueExpression& lhs, const ConstantValueExpression& rhs) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - std::visit([&](auto&& arg1) - { - using T1 = std::decay_t; - - std::visit([&](auto&& arg2) - { - using T2 = std::decay_t; - using PCType = BinaryConstantPropagation; - - if constexpr (is_complete_v) - { - using Op = typename PCType::Op; - if constexpr (is_complete_v) - optimized = Op{}(arg1, arg2); - } - - }, rhs.value); - }, lhs.value); - - if (optimized) - optimized->cachedExpressionType = GetConstantType(optimized->value); - - return optimized; - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateSingleValueCast(const ConstantValueExpression& operand) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - - std::visit([&](auto&& arg) - { - using T = std::decay_t; - using CCType = CastConstant; - - if constexpr (is_complete_v) - optimized = CCType{}(arg); - }, operand.value); - - return optimized; - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateConstantSwizzle(const std::array& components, const ConstantValueExpression& operand) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - using BaseType = typename VectorInfo::Base; - constexpr std::size_t FromComponentCount = VectorInfo::Dimensions; - - using SPType = SwizzlePropagation; - - if constexpr (is_complete_v) - optimized = SPType{}(components, arg); - }, operand.value); - - return optimized; - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateUnaryConstant(const ConstantValueExpression& operand) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - std::visit([&](auto&& arg) - { - using T = std::decay_t; - using PCType = UnaryConstantPropagation; - - if constexpr (is_complete_v) - { - using Op = typename PCType::Op; - if constexpr (is_complete_v) - optimized = Op{}(arg); - } - }, operand.value); - - if (optimized) - optimized->cachedExpressionType = GetConstantType(optimized->value); - - return optimized; - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateVec2Cast(TargetType v1, TargetType v2) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - - using CCType = CastConstant, TargetType, TargetType>; - - if constexpr (is_complete_v) - optimized = CCType{}(v1, v2); - - return optimized; - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateVec3Cast(TargetType v1, TargetType v2, TargetType v3) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - - using CCType = CastConstant, TargetType, TargetType, TargetType>; - - if constexpr (is_complete_v) - optimized = CCType{}(v1, v2, v3); - - return optimized; - } - - template - ExpressionPtr AstConstantPropagationVisitor::PropagateVec4Cast(TargetType v1, TargetType v2, TargetType v3, TargetType v4) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::unique_ptr optimized; - - using CCType = CastConstant, TargetType, TargetType, TargetType, TargetType>; - - if constexpr (is_complete_v) - optimized = CCType{}(v1, v2, v3, v4); - - return optimized; - } - - - StatementPtr AstConstantPropagationVisitor::Unscope(StatementPtr node) - { - assert(node); - - if (node->GetType() == NodeType::ScopedStatement) - return std::move(static_cast(*node).statement); - else - return node; - } -} diff --git a/src/Nazara/Shader/Ast/AstExportVisitor.cpp b/src/Nazara/Shader/Ast/AstExportVisitor.cpp deleted file mode 100644 index 6a0643860..000000000 --- a/src/Nazara/Shader/Ast/AstExportVisitor.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - void AstExportVisitor::Visit(Statement& statement, const Callbacks& callbacks) - { - m_callbacks = &callbacks; - statement.Visit(*this); - } - - void AstExportVisitor::Visit(DeclareFunctionStatement& node) - { - if (!node.isExported.HasValue() || !node.isExported.GetResultingValue()) - return; - - if (m_callbacks->onExportedFunc) - m_callbacks->onExportedFunc(node); - } - - void AstExportVisitor::Visit(DeclareStructStatement& node) - { - if (!node.isExported.HasValue() || !node.isExported.GetResultingValue()) - return; - - if (m_callbacks->onExportedStruct) - m_callbacks->onExportedStruct(node); - } -} diff --git a/src/Nazara/Shader/Ast/AstExpressionVisitor.cpp b/src/Nazara/Shader/Ast/AstExpressionVisitor.cpp deleted file mode 100644 index f12d14958..000000000 --- a/src/Nazara/Shader/Ast/AstExpressionVisitor.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - AstExpressionVisitor::~AstExpressionVisitor() = default; -} diff --git a/src/Nazara/Shader/Ast/AstExpressionVisitorExcept.cpp b/src/Nazara/Shader/Ast/AstExpressionVisitorExcept.cpp deleted file mode 100644 index ebf24bce6..000000000 --- a/src/Nazara/Shader/Ast/AstExpressionVisitorExcept.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ -#define NAZARA_SHADERAST_EXPRESSION(Node) void AstExpressionVisitorExcept::Visit(ShaderAst::Node& /*node*/) \ - { \ - throw std::runtime_error("unexpected " #Node " node"); \ - } -#include -} diff --git a/src/Nazara/Shader/Ast/AstRecursiveVisitor.cpp b/src/Nazara/Shader/Ast/AstRecursiveVisitor.cpp deleted file mode 100644 index bb086f568..000000000 --- a/src/Nazara/Shader/Ast/AstRecursiveVisitor.cpp +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - void AstRecursiveVisitor::Visit(AccessIdentifierExpression& node) - { - node.expr->Visit(*this); - } - - void AstRecursiveVisitor::Visit(AccessIndexExpression& node) - { - node.expr->Visit(*this); - for (auto& index : node.indices) - index->Visit(*this); - } - - void AstRecursiveVisitor::Visit(AliasValueExpression& /*node*/) - { - /* nothing to do */ - } - - void AstRecursiveVisitor::Visit(AssignExpression& node) - { - node.left->Visit(*this); - node.right->Visit(*this); - } - - void AstRecursiveVisitor::Visit(BinaryExpression& node) - { - node.left->Visit(*this); - node.right->Visit(*this); - } - - void AstRecursiveVisitor::Visit(CallFunctionExpression& node) - { - for (auto& param : node.parameters) - param->Visit(*this); - } - - void AstRecursiveVisitor::Visit(CallMethodExpression& node) - { - node.object->Visit(*this); - - for (auto& param : node.parameters) - param->Visit(*this); - } - - void AstRecursiveVisitor::Visit(CastExpression& node) - { - for (auto& expr : node.expressions) - { - if (!expr) - break; - - expr->Visit(*this); - } - } - - void AstRecursiveVisitor::Visit(ConditionalExpression& node) - { - node.truePath->Visit(*this); - node.falsePath->Visit(*this); - } - - void AstRecursiveVisitor::Visit(ConstantValueExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(ConstantExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(FunctionExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(IdentifierExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(IntrinsicExpression& node) - { - for (auto& param : node.parameters) - param->Visit(*this); - } - - void AstRecursiveVisitor::Visit(IntrinsicFunctionExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(StructTypeExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(SwizzleExpression& node) - { - if (node.expression) - node.expression->Visit(*this); - } - - void AstRecursiveVisitor::Visit(TypeExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(VariableValueExpression& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(UnaryExpression& node) - { - if (node.expression) - node.expression->Visit(*this); - } - - void AstRecursiveVisitor::Visit(BranchStatement& node) - { - for (auto& cond : node.condStatements) - { - cond.condition->Visit(*this); - cond.statement->Visit(*this); - } - - if (node.elseStatement) - node.elseStatement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(ConditionalStatement& node) - { - node.statement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(DeclareAliasStatement& node) - { - if (node.expression) - node.expression->Visit(*this); - } - - void AstRecursiveVisitor::Visit(DeclareConstStatement& node) - { - if (node.expression) - node.expression->Visit(*this); - } - - void AstRecursiveVisitor::Visit(DeclareExternalStatement& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(DeclareFunctionStatement& node) - { - for (auto& statement : node.statements) - statement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(DeclareOptionStatement& node) - { - if (node.defaultValue) - node.defaultValue->Visit(*this); - } - - void AstRecursiveVisitor::Visit(DeclareStructStatement& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(DeclareVariableStatement& node) - { - if (node.initialExpression) - node.initialExpression->Visit(*this); - } - - void AstRecursiveVisitor::Visit(DiscardStatement& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(ExpressionStatement& node) - { - node.expression->Visit(*this); - } - - void AstRecursiveVisitor::Visit(ForStatement& node) - { - if (node.fromExpr) - node.fromExpr->Visit(*this); - - if (node.toExpr) - node.toExpr->Visit(*this); - - if (node.stepExpr) - node.stepExpr->Visit(*this); - - if (node.statement) - node.statement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(ForEachStatement& node) - { - if (node.expression) - node.expression->Visit(*this); - - if (node.statement) - node.statement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(ImportStatement& /*node*/) - { - /* nothing to do */ - } - - void AstRecursiveVisitor::Visit(MultiStatement& node) - { - for (auto& statement : node.statements) - statement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(NoOpStatement& /*node*/) - { - /* Nothing to do */ - } - - void AstRecursiveVisitor::Visit(ReturnStatement& node) - { - if (node.returnExpr) - node.returnExpr->Visit(*this); - } - - void AstRecursiveVisitor::Visit(ScopedStatement& node) - { - if (node.statement) - node.statement->Visit(*this); - } - - void AstRecursiveVisitor::Visit(WhileStatement& node) - { - if (node.condition) - node.condition->Visit(*this); - - if (node.body) - node.body->Visit(*this); - } -} diff --git a/src/Nazara/Shader/Ast/AstReflect.cpp b/src/Nazara/Shader/Ast/AstReflect.cpp deleted file mode 100644 index c4c7afe35..000000000 --- a/src/Nazara/Shader/Ast/AstReflect.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - void AstReflect::Reflect(Statement& statement, const Callbacks& callbacks) - { - m_callbacks = &callbacks; - statement.Visit(*this); - } - - void AstReflect::Visit(DeclareAliasStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onAliasDeclaration) - m_callbacks->onAliasDeclaration(node); - - if (m_callbacks->onAliasIndex && node.aliasIndex) - m_callbacks->onAliasIndex(node.name, *node.aliasIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(DeclareConstStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onConstDeclaration) - m_callbacks->onConstDeclaration(node); - - if (m_callbacks->onConstIndex && node.constIndex) - m_callbacks->onConstIndex(node.name, *node.constIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(DeclareExternalStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onExternalDeclaration) - m_callbacks->onExternalDeclaration(node); - - if (m_callbacks->onVariableIndex) - { - for (const auto& extVar : node.externalVars) - { - if (extVar.varIndex) - m_callbacks->onVariableIndex(extVar.name, *extVar.varIndex, extVar.sourceLocation); - } - } - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(DeclareFunctionStatement& node) - { - assert(m_callbacks); - - if (m_callbacks->onFunctionDeclaration) - m_callbacks->onFunctionDeclaration(node); - - if (node.funcIndex && m_callbacks->onFunctionIndex) - m_callbacks->onFunctionIndex(node.name, *node.funcIndex, node.sourceLocation); - - if (m_callbacks->onEntryPointDeclaration) - { - if (!node.entryStage.HasValue()) - return; - - m_callbacks->onEntryPointDeclaration(node.entryStage.GetResultingValue(), node.name); - } - - if (m_callbacks->onVariableIndex) - { - for (const auto& parameter : node.parameters) - { - if (parameter.varIndex) - m_callbacks->onVariableIndex(parameter.name, *parameter.varIndex, parameter.sourceLocation); - } - } - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(DeclareOptionStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onOptionDeclaration) - m_callbacks->onOptionDeclaration(node); - - if (m_callbacks->onOptionIndex && node.optIndex) - m_callbacks->onOptionIndex(node.optName, *node.optIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(DeclareStructStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onStructDeclaration) - m_callbacks->onStructDeclaration(node); - - if (m_callbacks->onStructIndex && node.structIndex) - m_callbacks->onStructIndex(node.description.name, *node.structIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(DeclareVariableStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onVariableDeclaration) - m_callbacks->onVariableDeclaration(node); - - if (m_callbacks->onVariableIndex && node.varIndex) - m_callbacks->onVariableIndex(node.varName, *node.varIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(ForStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onVariableIndex && node.varIndex) - m_callbacks->onVariableIndex(node.varName, *node.varIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } - - void AstReflect::Visit(ForEachStatement& node) - { - assert(m_callbacks); - if (m_callbacks->onVariableIndex && node.varIndex) - m_callbacks->onVariableIndex(node.varName, *node.varIndex, node.sourceLocation); - - AstRecursiveVisitor::Visit(node); - } -} diff --git a/src/Nazara/Shader/Ast/AstSerializer.cpp b/src/Nazara/Shader/Ast/AstSerializer.cpp deleted file mode 100644 index 2415d9bb0..000000000 --- a/src/Nazara/Shader/Ast/AstSerializer.cpp +++ /dev/null @@ -1,1009 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - namespace - { - constexpr UInt32 s_shaderAstMagicNumber = 0x4E534852; - constexpr UInt32 s_shaderAstCurrentVersion = 1; - - class ShaderSerializerVisitor : public AstExpressionVisitor, public AstStatementVisitor - { - public: - ShaderSerializerVisitor(AstSerializerBase& serializer) : - m_serializer(serializer) - { - } - -#define NAZARA_SHADERAST_EXPRESSION(Node) void Visit(Node& node) override \ - { \ - m_serializer.Serialize(node); \ - m_serializer.SerializeNodeCommon(node); \ - m_serializer.SerializeExpressionCommon(node); \ - } - -#define NAZARA_SHADERAST_STATEMENT(Node) void Visit(Node& node) override \ - { \ - m_serializer.Serialize(node); \ - m_serializer.SerializeNodeCommon(node); \ - } -#include - - private: - AstSerializerBase& m_serializer; - }; - } - - void AstSerializerBase::Serialize(AccessIdentifierExpression& node) - { - Node(node.expr); - - Container(node.identifiers); - for (auto& identifier : node.identifiers) - { - Value(identifier.identifier); - SourceLoc(identifier.sourceLocation); - } - } - - void AstSerializerBase::Serialize(AccessIndexExpression& node) - { - Node(node.expr); - - Container(node.indices); - for (auto& identifier : node.indices) - Node(identifier); - } - - void AstSerializerBase::Serialize(AliasValueExpression& node) - { - SizeT(node.aliasId); - } - - void AstSerializerBase::Serialize(AssignExpression& node) - { - Enum(node.op); - Node(node.left); - Node(node.right); - } - - void AstSerializerBase::Serialize(BinaryExpression& node) - { - Enum(node.op); - Node(node.left); - Node(node.right); - } - - void AstSerializerBase::Serialize(CallFunctionExpression& node) - { - Node(node.targetFunction); - - Container(node.parameters); - for (auto& param : node.parameters) - Node(param); - } - - void AstSerializerBase::Serialize(CallMethodExpression& node) - { - Node(node.object); - Value(node.methodName); - - Container(node.parameters); - for (auto& param : node.parameters) - Node(param); - } - - void AstSerializerBase::Serialize(CastExpression& node) - { - ExprValue(node.targetType); - for (auto& expr : node.expressions) - Node(expr); - } - - void AstSerializerBase::Serialize(ConstantExpression& node) - { - SizeT(node.constantId); - } - - void AstSerializerBase::Serialize(ConditionalExpression& node) - { - Node(node.condition); - Node(node.truePath); - Node(node.falsePath); - } - - void AstSerializerBase::Serialize(ConstantValueExpression& node) - { - UInt32 typeIndex; - if (IsWriting()) - typeIndex = UInt32(node.value.index()); - - Value(typeIndex); - - // Waiting for template lambda in C++20 - auto SerializeValue = [&](auto dummyType) - { - using T = std::decay_t; - - auto& value = (IsWriting()) ? std::get(node.value) : node.value.emplace(); - Value(value); - }; - - static_assert(std::variant_size_v == 12); - switch (typeIndex) - { - case 0: break; - case 1: SerializeValue(bool()); break; - case 2: SerializeValue(float()); break; - case 3: SerializeValue(Int32()); break; - case 4: SerializeValue(UInt32()); break; - case 5: SerializeValue(Vector2f()); break; - case 6: SerializeValue(Vector3f()); break; - case 7: SerializeValue(Vector4f()); break; - case 8: SerializeValue(Vector2i32()); break; - case 9: SerializeValue(Vector3i32()); break; - case 10: SerializeValue(Vector4i32()); break; - case 11: SerializeValue(std::string()); break; - default: throw std::runtime_error("unexpected data type"); - } - } - - void AstSerializerBase::Serialize(IdentifierExpression& node) - { - Value(node.identifier); - } - - void AstSerializerBase::Serialize(IntrinsicExpression& node) - { - Enum(node.intrinsic); - Container(node.parameters); - for (auto& param : node.parameters) - Node(param); - } - - void AstSerializerBase::Serialize(IntrinsicFunctionExpression& node) - { - SizeT(node.intrinsicId); - } - - void AstSerializerBase::Serialize(StructTypeExpression& node) - { - SizeT(node.structTypeId); - } - - void AstSerializerBase::Serialize(TypeExpression& node) - { - SizeT(node.typeId); - } - - void AstSerializerBase::Serialize(FunctionExpression& node) - { - SizeT(node.funcId); - } - - void AstSerializerBase::Serialize(SwizzleExpression& node) - { - SizeT(node.componentCount); - Node(node.expression); - - for (std::size_t i = 0; i < node.componentCount; ++i) - Enum(node.components[i]); - } - - void AstSerializerBase::Serialize(VariableValueExpression& node) - { - SizeT(node.variableId); - } - - void AstSerializerBase::Serialize(UnaryExpression& node) - { - Enum(node.op); - Node(node.expression); - } - - void AstSerializerBase::Serialize(BranchStatement& node) - { - Container(node.condStatements); - for (auto& condStatement : node.condStatements) - { - Node(condStatement.condition); - Node(condStatement.statement); - } - - Node(node.elseStatement); - Value(node.isConst); - } - - void AstSerializerBase::Serialize(ConditionalStatement& node) - { - Node(node.condition); - Node(node.statement); - } - - void AstSerializerBase::Serialize(DeclareAliasStatement& node) - { - OptVal(node.aliasIndex); - Value(node.name); - Node(node.expression); - } - - void AstSerializerBase::Serialize(DeclareConstStatement& node) - { - OptVal(node.constIndex); - Value(node.name); - ExprValue(node.type); - Node(node.expression); - } - - void AstSerializerBase::Serialize(DeclareExternalStatement& node) - { - ExprValue(node.bindingSet); - - Container(node.externalVars); - for (auto& extVar : node.externalVars) - { - Value(extVar.name); - OptVal(extVar.varIndex); - ExprValue(extVar.type); - ExprValue(extVar.bindingIndex); - ExprValue(extVar.bindingSet); - SourceLoc(extVar.sourceLocation); - } - } - - void AstSerializerBase::Serialize(DeclareFunctionStatement& node) - { - Value(node.name); - ExprValue(node.returnType); - ExprValue(node.depthWrite); - ExprValue(node.earlyFragmentTests); - ExprValue(node.entryStage); - ExprValue(node.isExported); - OptVal(node.funcIndex); - - Container(node.parameters); - for (auto& parameter : node.parameters) - { - Value(parameter.name); - ExprValue(parameter.type); - OptVal(parameter.varIndex); - SourceLoc(parameter.sourceLocation); - } - - Container(node.statements); - for (auto& statement : node.statements) - Node(statement); - } - - void AstSerializerBase::Serialize(DeclareOptionStatement& node) - { - OptVal(node.optIndex); - Value(node.optName); - ExprValue(node.optType); - Node(node.defaultValue); - } - - void AstSerializerBase::Serialize(DeclareStructStatement& node) - { - OptVal(node.structIndex); - ExprValue(node.isExported); - - Value(node.description.name); - ExprValue(node.description.layout); - - Container(node.description.members); - for (auto& member : node.description.members) - { - Value(member.name); - ExprValue(member.type); - ExprValue(member.builtin); - ExprValue(member.cond); - ExprValue(member.locationIndex); - SourceLoc(member.sourceLocation); - } - } - - void AstSerializerBase::Serialize(DeclareVariableStatement& node) - { - OptVal(node.varIndex); - Value(node.varName); - ExprValue(node.varType); - Node(node.initialExpression); - } - - void AstSerializerBase::Serialize(DiscardStatement& /*node*/) - { - /* Nothing to do */ - } - - void AstSerializerBase::Serialize(ExpressionStatement& node) - { - Node(node.expression); - } - - void AstSerializerBase::Serialize(ForStatement& node) - { - ExprValue(node.unroll); - Value(node.varName); - Node(node.fromExpr); - Node(node.toExpr); - Node(node.stepExpr); - Node(node.statement); - } - - void AstSerializerBase::Serialize(ForEachStatement& node) - { - ExprValue(node.unroll); - Value(node.varName); - Node(node.expression); - Node(node.statement); - } - - void AstSerializerBase::Serialize(ImportStatement& node) - { - Value(node.moduleName); - } - - void AstSerializerBase::Serialize(MultiStatement& node) - { - Container(node.statements); - for (auto& statement : node.statements) - Node(statement); - } - - void AstSerializerBase::Serialize(NoOpStatement& /*node*/) - { - /* Nothing to do */ - } - - void AstSerializerBase::Serialize(ReturnStatement& node) - { - Node(node.returnExpr); - } - - void AstSerializerBase::Serialize(ScopedStatement& node) - { - Node(node.statement); - } - - void AstSerializerBase::Serialize(WhileStatement& node) - { - ExprValue(node.unroll); - Node(node.condition); - Node(node.body); - } - - void AstSerializerBase::SerializeExpressionCommon(Expression& expr) - { - OptType(expr.cachedExpressionType); - } - - void AstSerializerBase::SerializeNodeCommon(ShaderAst::Node& node) - { - SourceLoc(node.sourceLocation); - } - - void ShaderAstSerializer::Serialize(ModulePtr& module) - { - m_stream << s_shaderAstMagicNumber << s_shaderAstCurrentVersion; - - SerializeModule(module); - - m_stream.FlushBits(); - } - - bool ShaderAstSerializer::IsWriting() const - { - return true; - } - - void ShaderAstSerializer::Node(ExpressionPtr& node) - { - NodeType nodeType = (node) ? node->GetType() : NodeType::None; - m_stream << static_cast(nodeType); - - if (node) - { - ShaderSerializerVisitor visitor(*this); - node->Visit(visitor); - } - } - - void ShaderAstSerializer::Node(StatementPtr& node) - { - NodeType nodeType = (node) ? node->GetType() : NodeType::None; - m_stream << static_cast(nodeType); - - if (node) - { - ShaderSerializerVisitor visitor(*this); - node->Visit(visitor); - } - } - - void ShaderAstSerializer::SerializeModule(ModulePtr& module) - { - m_stream << module->metadata->moduleName; - m_stream << module->metadata->moduleId; - m_stream << module->metadata->shaderLangVersion; - - Container(module->importedModules); - for (auto& importedModule : module->importedModules) - { - Value(importedModule.identifier); - SerializeModule(importedModule.module); - } - - ShaderSerializerVisitor visitor(*this); - module->rootNode->Visit(visitor); - } - - void ShaderAstSerializer::SharedString(std::shared_ptr& val) - { - bool hasValue = (val != nullptr); - Value(hasValue); - - if (hasValue) - { - auto it = m_stringIndices.find(*val); - bool newString = (it == m_stringIndices.end()); - Value(newString); - - if (newString) - { - Value(const_cast(*val)); //< won't be used for writing - m_stringIndices.emplace(*val, SafeCast(m_stringIndices.size())); - } - else - Value(it->second); //< string index - } - } - - void ShaderAstSerializer::Type(ExpressionType& type) - { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - m_stream << UInt8(0); - else if constexpr (std::is_same_v) - { - m_stream << UInt8(1); - Enum(arg); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(3); - SizeT(arg.columnCount); - SizeT(arg.rowCount); - Enum(arg.type); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(4); - Enum(arg.dim); - Enum(arg.sampledType); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(5); - SizeT(arg.structIndex); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(6); - SizeT(arg.containedType.structIndex); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(7); - SizeT(arg.componentCount); - Enum(arg.type); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(8); - Value(arg.length); - Type(arg.containedType->type); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(9); - SizeT(arg.typeIndex); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(10); - SizeT(arg.funcIndex); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(11); - Enum(arg.intrinsic); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(12); - Type(arg.objectType->type); - SizeT(arg.methodIndex); - } - else if constexpr (std::is_same_v) - { - m_stream << UInt8(13); - SizeT(arg.aliasIndex); - Type(arg.targetType->type); - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, type); - } - - void ShaderAstSerializer::Value(bool& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(float& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(std::string& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Int32& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Vector2f& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Vector3f& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Vector4f& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Vector2i32& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Vector3i32& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(Vector4i32& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(UInt8& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(UInt16& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(UInt32& val) - { - m_stream << val; - } - - void ShaderAstSerializer::Value(UInt64& val) - { - m_stream << val; - } - - ModulePtr ShaderAstUnserializer::Unserialize() - { - UInt32 magicNumber; - UInt32 version; - m_stream >> magicNumber; - if (magicNumber != s_shaderAstMagicNumber) - throw std::runtime_error("invalid shader file"); - - m_stream >> version; - if (version > s_shaderAstCurrentVersion) - throw std::runtime_error("unsupported version"); - - ModulePtr module; - SerializeModule(module); - - return module; - } - - bool ShaderAstUnserializer::IsWriting() const - { - return false; - } - - void ShaderAstUnserializer::Node(ExpressionPtr& node) - { - Int32 nodeTypeInt; - m_stream >> nodeTypeInt; - - if (nodeTypeInt < static_cast(NodeType::None) || nodeTypeInt > static_cast(NodeType::Max)) - throw std::runtime_error("invalid node type"); - - NodeType nodeType = static_cast(nodeTypeInt); - switch (nodeType) - { - case NodeType::None: break; - -#define NAZARA_SHADERAST_EXPRESSION(Node) case NodeType:: Node : node = std::make_unique(); break; -#include - - default: throw std::runtime_error("unexpected node type"); - } - - if (node) - { - ShaderSerializerVisitor visitor(*this); - node->Visit(visitor); - } - } - - void ShaderAstUnserializer::Node(StatementPtr& node) - { - Int32 nodeTypeInt; - m_stream >> nodeTypeInt; - - if (nodeTypeInt < static_cast(NodeType::None) || nodeTypeInt > static_cast(NodeType::Max)) - throw std::runtime_error("invalid node type"); - - NodeType nodeType = static_cast(nodeTypeInt); - switch (nodeType) - { - case NodeType::None: break; - -#define NAZARA_SHADERAST_STATEMENT(Node) case NodeType:: Node : node = std::make_unique(); break; -#include - - default: throw std::runtime_error("unexpected node type"); - } - - if (node) - { - ShaderSerializerVisitor visitor(*this); - node->Visit(visitor); - } - } - - void ShaderAstUnserializer::SerializeModule(ModulePtr& module) - { - std::shared_ptr metadata = std::make_shared(); - m_stream >> metadata->moduleName; - m_stream >> metadata->moduleId; - m_stream >> metadata->shaderLangVersion; - - std::vector importedModules; - Container(importedModules); - for (auto& importedModule : importedModules) - { - Value(const_cast(importedModule.identifier)); //< not used for writing - SerializeModule(importedModule.module); - } - - MultiStatementPtr rootNode = std::make_unique(); - - ShaderSerializerVisitor visitor(*this); - rootNode->Visit(visitor); - - module = std::make_shared(std::move(metadata), std::move(rootNode), std::move(importedModules)); - } - - void ShaderAstUnserializer::SharedString(std::shared_ptr& val) - { - bool hasValue; - Value(hasValue); - - if (hasValue) - { - bool newString; - Value(newString); - - if (newString) - { - std::string newStr; - Value(newStr); - - val = std::make_shared(std::move(newStr)); - m_strings.emplace_back(val); - } - else - { - UInt32 strIndex; - Value(strIndex); - - assert(strIndex < m_strings.size()); - val = m_strings[strIndex]; - } - } - } - - void ShaderAstUnserializer::Type(ExpressionType& type) - { - UInt8 typeIndex; - Value(typeIndex); - - switch (typeIndex) - { - case 0: //< NoType - type = NoType{}; - break; - - case 1: //< PrimitiveType - { - PrimitiveType primitiveType; - Enum(primitiveType); - - type = primitiveType; - break; - } - - case 3: //< MatrixType - { - std::size_t columnCount, rowCount; - PrimitiveType primitiveType; - SizeT(columnCount); - SizeT(rowCount); - Enum(primitiveType); - - type = MatrixType { - columnCount, - rowCount, - primitiveType - }; - break; - } - - case 4: //< SamplerType - { - ImageType dim; - PrimitiveType sampledType; - Enum(dim); - Enum(sampledType); - - type = SamplerType { - dim, - sampledType - }; - break; - } - - case 5: //< StructType - { - UInt32 structIndex; - Value(structIndex); - - type = StructType{ - structIndex - }; - break; - } - - case 6: //< UniformType - { - std::size_t structIndex; - SizeT(structIndex); - - type = UniformType { - StructType { - structIndex - } - }; - break; - } - - case 7: //< VectorType - { - std::size_t componentCount; - PrimitiveType componentType; - SizeT(componentCount); - Enum(componentType); - - type = VectorType{ - componentCount, - componentType - }; - break; - } - - case 8: //< ArrayType - { - UInt32 length; - ExpressionType containedType; - Value(length); - Type(containedType); - - ArrayType arrayType; - arrayType.length = length; - arrayType.containedType = std::make_unique(); - arrayType.containedType->type = std::move(containedType); - - type = std::move(arrayType); - break; - } - - case 9: //< Type - { - std::size_t containedTypeIndex; - SizeT(containedTypeIndex); - - type = ShaderAst::Type{ - containedTypeIndex - }; - break; - } - - case 10: //< FunctionType - { - std::size_t funcIndex; - SizeT(funcIndex); - - type = FunctionType { - funcIndex - }; - break; - } - - case 11: //< IntrinsicFunctionType - { - IntrinsicType intrinsicType; - Enum(intrinsicType); - - type = IntrinsicFunctionType { - intrinsicType - }; - break; - } - - case 12: //< MethodType - { - ExpressionType objectType; - Type(objectType); - - std::size_t methodIndex; - SizeT(methodIndex); - - MethodType methodType; - methodType.objectType = std::make_unique(); - methodType.objectType->type = std::move(objectType); - methodType.methodIndex = methodIndex; - - type = std::move(methodType); - break; - } - - case 13: //< AliasType - { - std::size_t aliasIndex; - ExpressionType containedType; - SizeT(aliasIndex); - Type(containedType); - - AliasType aliasType; - aliasType.aliasIndex = aliasIndex; - aliasType.targetType = std::make_unique(); - aliasType.targetType->type = std::move(containedType); - - type = std::move(aliasType); - break; - } - - default: - break; - } - } - - void ShaderAstUnserializer::Value(bool& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(float& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(std::string& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Int32& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Vector2f& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Vector3f& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Vector4f& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Vector2i32& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Vector3i32& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(Vector4i32& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(UInt8& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(UInt16& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(UInt32& val) - { - m_stream >> val; - } - - void ShaderAstUnserializer::Value(UInt64& val) - { - m_stream >> val; - } - - - ByteArray SerializeShader(ModulePtr& module) - { - ByteArray byteArray; - ByteStream stream(&byteArray, OpenModeFlags(OpenMode::WriteOnly)); - - ShaderAstSerializer serializer(stream); - serializer.Serialize(module); - - return byteArray; - } - - ModulePtr UnserializeShader(ByteStream& stream) - { - ShaderAstUnserializer unserializer(stream); - return unserializer.Unserialize(); - } -} diff --git a/src/Nazara/Shader/Ast/AstStatementVisitor.cpp b/src/Nazara/Shader/Ast/AstStatementVisitor.cpp deleted file mode 100644 index 0f7fd6db6..000000000 --- a/src/Nazara/Shader/Ast/AstStatementVisitor.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - AstStatementVisitor::~AstStatementVisitor() = default; -} diff --git a/src/Nazara/Shader/Ast/AstStatementVisitorExcept.cpp b/src/Nazara/Shader/Ast/AstStatementVisitorExcept.cpp deleted file mode 100644 index 9b46f5bed..000000000 --- a/src/Nazara/Shader/Ast/AstStatementVisitorExcept.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ -#define NAZARA_SHADERAST_STATEMENT(Node) void AstStatementVisitorExcept::Visit(ShaderAst::Node& /*node*/) \ - { \ - throw std::runtime_error("unexpected " #Node " node"); \ - } -#include -} diff --git a/src/Nazara/Shader/Ast/AstUtils.cpp b/src/Nazara/Shader/Ast/AstUtils.cpp deleted file mode 100644 index c96726cae..000000000 --- a/src/Nazara/Shader/Ast/AstUtils.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - ExpressionCategory ShaderAstValueCategory::GetExpressionCategory(Expression& expression) - { - expression.Visit(*this); - return m_expressionCategory; - } - - void ShaderAstValueCategory::Visit(AccessIdentifierExpression& node) - { - node.expr->Visit(*this); - } - - void ShaderAstValueCategory::Visit(AccessIndexExpression& node) - { - node.expr->Visit(*this); - } - - void ShaderAstValueCategory::Visit(AliasValueExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(AssignExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(BinaryExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(CallFunctionExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(CallMethodExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(CastExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(ConditionalExpression& node) - { - node.truePath->Visit(*this); - ExpressionCategory trueExprCategory = m_expressionCategory; - - node.falsePath->Visit(*this); - ExpressionCategory falseExprCategory = m_expressionCategory; - - if (trueExprCategory == ExpressionCategory::RValue || falseExprCategory == ExpressionCategory::RValue) - m_expressionCategory = ExpressionCategory::RValue; - else - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(ConstantValueExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(ConstantExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(FunctionExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(IdentifierExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(IntrinsicExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } - - void ShaderAstValueCategory::Visit(IntrinsicFunctionExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(StructTypeExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(SwizzleExpression& node) - { - const ExpressionType* exprType = GetExpressionType(node); - assert(exprType); - - if (IsPrimitiveType(*exprType) && node.componentCount > 1) - // Swizzling more than a component on a primitive produces a rvalue (a.xxxx cannot be assigned) - m_expressionCategory = ExpressionCategory::RValue; - else - { - bool isRVaLue = false; - - std::array used; - used.fill(false); - - for (std::size_t i = 0; i < node.componentCount; ++i) - { - if (used[node.components[i]]) - { - // Swizzling the same component multiple times produces a rvalue (a.xx cannot be assigned) - isRVaLue = true; - break; - } - - used[node.components[i]] = true; - } - - if (isRVaLue) - m_expressionCategory = ExpressionCategory::RValue; - else - node.expression->Visit(*this); - } - } - - void ShaderAstValueCategory::Visit(TypeExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(VariableValueExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::LValue; - } - - void ShaderAstValueCategory::Visit(UnaryExpression& /*node*/) - { - m_expressionCategory = ExpressionCategory::RValue; - } -} diff --git a/src/Nazara/Shader/Ast/ConstantValue.cpp b/src/Nazara/Shader/Ast/ConstantValue.cpp deleted file mode 100644 index 2022a4aea..000000000 --- a/src/Nazara/Shader/Ast/ConstantValue.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz::ShaderAst -{ - ExpressionType GetConstantType(const ConstantValue& constant) - { - return std::visit([&](auto&& arg) -> ShaderAst::ExpressionType - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - return NoType{}; - else if constexpr (std::is_same_v) - return PrimitiveType::Boolean; - else if constexpr (std::is_same_v) - return PrimitiveType::Float32; - else if constexpr (std::is_same_v) - return PrimitiveType::Int32; - else if constexpr (std::is_same_v) - return PrimitiveType::UInt32; - else if constexpr (std::is_same_v) - return PrimitiveType::String; - else if constexpr (std::is_same_v) - return VectorType{ 2, PrimitiveType::Float32 }; - else if constexpr (std::is_same_v) - return VectorType{ 3, PrimitiveType::Float32 }; - else if constexpr (std::is_same_v) - return VectorType{ 4, PrimitiveType::Float32 }; - else if constexpr (std::is_same_v) - return VectorType{ 2, PrimitiveType::Int32 }; - else if constexpr (std::is_same_v) - return VectorType{ 3, PrimitiveType::Int32 }; - else if constexpr (std::is_same_v) - return VectorType{ 4, PrimitiveType::Int32 }; - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, constant); - } -} diff --git a/src/Nazara/Shader/Ast/DependencyCheckerVisitor.cpp b/src/Nazara/Shader/Ast/DependencyCheckerVisitor.cpp deleted file mode 100644 index c94d97c2d..000000000 --- a/src/Nazara/Shader/Ast/DependencyCheckerVisitor.cpp +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz::ShaderAst -{ - void DependencyCheckerVisitor::Register(Statement& statement, const Config& config) - { - m_config = config; - statement.Visit(*this); - } - - auto DependencyCheckerVisitor::GetContextUsageSet() -> UsageSet& - { - if (m_currentAliasDeclIndex) - return Retrieve(m_aliasUsages, *m_currentAliasDeclIndex); - else if (m_currentVariableDeclIndex) - return Retrieve(m_variableUsages, *m_currentVariableDeclIndex); - else - { - assert(m_currentFunctionIndex); - return Retrieve(m_functionUsages, *m_currentFunctionIndex); - } - } - - void DependencyCheckerVisitor::RegisterType(UsageSet& usageSet, const ExpressionType& exprType) - { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - usageSet.usedAliases.UnboundedSet(arg.aliasIndex); - else if constexpr (std::is_same_v) - usageSet.usedStructs.UnboundedSet(arg.structIndex); - else if constexpr (std::is_same_v) - usageSet.usedStructs.UnboundedSet(arg.containedType.structIndex); - - }, exprType); - } - - void DependencyCheckerVisitor::Resolve(const UsageSet& usageSet, bool allowUnknownId) - { - m_resolvedUsage.usedAliases |= usageSet.usedAliases; - m_resolvedUsage.usedFunctions |= usageSet.usedFunctions; - m_resolvedUsage.usedStructs |= usageSet.usedStructs; - m_resolvedUsage.usedVariables |= usageSet.usedVariables; - - for (std::size_t aliasIndex = usageSet.usedAliases.FindFirst(); aliasIndex != usageSet.usedAliases.npos; aliasIndex = usageSet.usedAliases.FindNext(aliasIndex)) - { - auto it = m_aliasUsages.find(aliasIndex); - if (it != m_aliasUsages.end()) - Resolve(it->second, allowUnknownId); - else if (!allowUnknownId) - throw std::runtime_error("unknown alias #" + std::to_string(aliasIndex)); - } - - for (std::size_t funcIndex = usageSet.usedFunctions.FindFirst(); funcIndex != usageSet.usedFunctions.npos; funcIndex = usageSet.usedFunctions.FindNext(funcIndex)) - { - auto it = m_functionUsages.find(funcIndex); - if (it != m_functionUsages.end()) - Resolve(it->second, allowUnknownId); - else if (!allowUnknownId) - throw std::runtime_error("unknown func #" + std::to_string(funcIndex)); - } - - for (std::size_t structIndex = usageSet.usedStructs.FindFirst(); structIndex != usageSet.usedStructs.npos; structIndex = usageSet.usedStructs.FindNext(structIndex)) - { - auto it = m_structUsages.find(structIndex); - if (it != m_structUsages.end()) - Resolve(it->second, allowUnknownId); - else if (!allowUnknownId) - throw std::runtime_error("unknown struct #" + std::to_string(structIndex)); - } - - for (std::size_t varIndex = usageSet.usedVariables.FindFirst(); varIndex != usageSet.usedVariables.npos; varIndex = usageSet.usedVariables.FindNext(varIndex)) - { - auto it = m_variableUsages.find(varIndex); - if (it != m_variableUsages.end()) - Resolve(it->second, allowUnknownId); - else if (!allowUnknownId) - throw std::runtime_error("unknown var #" + std::to_string(varIndex)); - } - } - - void DependencyCheckerVisitor::Visit(DeclareAliasStatement& node) - { - assert(node.aliasIndex); - assert(m_aliasUsages.find(*node.aliasIndex) == m_aliasUsages.end()); - m_aliasUsages.emplace(*node.aliasIndex, UsageSet{}); - - assert(node.aliasIndex); - m_currentAliasDeclIndex = *node.aliasIndex; - AstRecursiveVisitor::Visit(node); - m_currentAliasDeclIndex = {}; - } - - void DependencyCheckerVisitor::Visit(DeclareExternalStatement& node) - { - for (const auto& externalVar : node.externalVars) - { - assert(externalVar.varIndex); - std::size_t varIndex = *externalVar.varIndex; - - assert(m_variableUsages.find(varIndex) == m_variableUsages.end()); - UsageSet& usageSet = m_variableUsages[varIndex]; - - const auto& exprType = externalVar.type.GetResultingValue(); - RegisterType(usageSet, exprType); - - ++varIndex; - } - - AstRecursiveVisitor::Visit(node); - } - - void DependencyCheckerVisitor::Visit(DeclareFunctionStatement& node) - { - assert(node.funcIndex); - assert(m_functionUsages.find(*node.funcIndex) == m_functionUsages.end()); - UsageSet& usageSet = m_functionUsages[*node.funcIndex]; - - // Register struct used in parameters or return type - if (!node.parameters.empty()) - { - for (auto& parameter : node.parameters) - { - assert(parameter.varIndex); - - // Since parameters must always be defined, their type isn't a dependency of parameter variables - assert(m_variableUsages.find(*parameter.varIndex) == m_variableUsages.end()); - m_variableUsages.emplace(*parameter.varIndex, UsageSet{}); - - const auto& exprType = parameter.type.GetResultingValue(); - RegisterType(usageSet, exprType); - } - } - - if (node.returnType.HasValue()) - { - const auto& returnExprType = node.returnType.GetResultingValue(); - RegisterType(usageSet, returnExprType); - } - - if (node.entryStage.HasValue()) - { - ShaderStageType shaderStage = node.entryStage.GetResultingValue(); - if (m_config.usedShaderStages & shaderStage) - m_globalUsage.usedFunctions.UnboundedSet(*node.funcIndex); - } - - m_currentFunctionIndex = node.funcIndex; - AstRecursiveVisitor::Visit(node); - m_currentFunctionIndex = {}; - } - - void DependencyCheckerVisitor::Visit(DeclareStructStatement& node) - { - assert(node.structIndex); - assert(m_structUsages.find(*node.structIndex) == m_structUsages.end()); - UsageSet& usageSet = m_structUsages[*node.structIndex]; - - for (const auto& structMember : node.description.members) - { - const auto& memberExprType = structMember.type.GetResultingValue(); - RegisterType(usageSet, memberExprType); - } - - AstRecursiveVisitor::Visit(node); - } - - void DependencyCheckerVisitor::Visit(DeclareVariableStatement& node) - { - assert(node.varIndex); - assert(m_variableUsages.find(*node.varIndex) == m_variableUsages.end()); - UsageSet& usageSet = m_variableUsages[*node.varIndex]; - - const auto& varType = node.varType.GetResultingValue(); - RegisterType(usageSet, varType); - - m_currentVariableDeclIndex = node.varIndex; - AstRecursiveVisitor::Visit(node); - m_currentVariableDeclIndex = {}; - } - - void DependencyCheckerVisitor::Visit(AliasValueExpression& node) - { - UsageSet& usageSet = GetContextUsageSet(); - usageSet.usedAliases.UnboundedSet(node.aliasId); - } - - void DependencyCheckerVisitor::Visit(FunctionExpression& node) - { - UsageSet& usageSet = GetContextUsageSet(); - usageSet.usedFunctions.UnboundedSet(node.funcId); - } - - void DependencyCheckerVisitor::Visit(StructTypeExpression& node) - { - UsageSet& usageSet = GetContextUsageSet(); - usageSet.usedStructs.UnboundedSet(node.structTypeId); - } - - void DependencyCheckerVisitor::Visit(VariableValueExpression& node) - { - UsageSet& usageSet = GetContextUsageSet(); - usageSet.usedVariables.UnboundedSet(node.variableId); - } -} diff --git a/src/Nazara/Shader/Ast/EliminateUnusedPassVisitor.cpp b/src/Nazara/Shader/Ast/EliminateUnusedPassVisitor.cpp deleted file mode 100644 index 657a30362..000000000 --- a/src/Nazara/Shader/Ast/EliminateUnusedPassVisitor.cpp +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - struct EliminateUnusedPassVisitor::Context - { - const DependencyCheckerVisitor::UsageSet& usageSet; - }; - - ModulePtr EliminateUnusedPassVisitor::Process(const Module& shaderModule, const DependencyCheckerVisitor::UsageSet& usageSet) - { - auto rootNode = StaticUniquePointerCast(Process(*shaderModule.rootNode, usageSet)); - - return std::make_shared(shaderModule.metadata, std::move(rootNode), shaderModule.importedModules); - } - - StatementPtr EliminateUnusedPassVisitor::Process(Statement& statement, const DependencyCheckerVisitor::UsageSet& usageSet) - { - Context context{ - usageSet - }; - - m_context = &context; - CallOnExit onExit([this]() - { - m_context = nullptr; - }); - - return Clone(statement); - } - - StatementPtr EliminateUnusedPassVisitor::Clone(DeclareAliasStatement& node) - { - assert(node.aliasIndex); - if (!IsAliasUsed(*node.aliasIndex)) - return ShaderBuilder::NoOp(); - - return AstCloner::Clone(node); - } - - StatementPtr EliminateUnusedPassVisitor::Clone(DeclareExternalStatement& node) - { - bool isUsed = false; - for (const auto& externalVar : node.externalVars) - { - assert(externalVar.varIndex); - std::size_t varIndex = *externalVar.varIndex; - - if (IsVariableUsed(varIndex)) - { - isUsed = true; - break; - } - } - - if (!isUsed) - return ShaderBuilder::NoOp(); - - auto clonedNode = AstCloner::Clone(node); - - auto& externalStatement = static_cast(*clonedNode); - for (auto it = externalStatement.externalVars.begin(); it != externalStatement.externalVars.end(); ) - { - const auto& externalVar = *it; - assert(externalVar.varIndex); - std::size_t varIndex = *externalVar.varIndex; - - if (!IsVariableUsed(varIndex)) - it = externalStatement.externalVars.erase(it); - else - ++it; - } - - return clonedNode; - } - - StatementPtr EliminateUnusedPassVisitor::Clone(DeclareFunctionStatement& node) - { - assert(node.funcIndex); - if (!IsFunctionUsed(*node.funcIndex)) - return ShaderBuilder::NoOp(); - - return AstCloner::Clone(node); - } - - StatementPtr EliminateUnusedPassVisitor::Clone(DeclareStructStatement& node) - { - assert(node.structIndex); - if (!IsStructUsed(*node.structIndex)) - return ShaderBuilder::NoOp(); - - return AstCloner::Clone(node); - } - - StatementPtr EliminateUnusedPassVisitor::Clone(DeclareVariableStatement& node) - { - assert(node.varIndex); - if (!IsVariableUsed(*node.varIndex)) - return ShaderBuilder::NoOp(); - - return AstCloner::Clone(node); - } - - bool EliminateUnusedPassVisitor::IsAliasUsed(std::size_t aliasIndex) const - { - assert(m_context); - return m_context->usageSet.usedAliases.UnboundedTest(aliasIndex); - } - - bool EliminateUnusedPassVisitor::IsFunctionUsed(std::size_t funcIndex) const - { - assert(m_context); - return m_context->usageSet.usedFunctions.UnboundedTest(funcIndex); - } - - bool EliminateUnusedPassVisitor::IsStructUsed(std::size_t structIndex) const - { - assert(m_context); - return m_context->usageSet.usedStructs.UnboundedTest(structIndex); - } - - bool EliminateUnusedPassVisitor::IsVariableUsed(std::size_t varIndex) const - { - assert(m_context); - return m_context->usageSet.usedVariables.UnboundedTest(varIndex); - } -} diff --git a/src/Nazara/Shader/Ast/ExpressionType.cpp b/src/Nazara/Shader/Ast/ExpressionType.cpp deleted file mode 100644 index c500d6c25..000000000 --- a/src/Nazara/Shader/Ast/ExpressionType.cpp +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - AliasType::AliasType(const AliasType& alias) : - aliasIndex(alias.aliasIndex) - { - assert(alias.targetType); - targetType = std::make_unique(*alias.targetType); - } - - AliasType& AliasType::operator=(const AliasType& alias) - { - aliasIndex = alias.aliasIndex; - - assert(alias.targetType); - targetType = std::make_unique(*alias.targetType); - - return *this; - } - - bool AliasType::operator==(const AliasType& rhs) const - { - assert(targetType); - assert(rhs.targetType); - - if (aliasIndex != rhs.aliasIndex) - return false; - - if (targetType->type != rhs.targetType->type) - return false; - - return true; - } - - ArrayType::ArrayType(const ArrayType& array) : - length(array.length) - { - assert(array.containedType); - containedType = std::make_unique(*array.containedType); - } - - ArrayType& ArrayType::operator=(const ArrayType& array) - { - assert(array.containedType); - - containedType = std::make_unique(*array.containedType); - length = array.length; - - return *this; - } - - bool ArrayType::operator==(const ArrayType& rhs) const - { - assert(containedType); - assert(rhs.containedType); - - if (length != rhs.length) - return false; - - if (containedType->type != rhs.containedType->type) - return false; - - return true; - } - - - MethodType::MethodType(const MethodType& methodType) : - methodIndex(methodType.methodIndex) - { - assert(methodType.objectType); - objectType = std::make_unique(*methodType.objectType); - } - - MethodType& MethodType::operator=(const MethodType& methodType) - { - assert(methodType.objectType); - - methodIndex = methodType.methodIndex; - objectType = std::make_unique(*methodType.objectType); - - return *this; - } - - bool MethodType::operator==(const MethodType& rhs) const - { - assert(objectType); - assert(rhs.objectType); - return objectType->type == rhs.objectType->type && methodIndex == rhs.methodIndex; - } - - std::string ToString(const AliasType& type, const Stringifier& stringifier) - { - std::string str = "alias "; - if (stringifier.aliasStringifier) - str += stringifier.aliasStringifier(type.aliasIndex); - else - { - str += "#"; - str += std::to_string(type.aliasIndex); - } - - str += " -> "; - str += ToString(type.targetType->type); - - return str; - } - - std::string ToString(const ArrayType& type, const Stringifier& stringifier) - { - std::string str = "array["; - str += ToString(type.containedType->type, stringifier); - str += ", "; - str += std::to_string(type.length); - str += "]"; - - return str; - } - - std::string ToString(const ExpressionType& type, const Stringifier& stringifier) - { - return std::visit([&](auto&& arg) - { - return ToString(arg, stringifier); - }, type); - } - - std::string ToString(const FunctionType& /*type*/, const Stringifier& /*stringifier*/) - { - return ""; - } - - std::string ToString(const IntrinsicFunctionType& /*type*/, const Stringifier& /*stringifier*/) - { - return ""; - } - - std::string ToString(const MatrixType& type, const Stringifier& /*stringifier*/) - { - std::string str = "mat"; - if (type.columnCount == type.rowCount) - str += std::to_string(type.columnCount); - else - { - str += std::to_string(type.columnCount); - str += "x"; - str += std::to_string(type.rowCount); - } - - str += "["; - str += ToString(type.type); - str += "]"; - - return str; - } - - std::string ToString(const MethodType& type, const Stringifier& /*stringifier*/) - { - return "type) + " type>"; - } - - std::string ToString(NoType /*type*/, const Stringifier& /*stringifier*/) - { - return "()"; - } - - std::string ToString(PrimitiveType type, const Stringifier& /*stringifier*/) - { - switch (type) - { - case ShaderAst::PrimitiveType::Boolean: return "bool"; - case ShaderAst::PrimitiveType::Float32: return "f32"; - case ShaderAst::PrimitiveType::Int32: return "i32"; - case ShaderAst::PrimitiveType::UInt32: return "u32"; - case ShaderAst::PrimitiveType::String: return "string"; - } - - return ""; - } - - std::string ToString(const SamplerType& type, const Stringifier& /*stringifier*/) - { - std::string str = "sampler"; - - switch (type.dim) - { - case ImageType::E1D: str += "1D"; break; - case ImageType::E1D_Array: str += "1DArray"; break; - case ImageType::E2D: str += "2D"; break; - case ImageType::E2D_Array: str += "2DArray"; break; - case ImageType::E3D: str += "3D"; break; - case ImageType::Cubemap: str += "Cube"; break; - } - - str += "["; - str += ToString(type.sampledType); - str += "]"; - - return str; - } - - std::string ToString(const StructType& type, const Stringifier& stringifier) - { - if (stringifier.structStringifier) - return "struct " + stringifier.structStringifier(type.structIndex); - else - return "struct #" + std::to_string(type.structIndex); - } - - std::string ToString(const Type& type, const Stringifier& stringifier) - { - if (stringifier.typeStringifier) - return "type " + stringifier.typeStringifier(type.typeIndex); - else - return "type #" + std::to_string(type.typeIndex); - } - - std::string ToString(const UniformType& type, const Stringifier& stringifier) - { - std::string str = "uniform["; - str += ToString(type.containedType, stringifier); - str += "]"; - - return str; - } - - std::string ToString(const VectorType& type, const Stringifier& /*stringifier*/) - { - std::string str = "vec"; - str += std::to_string(type.componentCount); - str += "["; - str += ToString(type.type); - str += "]"; - - return str; - } -} diff --git a/src/Nazara/Shader/Ast/IndexRemapperVisitor.cpp b/src/Nazara/Shader/Ast/IndexRemapperVisitor.cpp deleted file mode 100644 index 733b2256a..000000000 --- a/src/Nazara/Shader/Ast/IndexRemapperVisitor.cpp +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - namespace - { - template void UniqueInsert(std::unordered_map& map, T key, U value) - { - assert(map.find(key) == map.end()); - map.emplace(std::move(key), std::move(value)); - } - } - - struct IndexRemapperVisitor::Context - { - const IndexRemapperVisitor::Options* options; - std::unordered_map newAliasIndices; - std::unordered_map newConstIndices; - std::unordered_map newFuncIndices; - std::unordered_map newStructIndices; - std::unordered_map newVarIndices; - }; - - StatementPtr IndexRemapperVisitor::Clone(Statement& statement, const Options& options) - { - assert(options.aliasIndexGenerator); - assert(options.constIndexGenerator); - assert(options.funcIndexGenerator); - assert(options.structIndexGenerator); - //assert(options.typeIndexGenerator); - assert(options.varIndexGenerator); - - Context context; - context.options = &options; - m_context = &context; - - return AstCloner::Clone(statement); - } - - StatementPtr IndexRemapperVisitor::Clone(DeclareAliasStatement& node) - { - DeclareAliasStatementPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->aliasIndex) - { - std::size_t newAliasIndex = m_context->options->aliasIndexGenerator(*clone->aliasIndex); - UniqueInsert(m_context->newAliasIndices, *clone->aliasIndex, newAliasIndex); - clone->aliasIndex = newAliasIndex; - } - else if (m_context->options->forceIndexGeneration) - clone->aliasIndex = m_context->options->aliasIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - StatementPtr IndexRemapperVisitor::Clone(DeclareConstStatement& node) - { - DeclareConstStatementPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->constIndex) - { - std::size_t newConstIndex = m_context->options->constIndexGenerator(*clone->constIndex); - UniqueInsert(m_context->newConstIndices, *clone->constIndex, newConstIndex); - clone->constIndex = newConstIndex; - } - else if (m_context->options->forceIndexGeneration) - clone->constIndex = m_context->options->constIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - StatementPtr IndexRemapperVisitor::Clone(DeclareExternalStatement& node) - { - DeclareExternalStatementPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - for (auto& extVar : clone->externalVars) - { - if (extVar.varIndex) - { - std::size_t newVarIndex = m_context->options->varIndexGenerator(*extVar.varIndex); - UniqueInsert(m_context->newVarIndices, *extVar.varIndex, newVarIndex); - extVar.varIndex = newVarIndex; - } - else if (m_context->options->forceIndexGeneration) - extVar.varIndex = m_context->options->varIndexGenerator(std::numeric_limits::max()); - } - - return clone; - } - - StatementPtr IndexRemapperVisitor::Clone(DeclareFunctionStatement& node) - { - DeclareFunctionStatementPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->funcIndex) - { - std::size_t newFuncIndex = m_context->options->funcIndexGenerator(*clone->funcIndex); - UniqueInsert(m_context->newFuncIndices, *clone->funcIndex, newFuncIndex); - clone->funcIndex = newFuncIndex; - } - else if (m_context->options->forceIndexGeneration) - clone->funcIndex = m_context->options->funcIndexGenerator(std::numeric_limits::max()); - - if (!clone->parameters.empty()) - { - for (auto& parameter : clone->parameters) - { - if (parameter.varIndex) - parameter.varIndex = Retrieve(m_context->newVarIndices, *parameter.varIndex); - else if (m_context->options->forceIndexGeneration) - parameter.varIndex = m_context->options->varIndexGenerator(std::numeric_limits::max()); - - HandleType(parameter.type); - } - } - - if (node.returnType.HasValue()) - HandleType(node.returnType); - - return clone; - } - - StatementPtr IndexRemapperVisitor::Clone(DeclareStructStatement& node) - { - DeclareStructStatementPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->structIndex) - { - std::size_t newStructIndex = m_context->options->structIndexGenerator(*clone->structIndex); - UniqueInsert(m_context->newStructIndices, *clone->structIndex, newStructIndex); - clone->structIndex = newStructIndex; - } - else if (m_context->options->forceIndexGeneration) - clone->structIndex = m_context->options->structIndexGenerator(std::numeric_limits::max()); - - for (auto& structMember : clone->description.members) - HandleType(structMember.type); - - return clone; - } - - StatementPtr IndexRemapperVisitor::Clone(DeclareVariableStatement& node) - { - DeclareVariableStatementPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->varIndex) - { - std::size_t newVarIndex = m_context->options->varIndexGenerator(*clone->varIndex); - UniqueInsert(m_context->newConstIndices, *clone->varIndex, newVarIndex); - clone->varIndex = newVarIndex; - } - else if (m_context->options->forceIndexGeneration) - clone->varIndex = m_context->options->varIndexGenerator(std::numeric_limits::max()); - - HandleType(node.varType); - - return clone; - } - - ExpressionPtr IndexRemapperVisitor::Clone(AliasValueExpression& node) - { - AliasValueExpressionPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->aliasId) - clone->aliasId = Retrieve(m_context->newAliasIndices, clone->aliasId); - else if (m_context->options->forceIndexGeneration) - clone->aliasId = m_context->options->aliasIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - ExpressionPtr IndexRemapperVisitor::Clone(ConstantExpression& node) - { - ConstantExpressionPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->constantId) - clone->constantId = Retrieve(m_context->newConstIndices, clone->constantId); - else if (m_context->options->forceIndexGeneration) - clone->constantId = m_context->options->constIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - ExpressionPtr IndexRemapperVisitor::Clone(FunctionExpression& node) - { - FunctionExpressionPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->funcId) - clone->funcId = Retrieve(m_context->newFuncIndices, clone->funcId); - else if (m_context->options->forceIndexGeneration) - clone->funcId = m_context->options->funcIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - ExpressionPtr IndexRemapperVisitor::Clone(StructTypeExpression& node) - { - StructTypeExpressionPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->structTypeId) - clone->structTypeId = Retrieve(m_context->newStructIndices, clone->structTypeId); - else if (m_context->options->forceIndexGeneration) - clone->structTypeId = m_context->options->structIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - ExpressionPtr IndexRemapperVisitor::Clone(VariableValueExpression& node) - { - VariableValueExpressionPtr clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->variableId) - clone->variableId = Retrieve(m_context->newVarIndices, clone->variableId); - else if (m_context->options->forceIndexGeneration) - clone->variableId = m_context->options->varIndexGenerator(std::numeric_limits::max()); - - return clone; - } - - void IndexRemapperVisitor::HandleType(ExpressionValue& exprType) - { - if (!exprType.IsResultingValue()) - return; - - const auto& resultingType = exprType.GetResultingValue(); - exprType = RemapType(resultingType); - } - - ExpressionType IndexRemapperVisitor::RemapType(const ExpressionType& exprType) - { - if (IsAliasType(exprType)) - { - const AliasType& aliasType = std::get(exprType); - - AliasType remappedAliasType; - remappedAliasType.aliasIndex = Retrieve(m_context->newAliasIndices, aliasType.aliasIndex); - remappedAliasType.targetType = std::make_unique(); - remappedAliasType.targetType->type = RemapType(aliasType.targetType->type); - - return remappedAliasType; - } - else if (IsArrayType(exprType)) - { - const ArrayType& arrayType = std::get(exprType); - - ArrayType remappedArrayType; - remappedArrayType.containedType = std::make_unique(); - remappedArrayType.containedType->type = RemapType(arrayType.containedType->type); - remappedArrayType.length = arrayType.length; - - return remappedArrayType; - } - else if (IsFunctionType(exprType)) - { - std::size_t newFuncIndex = Retrieve(m_context->newFuncIndices, std::get(exprType).funcIndex); - return FunctionType{ newFuncIndex }; - } - else if (IsMethodType(exprType)) - { - const MethodType& methodType = std::get(exprType); - - MethodType remappedMethodType; - remappedMethodType.methodIndex = methodType.methodIndex; - remappedMethodType.objectType = std::make_unique(); - remappedMethodType.objectType->type = RemapType(methodType.objectType->type); - - return remappedMethodType; - } - else if (IsStructType(exprType)) - { - std::size_t newStructIndex = Retrieve(m_context->newStructIndices, std::get(exprType).structIndex); - return StructType{ newStructIndex }; - } - else if (IsUniformType(exprType)) - { - UniformType uniformType; - uniformType.containedType.structIndex = Retrieve(m_context->newStructIndices, std::get(exprType).containedType.structIndex); - return uniformType; - } - else - return exprType; - } -} diff --git a/src/Nazara/Shader/Ast/Nodes.cpp b/src/Nazara/Shader/Ast/Nodes.cpp deleted file mode 100644 index 84fda1203..000000000 --- a/src/Nazara/Shader/Ast/Nodes.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - Node::~Node() = default; - -#define NAZARA_SHADERAST_NODE(Node) NodeType Node::GetType() const \ - { \ - return NodeType:: Node; \ - } -#include - -#define NAZARA_SHADERAST_EXPRESSION(Node) void Node::Visit(AstExpressionVisitor& visitor) \ - {\ - visitor.Visit(*this); \ - } - -#define NAZARA_SHADERAST_STATEMENT(Node) void Node::Visit(AstStatementVisitor& visitor) \ - {\ - visitor.Visit(*this); \ - } - -#include -} diff --git a/src/Nazara/Shader/Ast/SanitizeVisitor.cpp b/src/Nazara/Shader/Ast/SanitizeVisitor.cpp deleted file mode 100644 index d37924a22..000000000 --- a/src/Nazara/Shader/Ast/SanitizeVisitor.cpp +++ /dev/null @@ -1,4058 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderAst -{ - struct SanitizeVisitor::CurrentFunctionData - { - std::optional stageType; - Bitset<> calledFunctions; - DeclareFunctionStatement* statement; - FunctionFlags flags; - }; - - template - struct SanitizeVisitor::IdentifierList - { - Bitset availableIndices; - Bitset preregisteredIndices; - std::unordered_map values; - - void PreregisterIndex(std::size_t index, const ShaderLang::SourceLocation& sourceLocation) - { - if (index < availableIndices.GetSize()) - { - if (!availableIndices.Test(index) && !preregisteredIndices.UnboundedTest(index)) - throw ShaderLang::AstAlreadyUsedIndexPreregisterError{ sourceLocation, index }; - } - else if (index >= availableIndices.GetSize()) - availableIndices.Resize(index + 1, true); - - availableIndices.Set(index, false); - preregisteredIndices.UnboundedSet(index); - } - - template - std::size_t Register(U&& data, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - std::size_t dataIndex; - if (index.has_value()) - { - dataIndex = *index; - - if (dataIndex >= availableIndices.GetSize()) - availableIndices.Resize(dataIndex + 1, true); - else if (!availableIndices.Test(dataIndex)) - { - if (preregisteredIndices.UnboundedTest(dataIndex)) - preregisteredIndices.Reset(dataIndex); - else - throw ShaderLang::AstInvalidIndexError{ sourceLocation, dataIndex }; - } - } - else - dataIndex = RegisterNewIndex(false); - - assert(values.find(dataIndex) == values.end()); - - availableIndices.Set(dataIndex, false); - values.emplace(dataIndex, std::forward(data)); - return dataIndex; - } - - std::size_t RegisterNewIndex(bool preregister) - { - std::size_t index = availableIndices.FindFirst(); - if (index == availableIndices.npos) - { - index = availableIndices.GetSize(); - availableIndices.Resize(index + 1, true); - } - - availableIndices.Set(index, false); - - if (preregister) - preregisteredIndices.UnboundedSet(index); - - return index; - } - - T& Retrieve(std::size_t index, const ShaderLang::SourceLocation& sourceLocation) - { - auto it = values.find(index); - if (it == values.end()) - throw ShaderLang::AstInvalidIndexError{ sourceLocation, index }; - - return it->second; - } - - T* TryRetrieve(std::size_t index, const ShaderLang::SourceLocation& sourceLocation) - { - auto it = values.find(index); - if (it == values.end()) - { - if (!preregisteredIndices.UnboundedTest(index)) - throw ShaderLang::AstInvalidIndexError{ sourceLocation, index }; - - return nullptr; - } - - return &it->second; - } - }; - - struct SanitizeVisitor::Scope - { - std::size_t previousSize; - }; - - struct SanitizeVisitor::Environment - { - Uuid moduleId; - std::shared_ptr parentEnv; - std::vector identifiersInScope; - std::vector scopes; - }; - - struct SanitizeVisitor::NamedPartialType - { - std::string name; - PartialType type; - }; - - struct SanitizeVisitor::Context - { - struct ModuleData - { - std::unordered_map exportedSetByModule; - std::shared_ptr environment; - std::unique_ptr dependenciesVisitor; - }; - - struct PendingFunction - { - DeclareFunctionStatement* cloneNode; - const DeclareFunctionStatement* node; - }; - - struct UsedExternalData - { - bool isConditional; - }; - - static constexpr std::size_t ModuleIdSentinel = std::numeric_limits::max(); - - std::array entryFunctions = {}; - std::vector modules; - std::vector pendingFunctions; - std::vector* currentStatementList = nullptr; - std::unordered_map moduleByUuid; - std::unordered_map usedBindingIndexes; - std::unordered_map declaredExternalVar; - std::shared_ptr globalEnv; - std::shared_ptr currentEnv; - std::shared_ptr moduleEnv; - IdentifierList constantValues; - IdentifierList functions; - IdentifierList aliases; - IdentifierList intrinsics; - IdentifierList moduleIndices; - IdentifierList structs; - IdentifierList> types; - IdentifierList variableTypes; - ModulePtr currentModule; - Options options; - CurrentFunctionData* currentFunction = nullptr; - bool allowUnknownIdentifiers = false; - bool inConditionalStatement = false; - }; - - ModulePtr SanitizeVisitor::Sanitize(const Module& module, const Options& options, std::string* error) - { - ModulePtr clone = std::make_shared(module.metadata, module.importedModules); - - Context currentContext; - currentContext.options = options; - currentContext.currentModule = clone; - - m_context = ¤tContext; - CallOnExit resetContext([&] { m_context = nullptr; }); - - PreregisterIndices(module); - - // Register global env - m_context->globalEnv = std::make_shared(); - m_context->currentEnv = m_context->globalEnv; - RegisterBuiltin(); - - m_context->moduleEnv = std::make_shared(); - m_context->moduleEnv->moduleId = clone->metadata->moduleId; - m_context->moduleEnv->parentEnv = m_context->globalEnv; - - for (std::size_t moduleId = 0; moduleId < clone->importedModules.size(); ++moduleId) - { - auto importedModuleEnv = std::make_shared(); - importedModuleEnv->moduleId = clone->importedModules[moduleId].module->metadata->moduleId; - importedModuleEnv->parentEnv = m_context->globalEnv; - - m_context->currentEnv = importedModuleEnv; - - auto& importedModule = clone->importedModules[moduleId]; - importedModule.module->rootNode = SanitizeInternal(*importedModule.module->rootNode, error); - if (!importedModule.module->rootNode) - return {}; - - m_context->moduleByUuid[importedModule.module->metadata->moduleId] = moduleId; - auto& moduleData = m_context->modules.emplace_back(); - moduleData.environment = std::move(importedModuleEnv); - - m_context->currentEnv = m_context->globalEnv; - RegisterModule(importedModule.identifier, moduleId); - } - - m_context->currentEnv = m_context->moduleEnv; - - clone->rootNode = SanitizeInternal(*module.rootNode, error); - if (!clone->rootNode) - return {}; - - // Remove unused statements of imported modules - for (std::size_t moduleId = 0; moduleId < clone->importedModules.size(); ++moduleId) - { - auto& moduleData = m_context->modules[moduleId]; - auto& importedModule = clone->importedModules[moduleId]; - - if (moduleData.dependenciesVisitor) - { - moduleData.dependenciesVisitor->Resolve(true); //< allow unknown identifiers since we may be referencing other modules - - importedModule.module = EliminateUnusedPass(*importedModule.module, moduleData.dependenciesVisitor->GetUsage()); - } - } - - return clone; - } - - ExpressionValue SanitizeVisitor::CloneType(const ExpressionValue& exprType) - { - if (!exprType.HasValue()) - return {}; - - std::optional resolvedType = ResolveTypeExpr(exprType, false, {}); - if (!resolvedType.has_value()) - return AstCloner::CloneType(exprType); - - return std::move(resolvedType).value(); - } - - ExpressionPtr SanitizeVisitor::Clone(AccessIdentifierExpression& node) - { - if (node.identifiers.empty()) - throw ShaderLang::AstNoIdentifierError{ node.sourceLocation }; - - MandatoryExpr(node.expr, node.sourceLocation); - - // Handle module access (TODO: Add namespace expression?) - if (node.expr->GetType() == NodeType::IdentifierExpression && node.identifiers.size() == 1) - { - auto& identifierExpr = static_cast(*node.expr); - const IdentifierData* identifierData = FindIdentifier(identifierExpr.identifier); - if (identifierData && identifierData->category == IdentifierCategory::Module) - { - std::size_t moduleIndex = m_context->moduleIndices.Retrieve(identifierData->index, node.sourceLocation); - - const auto& env = *m_context->modules[moduleIndex].environment; - identifierData = FindIdentifier(env, node.identifiers.front().identifier); - if (identifierData) - return HandleIdentifier(identifierData, node.identifiers.front().sourceLocation); - } - } - - ExpressionPtr indexedExpr = CloneExpression(node.expr); - for (const auto& identifierEntry : node.identifiers) - { - if (identifierEntry.identifier.empty()) - throw ShaderLang::AstEmptyIdentifierError{ identifierEntry.sourceLocation }; - - const ExpressionType* exprType = GetExpressionType(*indexedExpr); - if (!exprType) - return AstCloner::Clone(node); //< unresolved type - - const ExpressionType& resolvedType = ResolveAlias(*exprType); - // TODO: Add proper support for methods - if (IsSamplerType(resolvedType)) - { - if (identifierEntry.identifier == "Sample") - { - // TODO: Add a MethodExpression? - auto identifierExpr = std::make_unique(); - identifierExpr->expr = std::move(indexedExpr); - identifierExpr->identifiers.emplace_back().identifier = identifierEntry.identifier; - - MethodType methodType; - methodType.methodIndex = 0; //< FIXME - methodType.objectType = std::make_unique(); - methodType.objectType->type = resolvedType; - - identifierExpr->cachedExpressionType = std::move(methodType); - indexedExpr = std::move(identifierExpr); - } - else - throw ShaderLang::CompilerUnknownMethodError{ identifierEntry.sourceLocation }; - } - else if (IsStructType(resolvedType)) - { - std::size_t structIndex = ResolveStruct(resolvedType, indexedExpr->sourceLocation); - const StructDescription* s = m_context->structs.Retrieve(structIndex, indexedExpr->sourceLocation); - - // Retrieve member index (not counting disabled fields) - Int32 fieldIndex = 0; - const StructDescription::StructMember* fieldPtr = nullptr; - for (const auto& field : s->members) - { - if (field.cond.HasValue()) - { - if (!field.cond.IsResultingValue()) - { - if (m_context->options.allowPartialSanitization) - return AstCloner::Clone(node); //< unresolved - - throw ShaderLang::CompilerConstantExpressionRequiredError{ field.cond.GetExpression()->sourceLocation }; - } - else if (!field.cond.GetResultingValue()) - continue; - } - - if (field.name == identifierEntry.identifier) - { - fieldPtr = &field; - break; - } - - fieldIndex++; - } - - if (!fieldPtr) - { - if (s->isConditional) - return AstCloner::Clone(node); //< unresolved - - throw ShaderLang::CompilerUnknownFieldError{ indexedExpr->sourceLocation, identifierEntry.identifier }; - } - - if (m_context->options.useIdentifierAccessesForStructs) - { - // Use a AccessIdentifierExpression - AccessIdentifierExpression* accessIdentifierPtr; - if (indexedExpr->GetType() != NodeType::AccessIdentifierExpression) - { - std::unique_ptr accessIndex = std::make_unique(); - accessIndex->sourceLocation = indexedExpr->sourceLocation; - accessIndex->expr = std::move(indexedExpr); - - accessIdentifierPtr = accessIndex.get(); - indexedExpr = std::move(accessIndex); - } - else - { - accessIdentifierPtr = static_cast(indexedExpr.get()); - accessIdentifierPtr->sourceLocation.ExtendToRight(indexedExpr->sourceLocation); - } - - accessIdentifierPtr->cachedExpressionType = ResolveTypeExpr(fieldPtr->type, false, identifierEntry.sourceLocation); - - auto& newIdentifierEntry = accessIdentifierPtr->identifiers.emplace_back(); - newIdentifierEntry.identifier = fieldPtr->name; - newIdentifierEntry.sourceLocation = indexedExpr->sourceLocation; - } - else - { - // Transform to AccessIndexExpression - std::unique_ptr accessIndex = std::make_unique(); - accessIndex->sourceLocation = indexedExpr->sourceLocation; - accessIndex->expr = std::move(indexedExpr); - accessIndex->indices.push_back(ShaderBuilder::Constant(fieldIndex)); - accessIndex->cachedExpressionType = ResolveTypeExpr(fieldPtr->type, false, identifierEntry.sourceLocation); - - indexedExpr = std::move(accessIndex); - } - } - else if (IsPrimitiveType(resolvedType) || IsVectorType(resolvedType)) - { - // Swizzle expression - std::size_t swizzleComponentCount = identifierEntry.identifier.size(); - if (swizzleComponentCount > 4) - throw ShaderLang::CompilerInvalidSwizzleError{ identifierEntry.sourceLocation }; - - if (m_context->options.removeScalarSwizzling && IsPrimitiveType(resolvedType)) - { - for (std::size_t j = 0; j < swizzleComponentCount; ++j) - { - if (ToSwizzleIndex(identifierEntry.identifier[j], identifierEntry.sourceLocation) != 0) - throw ShaderLang::CompilerInvalidScalarSwizzleError{ identifierEntry.sourceLocation }; - } - - if (swizzleComponentCount == 1) - continue; //< ignore this swizzle (a.x == a) - - // Use a Cast expression to replace swizzle - indexedExpr = CacheResult(std::move(indexedExpr)); //< Since we are going to use a value multiple times, cache it if required - - PrimitiveType baseType; - if (IsVectorType(resolvedType)) - baseType = std::get(resolvedType).type; - else - baseType = std::get(resolvedType); - - auto cast = std::make_unique(); - cast->targetType = ExpressionType{ VectorType{ swizzleComponentCount, baseType } }; - for (std::size_t j = 0; j < swizzleComponentCount; ++j) - cast->expressions[j] = CloneExpression(indexedExpr); - - Validate(*cast); - - indexedExpr = std::move(cast); - } - else - { - auto swizzle = std::make_unique(); - swizzle->expression = std::move(indexedExpr); - - swizzle->componentCount = swizzleComponentCount; - for (std::size_t j = 0; j < swizzleComponentCount; ++j) - swizzle->components[j] = ToSwizzleIndex(identifierEntry.identifier[j], identifierEntry.sourceLocation); - - Validate(*swizzle); - - indexedExpr = std::move(swizzle); - } - } - else - throw ShaderLang::CompilerUnexpectedAccessedTypeError{ node.sourceLocation }; - } - - return indexedExpr; - } - - ExpressionPtr SanitizeVisitor::Clone(AccessIndexExpression& node) - { - MandatoryExpr(node.expr, node.sourceLocation); - for (auto& index : node.indices) - MandatoryExpr(index, node.sourceLocation); - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - // TODO: Handle AccessIndex on structs with m_context->options.useIdentifierAccessesForStructs - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(AliasValueExpression& node) - { - const Identifier* targetIdentifier = ResolveAliasIdentifier(&m_context->aliases.Retrieve(node.aliasId, node.sourceLocation), node.sourceLocation); - ExpressionPtr targetExpr = HandleIdentifier(&targetIdentifier->target, node.sourceLocation); - - if (m_context->options.removeAliases) - return targetExpr; - - AliasType aliasType; - aliasType.aliasIndex = node.aliasId; - aliasType.targetType = std::make_unique(); - aliasType.targetType->type = *targetExpr->cachedExpressionType; - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - clone->cachedExpressionType = std::move(aliasType); - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(AssignExpression& node) - { - MandatoryExpr(node.left, node.sourceLocation); - MandatoryExpr(node.right, node.sourceLocation); - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(BinaryExpression& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(CallFunctionExpression& node) - { - ExpressionPtr targetExpr = CloneExpression(MandatoryExpr(node.targetFunction, node.sourceLocation)); - const ExpressionType* targetExprType = GetExpressionType(*targetExpr); - if (!targetExprType) - return AstCloner::Clone(node); //< unresolved type - - const ExpressionType& resolvedType = ResolveAlias(*targetExprType); - - if (IsFunctionType(resolvedType)) - { - if (!m_context->currentFunction) - throw ShaderLang::CompilerFunctionCallOutsideOfFunctionError{ node.sourceLocation }; - - std::size_t targetFuncIndex; - if (targetExpr->GetType() == NodeType::FunctionExpression) - targetFuncIndex = static_cast(*targetExpr).funcId; - else if (targetExpr->GetType() == NodeType::AliasValueExpression) - { - const auto& alias = static_cast(*targetExpr); - - const Identifier* aliasIdentifier = ResolveAliasIdentifier(&m_context->aliases.Retrieve(alias.aliasId, node.sourceLocation), targetExpr->sourceLocation); - if (aliasIdentifier->target.category != IdentifierCategory::Function) - throw ShaderLang::CompilerExpectedFunctionError{ targetExpr->sourceLocation }; - - targetFuncIndex = aliasIdentifier->target.index; - } - else - throw ShaderLang::CompilerExpectedFunctionError{ targetExpr->sourceLocation }; - - auto clone = std::make_unique(); - clone->sourceLocation = node.sourceLocation; - clone->targetFunction = std::move(targetExpr); - - clone->parameters.reserve(node.parameters.size()); - for (const auto& parameter : node.parameters) - clone->parameters.push_back(CloneExpression(parameter)); - - m_context->currentFunction->calledFunctions.UnboundedSet(targetFuncIndex); - - Validate(*clone); - - return clone; - } - else if (IsIntrinsicFunctionType(resolvedType)) - { - if (targetExpr->GetType() != NodeType::IntrinsicFunctionExpression) - throw ShaderLang::CompilerExpectedIntrinsicFunctionError{ targetExpr->sourceLocation }; - - std::size_t targetIntrinsicId = static_cast(*targetExpr).intrinsicId; - - std::vector parameters; - parameters.reserve(node.parameters.size()); - - for (const auto& param : node.parameters) - parameters.push_back(CloneExpression(param)); - - auto intrinsic = ShaderBuilder::Intrinsic(m_context->intrinsics.Retrieve(targetIntrinsicId, node.sourceLocation), std::move(parameters)); - intrinsic->sourceLocation = node.sourceLocation; - Validate(*intrinsic); - - return intrinsic; - } - else if (IsMethodType(resolvedType)) - { - const MethodType& methodType = std::get(resolvedType); - - std::vector parameters; - parameters.reserve(node.parameters.size() + 1); - - // TODO: Add MethodExpression - assert(targetExpr->GetType() == NodeType::AccessIdentifierExpression); - - parameters.push_back(std::move(static_cast(*targetExpr).expr)); - for (const auto& param : node.parameters) - parameters.push_back(CloneExpression(param)); - - assert(IsSamplerType(methodType.objectType->type) && methodType.methodIndex == 0); - auto intrinsic = ShaderBuilder::Intrinsic(IntrinsicType::SampleTexture, std::move(parameters)); - intrinsic->sourceLocation = node.sourceLocation; - Validate(*intrinsic); - - return intrinsic; - } - else - { - // Calling a type - vec3[f32](0.0, 1.0, 2.0) - it's a cast - auto clone = std::make_unique(); - clone->sourceLocation = node.sourceLocation; - clone->targetType = *targetExprType; - - if (node.parameters.size() > clone->expressions.size()) - throw ShaderLang::CompilerCastComponentMismatchError{ node.sourceLocation }; - - for (std::size_t i = 0; i < node.parameters.size(); ++i) - clone->expressions[i] = CloneExpression(node.parameters[i]); - - Validate(*clone); - - return Clone(*clone); //< Necessary because cast has to be modified (FIXME) - } - } - - ExpressionPtr SanitizeVisitor::Clone(CastExpression& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - if (Validate(*clone) == ValidationResult::Unresolved) - return clone; //< unresolved - - const ExpressionType& targetType = clone->targetType.GetResultingValue(); - - if (m_context->options.removeMatrixCast && IsMatrixType(targetType)) - { - const MatrixType& targetMatrixType = std::get(targetType); - - const ExpressionType& frontExprType = ResolveAlias(GetExpressionTypeSecure(*clone->expressions.front())); - bool isMatrixCast = IsMatrixType(frontExprType); - if (isMatrixCast && std::get(frontExprType) == targetMatrixType) - { - // Nothing to do - return std::move(clone->expressions.front()); - } - - auto variableDeclaration = ShaderBuilder::DeclareVariable("temp", targetType); //< Validation will prevent name-clash if required - variableDeclaration->sourceLocation = node.sourceLocation; - Validate(*variableDeclaration); - - std::size_t variableIndex = *variableDeclaration->varIndex; - - m_context->currentStatementList->emplace_back(std::move(variableDeclaration)); - - for (std::size_t i = 0; i < targetMatrixType.columnCount; ++i) - { - // temp[i] - auto columnExpr = ShaderBuilder::AccessIndex(ShaderBuilder::Variable(variableIndex, targetType), ShaderBuilder::Constant(UInt32(i))); - columnExpr->sourceLocation = node.sourceLocation; - Validate(*columnExpr); - - // vector expression - ExpressionPtr vectorExpr; - std::size_t vectorComponentCount; - if (isMatrixCast) - { - // fromMatrix[i] - auto matrixColumnExpr = ShaderBuilder::AccessIndex(CloneExpression(clone->expressions.front()), ShaderBuilder::Constant(UInt32(i))); - matrixColumnExpr->sourceLocation = node.sourceLocation; - Validate(*matrixColumnExpr); - - vectorExpr = std::move(matrixColumnExpr); - vectorComponentCount = std::get(frontExprType).rowCount; - } - else - { - // parameter #i - vectorExpr = std::move(clone->expressions[i]); - vectorComponentCount = std::get(ResolveAlias(GetExpressionTypeSecure(*vectorExpr))).componentCount; - } - - // cast expression (turn fromMatrix[i] to vec3[f32](fromMatrix[i])) - ExpressionPtr castExpr; - if (vectorComponentCount != targetMatrixType.rowCount) - { - CastExpressionPtr vecCast; - if (vectorComponentCount < targetMatrixType.rowCount) - { - std::array expressions; - expressions[0] = std::move(vectorExpr); - for (std::size_t j = 0; j < targetMatrixType.rowCount - vectorComponentCount; ++j) - expressions[j + 1] = ShaderBuilder::Constant(ExpressionType{ targetMatrixType.type }, (i == j + vectorComponentCount) ? 1 : 0); //< set 1 to diagonal - - vecCast = ShaderBuilder::Cast(ExpressionType{ VectorType{ targetMatrixType.rowCount, targetMatrixType.type } }, std::move(expressions)); - vecCast->sourceLocation = node.sourceLocation; - Validate(*vecCast); - - castExpr = std::move(vecCast); - } - else - { - std::array swizzleComponents; - std::iota(swizzleComponents.begin(), swizzleComponents.begin() + targetMatrixType.rowCount, 0); - - auto swizzleExpr = ShaderBuilder::Swizzle(std::move(vectorExpr), swizzleComponents, targetMatrixType.rowCount); - swizzleExpr->sourceLocation = node.sourceLocation; - Validate(*swizzleExpr); - - castExpr = std::move(swizzleExpr); - } - } - else - castExpr = std::move(vectorExpr); - - // temp[i] = castExpr - auto assignExpr = ShaderBuilder::Assign(AssignType::Simple, std::move(columnExpr), std::move(castExpr)); - assignExpr->sourceLocation = node.sourceLocation; - - m_context->currentStatementList->emplace_back(ShaderBuilder::ExpressionStatement(std::move(assignExpr))); - } - - auto varExpr = ShaderBuilder::Variable(variableIndex, targetType); - varExpr->sourceLocation = node.sourceLocation; - - return varExpr; - } - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(ConditionalExpression& node) - { - MandatoryExpr(node.condition, node.sourceLocation); - MandatoryExpr(node.truePath, node.sourceLocation); - MandatoryExpr(node.falsePath, node.sourceLocation); - - ExpressionPtr cloneCondition = AstCloner::Clone(*node.condition); - - std::optional conditionValue = ComputeConstantValue(*cloneCondition); - if (!conditionValue.has_value()) - { - // Unresolvable condition - return AstCloner::Clone(node); - } - - if (GetConstantType(*conditionValue) != ExpressionType{ PrimitiveType::Boolean }) - throw ShaderLang::CompilerConditionExpectedBoolError{ cloneCondition->sourceLocation, ToString(GetConstantType(*conditionValue), cloneCondition->sourceLocation) }; - - if (std::get(*conditionValue)) - return AstCloner::Clone(*node.truePath); - else - return AstCloner::Clone(*node.falsePath); - } - - ExpressionPtr SanitizeVisitor::Clone(ConstantValueExpression& node) - { - if (std::holds_alternative(node.value)) - throw ShaderLang::CompilerConstantExpectedValueError{ node.sourceLocation }; - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - clone->cachedExpressionType = GetConstantType(clone->value); - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(ConstantExpression& node) - { - const ConstantValue* value = m_context->constantValues.TryRetrieve(node.constantId, node.sourceLocation); - if (!value) - { - if (!m_context->options.allowPartialSanitization) - throw ShaderLang::AstInvalidConstantIndexError{ node.sourceLocation, node.constantId }; - - return AstCloner::Clone(node); //< unresolved - } - - // Replace by constant value - auto constant = ShaderBuilder::Constant(*value); - constant->cachedExpressionType = GetConstantType(constant->value); - constant->sourceLocation = node.sourceLocation; - - return constant; - } - - ExpressionPtr SanitizeVisitor::Clone(IdentifierExpression& node) - { - assert(m_context); - - const IdentifierData* identifierData = FindIdentifier(node.identifier); - if (!identifierData) - { - if (m_context->allowUnknownIdentifiers) - return AstCloner::Clone(node); - - throw ShaderLang::CompilerUnknownIdentifierError{ node.sourceLocation, node.identifier }; - } - - if (identifierData->category == IdentifierCategory::Unresolved) - return AstCloner::Clone(node); - - return HandleIdentifier(identifierData, node.sourceLocation); - } - - ExpressionPtr SanitizeVisitor::Clone(IntrinsicExpression& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(SwizzleExpression& node) - { - auto expression = CloneExpression(MandatoryExpr(node.expression, node.sourceLocation)); - - const ExpressionType* exprType = GetExpressionType(*expression); - if (!exprType) - { - auto swizzleExpr = ShaderBuilder::Swizzle(std::move(expression), node.components, node.componentCount); //< unresolved - swizzleExpr->cachedExpressionType = node.cachedExpressionType; - swizzleExpr->sourceLocation = node.sourceLocation; - - return swizzleExpr; - } - - const ExpressionType& resolvedExprType = ResolveAlias(*exprType); - - if (m_context->options.removeScalarSwizzling && IsPrimitiveType(resolvedExprType)) - { - for (std::size_t i = 0; i < node.componentCount; ++i) - { - if (node.components[i] != 0) - throw ShaderLang::CompilerInvalidScalarSwizzleError{ node.sourceLocation }; - } - - if (node.componentCount == 1) - return expression; //< ignore this swizzle (a.x == a) - - // Use a Cast expression to replace swizzle - expression = CacheResult(std::move(expression)); //< Since we are going to use a value multiple times, cache it if required - - PrimitiveType baseType; - if (IsVectorType(resolvedExprType)) - baseType = std::get(resolvedExprType).type; - else - baseType = std::get(resolvedExprType); - - auto cast = std::make_unique(); - cast->sourceLocation = node.sourceLocation; - cast->targetType = ExpressionType{ VectorType{ node.componentCount, baseType } }; - for (std::size_t j = 0; j < node.componentCount; ++j) - cast->expressions[j] = CloneExpression(expression); - - Validate(*cast); - - return cast; - } - else - { - auto clone = std::make_unique(); - clone->componentCount = node.componentCount; - clone->components = node.components; - clone->expression = std::move(expression); - clone->sourceLocation = node.sourceLocation; - Validate(*clone); - - return clone; - } - } - - ExpressionPtr SanitizeVisitor::Clone(UnaryExpression& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - return clone; - } - - ExpressionPtr SanitizeVisitor::Clone(VariableValueExpression& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(BranchStatement& node) - { - if (node.isConst) - { - // Evaluate every condition at compilation and select the right statement - for (auto& cond : node.condStatements) - { - MandatoryExpr(cond.condition, node.sourceLocation); - - std::optional conditionValue = ComputeConstantValue(*AstCloner::Clone(*cond.condition)); - if (!conditionValue.has_value()) - return AstCloner::Clone(node); //< Unresolvable condition - - if (GetConstantType(*conditionValue) != ExpressionType{ PrimitiveType::Boolean }) - throw ShaderLang::CompilerConditionExpectedBoolError{ cond.condition->sourceLocation, ToString(GetConstantType(*conditionValue), cond.condition->sourceLocation) }; - - if (std::get(*conditionValue)) - return Unscope(AstCloner::Clone(*cond.statement)); - } - - // Every condition failed, fallback to else if any - if (node.elseStatement) - return Unscope(AstCloner::Clone(*node.elseStatement)); - else - return ShaderBuilder::NoOp(); - } - - auto clone = std::make_unique(); - clone->condStatements.reserve(node.condStatements.size()); - - if (!m_context->currentFunction) - throw ShaderLang::CompilerBranchOutsideOfFunctionError{ node.sourceLocation }; - - BranchStatement* root = clone.get(); - for (std::size_t condIndex = 0; condIndex < node.condStatements.size(); ++condIndex) - { - auto& cond = node.condStatements[condIndex]; - - PushScope(); - - auto BuildCondStatement = [&](BranchStatement::ConditionalStatement& condStatement) - { - condStatement.condition = CloneExpression(MandatoryExpr(cond.condition, node.sourceLocation)); - - const ExpressionType* condType = GetExpressionType(*condStatement.condition); - if (!condType) - return ValidationResult::Unresolved; - - if (!IsPrimitiveType(*condType) || std::get(*condType) != PrimitiveType::Boolean) - throw ShaderLang::CompilerConditionExpectedBoolError{ condStatement.condition->sourceLocation, ToString(*condType, condStatement.condition->sourceLocation)}; - - condStatement.statement = CloneStatement(MandatoryStatement(cond.statement, node.sourceLocation)); - return ValidationResult::Validated; - }; - - if (m_context->options.splitMultipleBranches && condIndex > 0) - { - auto currentBranch = std::make_unique(); - - if (BuildCondStatement(currentBranch->condStatements.emplace_back()) == ValidationResult::Unresolved) - return AstCloner::Clone(node); - - root->elseStatement = std::move(currentBranch); - root = static_cast(root->elseStatement.get()); - } - else - { - if (BuildCondStatement(clone->condStatements.emplace_back()) == ValidationResult::Unresolved) - return AstCloner::Clone(node); - } - - PopScope(); - } - - if (node.elseStatement) - { - PushScope(); - root->elseStatement = CloneStatement(node.elseStatement); - PopScope(); - } - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(ConditionalStatement& node) - { - MandatoryExpr(node.condition, node.sourceLocation); - MandatoryStatement(node.statement, node.sourceLocation); - - ExpressionPtr cloneCondition = AstCloner::Clone(*node.condition); - - std::optional conditionValue = ComputeConstantValue(*cloneCondition); - - bool wasInConditionalStatement = m_context->inConditionalStatement; - m_context->inConditionalStatement = true; - CallOnExit restoreCond([=] { m_context->inConditionalStatement = wasInConditionalStatement; }); - - if (!conditionValue.has_value()) - { - // Unresolvable condition - auto condStatement = ShaderBuilder::ConditionalStatement(std::move(cloneCondition), AstCloner::Clone(*node.statement)); - condStatement->sourceLocation = node.sourceLocation; - - return condStatement; - } - - if (GetConstantType(*conditionValue) != ExpressionType{ PrimitiveType::Boolean }) - throw ShaderLang::CompilerConditionExpectedBoolError{ cloneCondition->sourceLocation, ToString(GetConstantType(*conditionValue), cloneCondition->sourceLocation) }; - - if (std::get(*conditionValue)) - return AstCloner::Clone(*node.statement); - else - return ShaderBuilder::NoOp(); - } - - StatementPtr SanitizeVisitor::Clone(DeclareAliasStatement& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - if (m_context->options.removeAliases) - return ShaderBuilder::NoOp(); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DeclareConstStatement& node) - { - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (!clone->expression) - throw ShaderLang::CompilerConstMissingExpressionError{ node.sourceLocation }; - - clone->expression = PropagateConstants(*clone->expression); - if (clone->expression->GetType() != NodeType::ConstantValueExpression) - { - if (!m_context->options.allowPartialSanitization) - throw ShaderLang::CompilerConstantExpressionRequiredError{ clone->expression->sourceLocation }; - - clone->constIndex = RegisterConstant(clone->name, std::nullopt, clone->constIndex, node.sourceLocation); - return clone; - } - - const ConstantValue& value = static_cast(*clone->expression).value; - - ExpressionType expressionType = GetConstantType(value); - - std::optional constType = ResolveTypeExpr(clone->type, true, node.sourceLocation); - - if (clone->type.HasValue() && constType.has_value() && *constType != ResolveAlias(expressionType)) - throw ShaderLang::CompilerVarDeclarationTypeUnmatchingError{ clone->expression->sourceLocation, ToString(expressionType, clone->expression->sourceLocation), ToString(*constType, node.sourceLocation) }; - - clone->type = expressionType; - - clone->constIndex = RegisterConstant(clone->name, value, clone->constIndex, node.sourceLocation); - - if (m_context->options.removeConstDeclaration) - return ShaderBuilder::NoOp(); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DeclareExternalStatement& node) - { - assert(m_context); - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - std::optional defaultBlockSet = 0; - if (clone->bindingSet.HasValue()) - { - if (ComputeExprValue(clone->bindingSet, node.sourceLocation) == ValidationResult::Validated) - defaultBlockSet = clone->bindingSet.GetResultingValue(); - else - defaultBlockSet.reset(); //< Unresolved value - } - - for (auto& extVar : clone->externalVars) - { - if (!extVar.bindingIndex.HasValue()) - throw ShaderLang::CompilerExtMissingBindingIndexError{ extVar.sourceLocation }; - - if (extVar.bindingSet.HasValue()) - ComputeExprValue(extVar.bindingSet, node.sourceLocation); - else if (defaultBlockSet) - extVar.bindingSet = *defaultBlockSet; - - ComputeExprValue(extVar.bindingIndex, node.sourceLocation); - - Context::UsedExternalData usedBindingData; - usedBindingData.isConditional = m_context->inConditionalStatement; - - if (extVar.bindingSet.IsResultingValue() && extVar.bindingIndex.IsResultingValue()) - { - UInt64 bindingSet = extVar.bindingSet.GetResultingValue(); - UInt64 bindingIndex = extVar.bindingIndex.GetResultingValue(); - - UInt64 bindingKey = bindingSet << 32 | bindingIndex; - if (auto it = m_context->usedBindingIndexes.find(bindingKey); it != m_context->usedBindingIndexes.end()) - { - if (!it->second.isConditional || !usedBindingData.isConditional) - throw ShaderLang::CompilerExtBindingAlreadyUsedError{ extVar.sourceLocation, UInt32(bindingSet), UInt32(bindingIndex) }; - } - - m_context->usedBindingIndexes.emplace(bindingKey, usedBindingData); - } - - if (auto it = m_context->declaredExternalVar.find(extVar.name); it != m_context->declaredExternalVar.end()) - { - if (!it->second.isConditional || !usedBindingData.isConditional) - throw ShaderLang::CompilerExtAlreadyDeclaredError{ extVar.sourceLocation, extVar.name }; - } - - m_context->declaredExternalVar.emplace(extVar.name, usedBindingData); - - std::optional resolvedType = ResolveTypeExpr(extVar.type, false, node.sourceLocation); - if (!resolvedType.has_value()) - { - RegisterUnresolved(extVar.name); - continue; - } - - const ExpressionType& targetType = ResolveAlias(*resolvedType); - - ExpressionType varType; - if (IsUniformType(targetType)) - varType = std::get(targetType).containedType; - else if (IsSamplerType(targetType)) - varType = targetType; - else - throw ShaderLang::CompilerExtTypeNotAllowedError{ extVar.sourceLocation, extVar.name, ToString(*resolvedType, extVar.sourceLocation) }; - - extVar.type = std::move(resolvedType).value(); - extVar.varIndex = RegisterVariable(extVar.name, std::move(varType), extVar.varIndex, extVar.sourceLocation); - - SanitizeIdentifier(extVar.name); - } - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DeclareFunctionStatement& node) - { - if (m_context->currentFunction) - throw ShaderLang::CompilerFunctionDeclarationInsideFunctionError{ node.sourceLocation }; - - auto clone = std::make_unique(); - clone->name = node.name; - - clone->parameters.reserve(node.parameters.size()); - for (auto& parameter : node.parameters) - { - auto& cloneParam = clone->parameters.emplace_back(); - cloneParam.name = parameter.name; - cloneParam.type = CloneType(parameter.type); - cloneParam.varIndex = parameter.varIndex; - cloneParam.sourceLocation = parameter.sourceLocation; - } - - if (node.returnType.HasValue()) - clone->returnType = CloneType(node.returnType); - else - clone->returnType = ExpressionType{ NoType{} }; - - if (node.depthWrite.HasValue()) - ComputeExprValue(node.depthWrite, clone->depthWrite, node.sourceLocation); - - if (node.earlyFragmentTests.HasValue()) - ComputeExprValue(node.earlyFragmentTests, clone->earlyFragmentTests, node.sourceLocation); - - if (node.entryStage.HasValue()) - ComputeExprValue(node.entryStage, clone->entryStage, node.sourceLocation); - - if (node.isExported.HasValue()) - ComputeExprValue(node.isExported, clone->isExported, node.sourceLocation); - - if (clone->entryStage.IsResultingValue()) - { - ShaderStageType stageType = clone->entryStage.GetResultingValue(); - - if (!m_context->options.allowPartialSanitization) - { - if (m_context->entryFunctions[UnderlyingCast(stageType)]) - throw ShaderLang::CompilerEntryPointAlreadyDefinedError{ clone->sourceLocation, stageType }; - - m_context->entryFunctions[UnderlyingCast(stageType)] = &node; - } - - if (node.parameters.size() > 1) - throw ShaderLang::CompilerEntryFunctionParameterError{ node.parameters[1].sourceLocation }; - - if (!node.parameters.empty()) - { - auto& parameter = node.parameters.front(); - if (parameter.type.IsResultingValue()) - { - if (!IsStructType(ResolveAlias(parameter.type.GetResultingValue()))) - throw ShaderLang::CompilerEntryFunctionParameterError{ parameter.sourceLocation }; - } - } - - if (stageType != ShaderStageType::Fragment) - { - if (node.depthWrite.HasValue()) - throw ShaderLang::CompilerDepthWriteAttributeError{ node.sourceLocation }; - - if (node.earlyFragmentTests.HasValue()) - throw ShaderLang::CompilerEarlyFragmentTestsAttributeError{ node.sourceLocation }; - } - } - - // Function content is resolved in a second pass - auto& pendingFunc = m_context->pendingFunctions.emplace_back(); - pendingFunc.cloneNode = clone.get(); - pendingFunc.node = &node; - - if (clone->earlyFragmentTests.HasValue() && clone->earlyFragmentTests.GetResultingValue()) - { - //TODO: warning and disable early fragment tests - throw ShaderLang::CompilerDiscardEarlyFragmentTestsError{ node.sourceLocation }; - } - - FunctionData funcData; - funcData.node = clone.get(); //< update function node - - std::size_t funcIndex = RegisterFunction(clone->name, std::move(funcData), node.funcIndex, node.sourceLocation); - clone->funcIndex = funcIndex; - - SanitizeIdentifier(clone->name); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DeclareOptionStatement& node) - { - if (m_context->currentFunction) - throw ShaderLang::CompilerOptionDeclarationInsideFunctionError{ node.sourceLocation }; - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - if (clone->optName.empty()) - throw ShaderLang::AstEmptyIdentifierError{ node.sourceLocation }; - - std::optional resolvedOptionType = ResolveTypeExpr(clone->optType, false, node.sourceLocation); - if (!resolvedOptionType) - { - clone->optIndex = RegisterConstant(clone->optName, std::nullopt, clone->optIndex, node.sourceLocation); - return clone; - } - - ExpressionType resolvedType = ResolveType(*resolvedOptionType, false, node.sourceLocation); - const ExpressionType& targetType = ResolveAlias(resolvedType); - - if (clone->defaultValue) - { - const ExpressionType* defaultValueType = GetExpressionType(*clone->defaultValue); - if (!defaultValueType) - { - clone->optIndex = RegisterConstant(clone->optName, std::nullopt, clone->optIndex, node.sourceLocation); - return clone; //< unresolved - } - - if (targetType != *defaultValueType) - throw ShaderLang::CompilerVarDeclarationTypeUnmatchingError{ node.sourceLocation }; - } - - clone->optType = std::move(resolvedType); - - UInt32 optionHash = CRC32(reinterpret_cast(clone->optName.data()), clone->optName.size()); - - if (auto optionValueIt = m_context->options.optionValues.find(optionHash); optionValueIt != m_context->options.optionValues.end()) - clone->optIndex = RegisterConstant(clone->optName, optionValueIt->second, node.optIndex, node.sourceLocation); - else - { - if (m_context->options.allowPartialSanitization) - { - // Partial sanitization, we cannot give a value to this option - clone->optIndex = RegisterConstant(clone->optName, std::nullopt, clone->optIndex, node.sourceLocation); - } - else - { - if (!clone->defaultValue) - throw ShaderLang::CompilerMissingOptionValueError{ node.sourceLocation, clone->optName }; - - clone->optIndex = RegisterConstant(clone->optName, ComputeConstantValue(*clone->defaultValue), node.optIndex, node.sourceLocation); - } - } - - if (m_context->options.removeOptionDeclaration) - return ShaderBuilder::NoOp(); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DeclareStructStatement& node) - { - if (m_context->currentFunction) - throw ShaderLang::CompilerStructDeclarationInsideFunctionError{ node.sourceLocation }; - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - - if (clone->isExported.HasValue()) - ComputeExprValue(clone->isExported, node.sourceLocation); - - if (clone->description.layout.HasValue()) - ComputeExprValue(clone->description.layout, node.sourceLocation); - - std::unordered_set declaredMembers; - for (auto& member : clone->description.members) - { - if (member.cond.HasValue()) - { - ComputeExprValue(member.cond, member.sourceLocation); - if (member.cond.IsResultingValue() && !member.cond.GetResultingValue()) - continue; - } - - if (member.builtin.HasValue()) - ComputeExprValue(member.builtin, member.sourceLocation); - - if (member.locationIndex.HasValue()) - ComputeExprValue(member.locationIndex, member.sourceLocation); - - if (member.builtin.HasValue() && member.locationIndex.HasValue()) - throw ShaderLang::CompilerStructFieldBuiltinLocationError{ member.sourceLocation }; - - if (declaredMembers.find(member.name) != declaredMembers.end()) - { - if ((!member.cond.HasValue() || !member.cond.IsResultingValue()) && !m_context->options.allowPartialSanitization) - throw ShaderLang::CompilerStructFieldMultipleError{ member.sourceLocation, member.name }; - } - - declaredMembers.insert(member.name); - - if (member.type.HasValue() && member.type.IsExpression()) - { - assert(m_context->options.allowPartialSanitization); - continue; - } - - ExpressionType resolvedType = member.type.GetResultingValue(); - if (clone->description.layout.IsResultingValue() && clone->description.layout.GetResultingValue() == StructLayout::Std140) - { - const ExpressionType& targetType = ResolveAlias(member.type.GetResultingValue()); - - if (IsPrimitiveType(targetType) && std::get(targetType) == PrimitiveType::Boolean) - throw ShaderLang::CompilerStructLayoutTypeNotAllowedError{ member.sourceLocation, "bool", "std140" }; - else if (IsStructType(targetType)) - { - std::size_t structIndex = std::get(targetType).structIndex; - const StructDescription* desc = m_context->structs.Retrieve(structIndex, member.sourceLocation); - if (!desc->layout.HasValue() || desc->layout.GetResultingValue() != clone->description.layout.GetResultingValue()) - throw ShaderLang::CompilerStructLayoutInnerMismatchError{ member.sourceLocation, "std140", "" }; - } - } - } - - clone->description.isConditional = m_context->inConditionalStatement; - - clone->structIndex = RegisterStruct(clone->description.name, &clone->description, clone->structIndex, clone->sourceLocation); - - SanitizeIdentifier(clone->description.name); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DeclareVariableStatement& node) - { - if (!m_context->currentFunction) - throw ShaderLang::CompilerVarDeclarationOutsideOfFunctionError{ node.sourceLocation }; - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - Validate(*clone); - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(DiscardStatement& node) - { - if (!m_context->currentFunction) - throw ShaderLang::CompilerDiscardOutsideOfFunctionError{ node.sourceLocation }; - - m_context->currentFunction->flags |= FunctionFlag::DoesDiscard; - - return AstCloner::Clone(node); - } - - StatementPtr SanitizeVisitor::Clone(ExpressionStatement& node) - { - MandatoryExpr(node.expression, node.sourceLocation); - - return AstCloner::Clone(node); - } - - StatementPtr SanitizeVisitor::Clone(ForStatement& node) - { - if (node.varName.empty()) - throw ShaderLang::AstEmptyIdentifierError{ node.sourceLocation }; - - auto fromExpr = CloneExpression(MandatoryExpr(node.fromExpr, node.sourceLocation)); - auto stepExpr = CloneExpression(node.stepExpr); - auto toExpr = CloneExpression(MandatoryExpr(node.toExpr, node.sourceLocation)); - MandatoryStatement(node.statement, node.sourceLocation); - - const ExpressionType* fromExprType = GetExpressionType(*fromExpr); - const ExpressionType* toExprType = GetExpressionType(*toExpr); - - ExpressionValue unrollValue; - - auto CloneFor = [&] - { - auto clone = std::make_unique(); - clone->fromExpr = std::move(fromExpr); - clone->stepExpr = std::move(stepExpr); - clone->toExpr = std::move(toExpr); - clone->varName = node.varName; - clone->unroll = std::move(unrollValue); - - PushScope(); - { - if (fromExprType) - clone->varIndex = RegisterVariable(node.varName, *fromExprType, node.varIndex, node.sourceLocation); - else - { - RegisterUnresolved(node.varName); - clone->varIndex = node.varIndex; //< preserve var index, if set - } - clone->statement = CloneStatement(node.statement); - } - PopScope(); - - SanitizeIdentifier(clone->varName); - - return clone; - }; - - if (node.unroll.HasValue() && ComputeExprValue(node.unroll, unrollValue, node.sourceLocation) == ValidationResult::Unresolved) - return CloneFor(); //< unresolved unroll - - if (!fromExprType || !toExprType) - return CloneFor(); //< unresolved from/to type - - const ExpressionType& resolvedFromExprType = ResolveAlias(*fromExprType); - if (!IsPrimitiveType(resolvedFromExprType)) - throw ShaderLang::CompilerForFromTypeExpectIntegerTypeError{ fromExpr->sourceLocation, ToString(*fromExprType, fromExpr->sourceLocation) }; - - PrimitiveType counterType = std::get(resolvedFromExprType); - if (counterType != PrimitiveType::Int32 && counterType != PrimitiveType::UInt32) - throw ShaderLang::CompilerForFromTypeExpectIntegerTypeError{ fromExpr->sourceLocation, ToString(*fromExprType, fromExpr->sourceLocation) }; - - const ExpressionType& resolvedToExprType = ResolveAlias(*toExprType); - if (resolvedToExprType != resolvedFromExprType) - throw ShaderLang::CompilerForToUnmatchingTypeError{ toExpr->sourceLocation, ToString(*toExprType, toExpr->sourceLocation), ToString(*fromExprType, fromExpr->sourceLocation) }; - - if (stepExpr) - { - const ExpressionType* stepExprType = GetExpressionType(*stepExpr); - if (!stepExprType) - return CloneFor(); //< unresolved step type - - const ExpressionType& resolvedStepExprType = ResolveAlias(*stepExprType); - if (resolvedStepExprType != resolvedFromExprType) - throw ShaderLang::CompilerForStepUnmatchingTypeError{ stepExpr->sourceLocation, ToString(*stepExprType, stepExpr->sourceLocation), ToString(*fromExprType, fromExpr->sourceLocation) }; - } - - if (unrollValue.HasValue()) - { - assert(unrollValue.IsResultingValue()); - if (unrollValue.GetResultingValue() == LoopUnroll::Always) - { - std::optional fromValue = ComputeConstantValue(*fromExpr); - std::optional toValue = ComputeConstantValue(*toExpr); - if (!fromValue.has_value() || !toValue.has_value()) - return CloneFor(); //< can't resolve step value - - std::optional stepValue; - if (stepExpr) - { - stepValue = ComputeConstantValue(*stepExpr); - if (!stepValue.has_value()) - return CloneFor(); //< can't resolve step value - } - - auto multi = std::make_unique(); - multi->sourceLocation = node.sourceLocation; - - auto Unroll = [&](auto dummy) - { - using T = std::decay_t; - - T counter = std::get(*fromValue); - T to = std::get(*toValue); - T step = (stepExpr) ? std::get(*stepValue) : T(1); - - for (; counter < to; counter += step) - { - PushScope(); - - auto innerMulti = std::make_unique(); - innerMulti->sourceLocation = node.sourceLocation; - - auto constant = ShaderBuilder::Constant(counter); - constant->sourceLocation = node.sourceLocation; - - auto var = ShaderBuilder::DeclareVariable(node.varName, std::move(constant)); - var->sourceLocation = node.sourceLocation; - - Validate(*var); - innerMulti->statements.emplace_back(std::move(var)); - - innerMulti->statements.emplace_back(Unscope(CloneStatement(node.statement))); - - multi->statements.emplace_back(ShaderBuilder::Scoped(std::move(innerMulti))); - - PopScope(); - } - }; - - switch (counterType) - { - case PrimitiveType::Int32: - Unroll(Int32{}); - break; - - case PrimitiveType::UInt32: - Unroll(UInt32{}); - break; - - default: - throw ShaderLang::AstInternalError{ node.sourceLocation, "unexpected counter type " }; - } - - return multi; - } - } - - if (m_context->options.reduceLoopsToWhile) - { - PushScope(); - - auto multi = std::make_unique(); - - // Counter variable - auto counterVariable = ShaderBuilder::DeclareVariable(node.varName, std::move(fromExpr)); - counterVariable->sourceLocation = node.sourceLocation; - counterVariable->varIndex = node.varIndex; - Validate(*counterVariable); - - std::size_t counterVarIndex = counterVariable->varIndex.value(); - multi->statements.emplace_back(std::move(counterVariable)); - - // Target variable - auto targetVariable = ShaderBuilder::DeclareVariable("to", std::move(toExpr)); - targetVariable->sourceLocation = node.sourceLocation; - Validate(*targetVariable); - - std::size_t targetVarIndex = targetVariable->varIndex.value(); - multi->statements.emplace_back(std::move(targetVariable)); - - // Step variable - std::optional stepVarIndex; - - if (stepExpr) - { - auto stepVariable = ShaderBuilder::DeclareVariable("step", std::move(stepExpr)); - stepVariable->sourceLocation = node.sourceLocation; - Validate(*stepVariable); - - stepVarIndex = stepVariable->varIndex; - multi->statements.emplace_back(std::move(stepVariable)); - } - - // While - auto whileStatement = std::make_unique(); - whileStatement->unroll = std::move(unrollValue); - - // While condition - auto conditionCounterVariable = ShaderBuilder::Variable(counterVarIndex, counterType); - conditionCounterVariable->sourceLocation = node.sourceLocation; - - auto conditionTargetVariable = ShaderBuilder::Variable(targetVarIndex, counterType); - conditionTargetVariable->sourceLocation = node.sourceLocation; - - auto condition = ShaderBuilder::Binary(BinaryType::CompLt, std::move(conditionCounterVariable), std::move(conditionTargetVariable)); - condition->sourceLocation = node.sourceLocation; - Validate(*condition); - - whileStatement->condition = std::move(condition); - - // While body - auto body = std::make_unique(); - body->statements.reserve(2); - - body->statements.emplace_back(Unscope(CloneStatement(node.statement))); - - ExpressionPtr incrExpr; - if (stepVarIndex) - incrExpr = ShaderBuilder::Variable(*stepVarIndex, counterType); - else - incrExpr = (counterType == PrimitiveType::Int32) ? ShaderBuilder::Constant(1) : ShaderBuilder::Constant(1u); - - auto incrCounter = ShaderBuilder::Assign(AssignType::CompoundAdd, ShaderBuilder::Variable(counterVarIndex, counterType), std::move(incrExpr)); - incrCounter->sourceLocation = node.sourceLocation; - Validate(*incrCounter); - - body->statements.emplace_back(ShaderBuilder::ExpressionStatement(std::move(incrCounter))); - - whileStatement->body = std::move(body); - - multi->statements.emplace_back(std::move(whileStatement)); - - PopScope(); - - return multi; - } - else - return CloneFor(); - } - - StatementPtr SanitizeVisitor::Clone(ForEachStatement& node) - { - auto expr = CloneExpression(MandatoryExpr(node.expression, node.sourceLocation)); - - if (node.varName.empty()) - throw ShaderLang::AstEmptyIdentifierError{ node.sourceLocation }; - - const ExpressionType* exprType = GetExpressionType(*expr); - if (!exprType) - return AstCloner::Clone(node); //< unresolved expression type - - const ExpressionType& resolvedExprType = ResolveAlias(*exprType); - - ExpressionType innerType; - if (IsArrayType(resolvedExprType)) - { - const ArrayType& arrayType = std::get(resolvedExprType); - innerType = arrayType.containedType->type; - } - else - throw ShaderLang::CompilerForEachUnsupportedTypeError{ node.sourceLocation, ToString(*exprType, node.sourceLocation) }; - - ExpressionValue unrollValue; - if (node.unroll.HasValue()) - { - if (ComputeExprValue(node.unroll, unrollValue, node.sourceLocation) == ValidationResult::Unresolved) - return AstCloner::Clone(node); //< unresolved unroll type - - if (unrollValue.GetResultingValue() == LoopUnroll::Always) - { - PushScope(); - - // Repeat code - auto multi = std::make_unique(); - multi->sourceLocation = node.sourceLocation; - - if (IsArrayType(resolvedExprType)) - { - const ArrayType& arrayType = std::get(resolvedExprType); - - for (UInt32 i = 0; i < arrayType.length; ++i) - { - PushScope(); - - auto innerMulti = std::make_unique(); - innerMulti->sourceLocation = node.sourceLocation; - - auto accessIndex = ShaderBuilder::AccessIndex(CloneExpression(expr), ShaderBuilder::Constant(i)); - Validate(*accessIndex); - - auto elementVariable = ShaderBuilder::DeclareVariable(node.varName, std::move(accessIndex)); - Validate(*elementVariable); - - innerMulti->statements.emplace_back(std::move(elementVariable)); - innerMulti->statements.emplace_back(Unscope(CloneStatement(node.statement))); - - multi->statements.emplace_back(ShaderBuilder::Scoped(std::move(innerMulti))); - - PopScope(); - } - } - - PopScope(); - - return multi; - } - } - - if (m_context->options.reduceLoopsToWhile) - { - PushScope(); - - auto multi = std::make_unique(); - - if (IsArrayType(resolvedExprType)) - { - const ArrayType& arrayType = std::get(resolvedExprType); - - multi->statements.reserve(2); - - // Counter variable - auto counterVariable = ShaderBuilder::DeclareVariable("i", ShaderBuilder::Constant(0u)); - Validate(*counterVariable); - - std::size_t counterVarIndex = counterVariable->varIndex.value(); - - multi->statements.emplace_back(std::move(counterVariable)); - - auto whileStatement = std::make_unique(); - whileStatement->unroll = std::move(unrollValue); - - // While condition - auto condition = ShaderBuilder::Binary(BinaryType::CompLt, ShaderBuilder::Variable(counterVarIndex, PrimitiveType::UInt32), ShaderBuilder::Constant(arrayType.length)); - Validate(*condition); - whileStatement->condition = std::move(condition); - - // While body - auto body = std::make_unique(); - body->statements.reserve(3); - - auto accessIndex = ShaderBuilder::AccessIndex(std::move(expr), ShaderBuilder::Variable(counterVarIndex, PrimitiveType::UInt32)); - Validate(*accessIndex); - - auto elementVariable = ShaderBuilder::DeclareVariable(node.varName, std::move(accessIndex)); - elementVariable->varIndex = node.varIndex; //< Preserve var index - Validate(*elementVariable); - body->statements.emplace_back(std::move(elementVariable)); - - body->statements.emplace_back(Unscope(CloneStatement(node.statement))); - - auto incrCounter = ShaderBuilder::Assign(AssignType::CompoundAdd, ShaderBuilder::Variable(counterVarIndex, PrimitiveType::UInt32), ShaderBuilder::Constant(1u)); - Validate(*incrCounter); - - body->statements.emplace_back(ShaderBuilder::ExpressionStatement(std::move(incrCounter))); - - whileStatement->body = std::move(body); - - multi->statements.emplace_back(std::move(whileStatement)); - } - - PopScope(); - - return multi; - } - else - { - auto clone = std::make_unique(); - clone->expression = std::move(expr); - clone->varName = node.varName; - clone->unroll = std::move(unrollValue); - clone->sourceLocation = node.sourceLocation; - - PushScope(); - { - clone->varIndex = RegisterVariable(node.varName, innerType, node.varIndex, node.sourceLocation); - clone->statement = CloneStatement(node.statement); - } - PopScope(); - - SanitizeIdentifier(clone->varName); - - return clone; - } - } - - StatementPtr SanitizeVisitor::Clone(ImportStatement& node) - { - if (!m_context->options.moduleResolver) - { - if (!m_context->options.allowPartialSanitization) - throw ShaderLang::CompilerNoModuleResolverError{ node.sourceLocation }; - - // when partially sanitizing, importing a whole module could register any identifier, so at this point we can't see unknown identifiers as errors - m_context->allowUnknownIdentifiers = true; - - return StaticUniquePointerCast(AstCloner::Clone(node)); - } - - ModulePtr targetModule = m_context->options.moduleResolver->Resolve(node.moduleName); - if (!targetModule) - throw ShaderLang::CompilerModuleNotFoundError{ node.sourceLocation, node.moduleName }; - - std::size_t moduleIndex; - - const Uuid& moduleUuid = targetModule->metadata->moduleId; - auto it = m_context->moduleByUuid.find(moduleUuid); - if (it == m_context->moduleByUuid.end()) - { - m_context->moduleByUuid[moduleUuid] = Context::ModuleIdSentinel; - - // Generate module identifier (based on UUID) - const auto& moduleUuidBytes = moduleUuid.ToArray(); - - SHA256Hash hasher; - hasher.Begin(); - hasher.Append(moduleUuidBytes.data(), moduleUuidBytes.size()); - hasher.End(); - - std::string identifier = "_" + hasher.End().ToHex().substr(0, 8); - - // Load new module - auto moduleEnvironment = std::make_shared(); - moduleEnvironment->parentEnv = m_context->globalEnv; - - auto previousEnv = m_context->currentEnv; - m_context->currentEnv = moduleEnvironment; - - ModulePtr sanitizedModule = std::make_shared(targetModule->metadata); - - // Remap already used indices - IndexRemapperVisitor::Options indexCallbacks; - indexCallbacks.aliasIndexGenerator = [this](std::size_t /*previousIndex*/) { return m_context->aliases.RegisterNewIndex(true); }; - indexCallbacks.constIndexGenerator = [this](std::size_t /*previousIndex*/) { return m_context->constantValues.RegisterNewIndex(true); }; - indexCallbacks.funcIndexGenerator = [this](std::size_t /*previousIndex*/) { return m_context->functions.RegisterNewIndex(true); }; - indexCallbacks.structIndexGenerator = [this](std::size_t /*previousIndex*/) { return m_context->structs.RegisterNewIndex(true); }; - indexCallbacks.varIndexGenerator = [this](std::size_t /*previousIndex*/) { return m_context->variableTypes.RegisterNewIndex(true); }; - indexCallbacks.forceIndexGeneration = true; - - sanitizedModule->rootNode = StaticUniquePointerCast(RemapIndices(*targetModule->rootNode, indexCallbacks)); - - std::string error; - sanitizedModule->rootNode = SanitizeInternal(*sanitizedModule->rootNode, &error); - if (!sanitizedModule->rootNode) - throw ShaderLang::CompilerModuleCompilationFailedError{ node.sourceLocation, node.moduleName, error }; - - moduleIndex = m_context->modules.size(); - - assert(m_context->modules.size() == moduleIndex); - auto& moduleData = m_context->modules.emplace_back(); - - // Don't run dependency checker when partially sanitizing - if (!m_context->options.allowPartialSanitization) - { - moduleData.dependenciesVisitor = std::make_unique(); - moduleData.dependenciesVisitor->Register(*sanitizedModule->rootNode); - } - - moduleData.environment = std::move(moduleEnvironment); - - assert(m_context->currentModule->importedModules.size() == moduleIndex); - auto& importedModule = m_context->currentModule->importedModules.emplace_back(); - importedModule.identifier = identifier; - importedModule.module = std::move(sanitizedModule); - - m_context->currentEnv = std::move(previousEnv); - - RegisterModule(identifier, moduleIndex); - - m_context->moduleByUuid[moduleUuid] = moduleIndex; - } - else - { - // Module has already been imported - moduleIndex = it->second; - if (moduleIndex == Context::ModuleIdSentinel) - throw ShaderLang::CompilerCircularImportError{ node.sourceLocation, node.moduleName }; - } - - auto& moduleData = m_context->modules[moduleIndex]; - - auto& exportedSet = moduleData.exportedSetByModule[m_context->currentEnv->moduleId]; - - // Extract exported nodes and their dependencies - std::vector aliasStatements; - - AstExportVisitor::Callbacks callbacks; - callbacks.onExportedFunc = [&](DeclareFunctionStatement& node) - { - assert(node.funcIndex); - - if (moduleData.dependenciesVisitor) - moduleData.dependenciesVisitor->MarkFunctionAsUsed(*node.funcIndex); - - if (!exportedSet.usedFunctions.UnboundedTest(*node.funcIndex)) - { - exportedSet.usedFunctions.UnboundedSet(*node.funcIndex); - aliasStatements.emplace_back(ShaderBuilder::DeclareAlias(node.name, ShaderBuilder::Function(*node.funcIndex))); - } - }; - - callbacks.onExportedStruct = [&](DeclareStructStatement& node) - { - assert(node.structIndex); - - if (moduleData.dependenciesVisitor) - moduleData.dependenciesVisitor->MarkStructAsUsed(*node.structIndex); - - if (!exportedSet.usedStructs.UnboundedTest(*node.structIndex)) - { - exportedSet.usedStructs.UnboundedSet(*node.structIndex); - aliasStatements.emplace_back(ShaderBuilder::DeclareAlias(node.description.name, ShaderBuilder::StructType(*node.structIndex))); - } - }; - - AstExportVisitor exportVisitor; - exportVisitor.Visit(*m_context->currentModule->importedModules[moduleIndex].module->rootNode, callbacks); - - if (aliasStatements.empty()) - return ShaderBuilder::NoOp(); - - // Register aliases - for (auto& aliasPtr : aliasStatements) - Validate(*aliasPtr); - - if (m_context->options.removeAliases) - return ShaderBuilder::NoOp(); - - // Generate alias statements - MultiStatementPtr aliasBlock = std::make_unique(); - for (auto& aliasPtr : aliasStatements) - aliasBlock->statements.push_back(std::move(aliasPtr)); - - m_context->allowUnknownIdentifiers = true; //< if module uses a unresolved and non-exported symbol, we need to allow unknown identifiers - - return aliasBlock; - } - - StatementPtr SanitizeVisitor::Clone(MultiStatement& node) - { - auto clone = std::make_unique(); - clone->statements.reserve(node.statements.size()); - - std::vector* previousList = m_context->currentStatementList; - m_context->currentStatementList = &clone->statements; - - for (auto& statement : node.statements) - clone->statements.push_back(AstCloner::Clone(MandatoryStatement(statement, node.sourceLocation))); - - m_context->currentStatementList = previousList; - - return clone; - } - - StatementPtr SanitizeVisitor::Clone(ScopedStatement& node) - { - MandatoryStatement(node.statement, node.sourceLocation); - - PushScope(); - - auto scopedClone = AstCloner::Clone(node); - - PopScope(); - - return scopedClone; - } - - StatementPtr SanitizeVisitor::Clone(WhileStatement& node) - { - MandatoryExpr(node.condition, node.sourceLocation); - MandatoryStatement(node.body, node.sourceLocation); - - auto clone = StaticUniquePointerCast(AstCloner::Clone(node)); - if (Validate(*clone) == ValidationResult::Unresolved) - return clone; - - if (clone->unroll.HasValue()) - { - if (ComputeExprValue(clone->unroll, node.sourceLocation) == ValidationResult::Validated && clone->unroll.GetResultingValue() == LoopUnroll::Always) - throw ShaderLang::CompilerWhileUnrollNotSupportedError{ node.sourceLocation }; - } - - return clone; - } - - auto SanitizeVisitor::FindIdentifier(const std::string_view& identifierName) const -> const IdentifierData* - { - return FindIdentifier(*m_context->currentEnv, identifierName); - } - - template - auto SanitizeVisitor::FindIdentifier(const std::string_view& identifierName, F&& functor) const -> const IdentifierData* - { - return FindIdentifier(*m_context->currentEnv, identifierName, std::forward(functor)); - } - - auto SanitizeVisitor::FindIdentifier(const Environment& environment, const std::string_view& identifierName) const -> const IdentifierData* - { - auto it = std::find_if(environment.identifiersInScope.rbegin(), environment.identifiersInScope.rend(), [&](const Identifier& identifier) { return identifier.name == identifierName; }); - if (it == environment.identifiersInScope.rend()) - { - if (environment.parentEnv) - return FindIdentifier(*environment.parentEnv, identifierName); - else - return nullptr; - } - - return &it->target; - } - - template - auto SanitizeVisitor::FindIdentifier(const Environment& environment, const std::string_view& identifierName, F&& functor) const -> const IdentifierData* - { - auto it = std::find_if(environment.identifiersInScope.rbegin(), environment.identifiersInScope.rend(), [&](const Identifier& identifier) - { - if (identifier.name == identifierName) - { - if (functor(identifier.target)) - return true; - } - - return false; - }); - if (it == environment.identifiersInScope.rend()) - { - if (environment.parentEnv) - return FindIdentifier(*environment.parentEnv, identifierName, std::forward(functor)); - else - return nullptr; - } - - return &it->target; - } - - const ExpressionType* SanitizeVisitor::GetExpressionType(Expression& expr) const - { - const ExpressionType* expressionType = ShaderAst::GetExpressionType(expr); - if (!expressionType) - { - if (!m_context->options.allowPartialSanitization) - throw ShaderLang::AstInternalError{ expr.sourceLocation, "unexpected missing expression type" }; - } - - return expressionType; - } - - const ExpressionType& SanitizeVisitor::GetExpressionTypeSecure(Expression& expr) const - { - const ExpressionType* expressionType = GetExpressionType(expr); - if (!expressionType) - throw ShaderLang::AstInternalError{ expr.sourceLocation, "unexpected missing expression type" }; - - return *expressionType; - } - - ExpressionPtr SanitizeVisitor::HandleIdentifier(const IdentifierData* identifierData, const ShaderLang::SourceLocation& sourceLocation) - { - switch (identifierData->category) - { - case IdentifierCategory::Alias: - { - AliasValueExpression aliasValue; - aliasValue.aliasId = identifierData->index; - aliasValue.sourceLocation = sourceLocation; - - return Clone(aliasValue); - } - - case IdentifierCategory::Constant: - { - // Replace IdentifierExpression by Constant(Value)Expression - ConstantExpression constantExpr; - constantExpr.constantId = identifierData->index; - constantExpr.sourceLocation = sourceLocation; - - return Clone(constantExpr); //< Turn ConstantExpression into ConstantValueExpression - } - - case IdentifierCategory::Function: - { - // Replace IdentifierExpression by FunctionExpression - auto funcExpr = std::make_unique(); - funcExpr->cachedExpressionType = FunctionType{ identifierData->index }; //< FIXME: Functions (and intrinsic) should be typed by their parameters/return type - funcExpr->funcId = identifierData->index; - funcExpr->sourceLocation = sourceLocation; - - return funcExpr; - } - - case IdentifierCategory::Intrinsic: - { - IntrinsicType intrinsicType = m_context->intrinsics.Retrieve(identifierData->index, sourceLocation); - - // Replace IdentifierExpression by IntrinsicFunctionExpression - auto intrinsicExpr = std::make_unique(); - intrinsicExpr->cachedExpressionType = IntrinsicFunctionType{ intrinsicType }; //< FIXME: Functions (and intrinsic) should be typed by their parameters/return type - intrinsicExpr->intrinsicId = identifierData->index; - intrinsicExpr->sourceLocation = sourceLocation; - - return intrinsicExpr; - } - - case IdentifierCategory::Module: - throw ShaderLang::AstUnexpectedIdentifierError{ sourceLocation, "module" }; - - case IdentifierCategory::Struct: - { - // Replace IdentifierExpression by StructTypeExpression - auto structExpr = std::make_unique(); - structExpr->cachedExpressionType = StructType{ identifierData->index }; - structExpr->sourceLocation = sourceLocation; - structExpr->structTypeId = identifierData->index; - - return structExpr; - } - - case IdentifierCategory::Type: - { - auto typeExpr = std::make_unique(); - typeExpr->cachedExpressionType = Type{ identifierData->index }; - typeExpr->sourceLocation = sourceLocation; - typeExpr->typeId = identifierData->index; - - return typeExpr; - } - - case IdentifierCategory::Unresolved: - throw ShaderLang::AstUnexpectedIdentifierError{ sourceLocation, "unresolved" }; - - case IdentifierCategory::Variable: - { - // Replace IdentifierExpression by VariableExpression - auto varExpr = std::make_unique(); - varExpr->cachedExpressionType = m_context->variableTypes.Retrieve(identifierData->index, sourceLocation); - varExpr->sourceLocation = sourceLocation; - varExpr->variableId = identifierData->index; - - return varExpr; - } - } - - throw ShaderLang::AstInternalError{ sourceLocation, "unhandled identifier category" }; - } - - void SanitizeVisitor::PushScope() - { - auto& scope = m_context->currentEnv->scopes.emplace_back(); - scope.previousSize = m_context->currentEnv->identifiersInScope.size(); - } - - void SanitizeVisitor::PopScope() - { - assert(!m_context->currentEnv->scopes.empty()); - auto& scope = m_context->currentEnv->scopes.back(); - m_context->currentEnv->identifiersInScope.resize(scope.previousSize); - m_context->currentEnv->scopes.pop_back(); - } - - ExpressionPtr SanitizeVisitor::CacheResult(ExpressionPtr expression) - { - // No need to cache LValues (variables/constants) (TODO: Improve this, as constants don't need to be cached as well) - if (GetExpressionCategory(*expression) == ExpressionCategory::LValue) - return expression; - - assert(m_context->currentStatementList); - - auto variableDeclaration = ShaderBuilder::DeclareVariable("cachedResult", std::move(expression)); //< Validation will prevent name-clash if required - Validate(*variableDeclaration); - - auto varExpr = std::make_unique(); - varExpr->sourceLocation = variableDeclaration->initialExpression->sourceLocation; - varExpr->variableId = *variableDeclaration->varIndex; - - m_context->currentStatementList->push_back(std::move(variableDeclaration)); - - return varExpr; - } - - std::optional SanitizeVisitor::ComputeConstantValue(Expression& expr) const - { - // Run optimizer on constant value to hopefully retrieve a single constant value - ExpressionPtr optimizedExpr = PropagateConstants(expr); - if (optimizedExpr->GetType() != NodeType::ConstantValueExpression) - { - if (!m_context->options.allowPartialSanitization) - throw ShaderLang::CompilerConstantExpressionRequiredError{ expr.sourceLocation }; - - return std::nullopt; - } - - return static_cast(*optimizedExpr).value; - } - - template - auto SanitizeVisitor::ComputeExprValue(ExpressionValue& attribute, const ShaderLang::SourceLocation& sourceLocation) const -> ValidationResult - { - if (!attribute.HasValue()) - throw ShaderLang::AstAttributeRequiresValueError{ sourceLocation }; - - if (attribute.IsExpression()) - { - auto& expr = *attribute.GetExpression(); - - std::optional value = ComputeConstantValue(expr); - if (!value) - return ValidationResult::Unresolved; - - if constexpr (TypeListFind) - { - if (!std::holds_alternative(*value)) - { - // HAAAAAX - if (std::holds_alternative(*value) && std::is_same_v) - attribute = static_cast(std::get(*value)); - else - throw ShaderLang::CompilerAttributeUnexpectedTypeError{ expr.sourceLocation }; - } - else - attribute = std::get(*value); - } - else - throw ShaderLang::CompilerAttributeUnexpectedExpressionError{ expr.sourceLocation }; - } - - return ValidationResult::Validated; - } - - template - auto SanitizeVisitor::ComputeExprValue(const ExpressionValue& attribute, ExpressionValue& targetAttribute, const ShaderLang::SourceLocation& sourceLocation) -> ValidationResult - { - if (!attribute.HasValue()) - throw ShaderLang::AstAttributeRequiresValueError{ sourceLocation }; - - if (attribute.IsExpression()) - { - auto& expr = *attribute.GetExpression(); - - std::optional value = ComputeConstantValue(*attribute.GetExpression()); - if (!value) - { - targetAttribute = AstCloner::Clone(*attribute.GetExpression()); - return ValidationResult::Unresolved; - } - - if constexpr (TypeListFind) - { - if (!std::holds_alternative(*value)) - { - // HAAAAAX - if (std::holds_alternative(*value) && std::is_same_v) - targetAttribute = static_cast(std::get(*value)); - else - throw ShaderLang::CompilerAttributeUnexpectedTypeError{ expr.sourceLocation }; - } - else - targetAttribute = std::get(*value); - } - else - throw ShaderLang::CompilerAttributeUnexpectedExpressionError{ expr.sourceLocation }; - } - else - { - assert(attribute.IsResultingValue()); - targetAttribute = attribute.GetResultingValue(); - } - - return ValidationResult::Validated; - } - - template - std::unique_ptr SanitizeVisitor::PropagateConstants(T& node) const - { - AstConstantPropagationVisitor::Options optimizerOptions; - optimizerOptions.constantQueryCallback = [&](std::size_t constantId) -> const ConstantValue* - { - const ConstantValue* value = m_context->constantValues.TryRetrieve(constantId, node.sourceLocation); - if (!value && !m_context->options.allowPartialSanitization) - throw ShaderLang::AstInvalidConstantIndexError{ node.sourceLocation, constantId }; - - return value; - }; - - // Run optimizer on constant value to hopefully retrieve a single constant value - return StaticUniquePointerCast(ShaderAst::PropagateConstants(node, optimizerOptions)); - } - - void SanitizeVisitor::PreregisterIndices(const Module& module) - { - // If AST has been sanitized before and is sanitized again but with different options that may introduce new variables (for example reduceLoopsToWhile) - // we have to make sure we won't override variable indices. This is done by visiting the AST a first time and preregistering all indices. - // TODO: Only do this is the AST has been already sanitized, maybe using a flag stored in the module? - - AstReflect::Callbacks registerCallbacks; - registerCallbacks.onAliasIndex = [this](const std::string& /*name*/, std::size_t index, const ShaderLang::SourceLocation& sourceLocation) { m_context->aliases.PreregisterIndex(index, sourceLocation); }; - registerCallbacks.onConstIndex = [this](const std::string& /*name*/, std::size_t index, const ShaderLang::SourceLocation& sourceLocation) { m_context->constantValues.PreregisterIndex(index, sourceLocation); }; - registerCallbacks.onFunctionIndex = [this](const std::string& /*name*/, std::size_t index, const ShaderLang::SourceLocation& sourceLocation) { m_context->functions.PreregisterIndex(index, sourceLocation); }; - registerCallbacks.onOptionIndex = [this](const std::string& /*name*/, std::size_t index, const ShaderLang::SourceLocation& sourceLocation) { m_context->constantValues.PreregisterIndex(index, sourceLocation); }; - registerCallbacks.onStructIndex = [this](const std::string& /*name*/, std::size_t index, const ShaderLang::SourceLocation& sourceLocation) { m_context->structs.PreregisterIndex(index, sourceLocation); }; - registerCallbacks.onVariableIndex = [this](const std::string& /*name*/, std::size_t index, const ShaderLang::SourceLocation& sourceLocation) { m_context->variableTypes.PreregisterIndex(index, sourceLocation); }; - - AstReflect reflectVisitor; - for (const auto& importedModule : module.importedModules) - reflectVisitor.Reflect(*importedModule.module->rootNode, registerCallbacks); - - reflectVisitor.Reflect(*module.rootNode, registerCallbacks); - } - - void SanitizeVisitor::PropagateFunctionFlags(std::size_t funcIndex, FunctionFlags flags, Bitset<>& seen) - { - auto& funcData = m_context->functions.Retrieve(funcIndex, {}); - funcData.flags |= flags; - - for (std::size_t i = funcData.calledByFunctions.FindFirst(); i != funcData.calledByFunctions.npos; i = funcData.calledByFunctions.FindNext(i)) - PropagateFunctionFlags(i, funcData.flags, seen); - } - - void SanitizeVisitor::RegisterBuiltin() - { - // Primitive types - RegisterType("bool", PrimitiveType::Boolean, std::nullopt, {}); - RegisterType("f32", PrimitiveType::Float32, std::nullopt, {}); - RegisterType("i32", PrimitiveType::Int32, std::nullopt, {}); - RegisterType("u32", PrimitiveType::UInt32, std::nullopt, {}); - - // Partial types - - // Array - RegisterType("array", PartialType { - { TypeParameterCategory::FullType, TypeParameterCategory::ConstantValue }, - [=](const TypeParameter* parameters, std::size_t parameterCount, const ShaderLang::SourceLocation& sourceLocation) -> ExpressionType - { - assert(parameterCount == 2); - assert(std::holds_alternative(parameters[0])); - assert(std::holds_alternative(parameters[1])); - - const ExpressionType& exprType = std::get(parameters[0]); - const ConstantValue& length = std::get(parameters[1]); - - UInt32 lengthValue; - if (std::holds_alternative(length)) - { - Int32 value = std::get(length); - if (value <= 0) - throw ShaderLang::CompilerArrayLengthError{ sourceLocation, std::to_string(value) }; - - lengthValue = SafeCast(value); - } - else if (std::holds_alternative(length)) - { - lengthValue = std::get(length); - if (lengthValue == 0) - throw ShaderLang::CompilerArrayLengthError{ sourceLocation, std::to_string(lengthValue) }; - } - else - throw ShaderLang::CompilerArrayLengthError{ sourceLocation, ToString(GetConstantType(length), sourceLocation) }; - - ArrayType arrayType; - arrayType.containedType = std::make_unique(); - arrayType.containedType->type = exprType; - arrayType.length = lengthValue; - - return arrayType; - } - }, std::nullopt, {}); - - // matX - for (std::size_t componentCount = 2; componentCount <= 4; ++componentCount) - { - RegisterType("mat" + std::to_string(componentCount), PartialType { - { TypeParameterCategory::PrimitiveType }, - [=](const TypeParameter* parameters, std::size_t parameterCount, const ShaderLang::SourceLocation& /*sourceLocation*/) -> ExpressionType - { - assert(parameterCount == 1); - assert(std::holds_alternative(*parameters)); - - const ExpressionType& exprType = std::get(*parameters); - assert(IsPrimitiveType(exprType)); - - return MatrixType { - componentCount, componentCount, std::get(exprType) - }; - } - }, std::nullopt, {}); - } - - // vecX - for (std::size_t componentCount = 2; componentCount <= 4; ++componentCount) - { - RegisterType("vec" + std::to_string(componentCount), PartialType { - { TypeParameterCategory::PrimitiveType }, - [=](const TypeParameter* parameters, std::size_t parameterCount, const ShaderLang::SourceLocation& /*sourceLocation*/) -> ExpressionType - { - assert(parameterCount == 1); - assert(std::holds_alternative(*parameters)); - - const ExpressionType& exprType = std::get(*parameters); - assert(IsPrimitiveType(exprType)); - - return VectorType { - componentCount, std::get(exprType) - }; - } - }, std::nullopt, {}); - } - - // samplers - struct SamplerInfo - { - std::string typeName; - ImageType imageType; - }; - - std::array samplerInfos = { - { - { - "sampler2D", - ImageType::E2D - }, - { - "samplerCube", - ImageType::Cubemap - } - } - }; - - for (SamplerInfo& sampler : samplerInfos) - { - RegisterType(std::move(sampler.typeName), PartialType { - { TypeParameterCategory::PrimitiveType }, - [=](const TypeParameter* parameters, std::size_t parameterCount, const ShaderLang::SourceLocation& sourceLocation) -> ExpressionType - { - assert(parameterCount == 1); - assert(std::holds_alternative(*parameters)); - - const ExpressionType& exprType = std::get(*parameters); - assert(IsPrimitiveType(exprType)); - - PrimitiveType primitiveType = std::get(exprType); - - // TODO: Add support for integer samplers - if (primitiveType != PrimitiveType::Float32) - throw ShaderLang::CompilerSamplerUnexpectedTypeError{ sourceLocation, ToString(exprType, sourceLocation) }; - - return SamplerType { - sampler.imageType, primitiveType - }; - } - }, std::nullopt, {}); - } - - // uniform - RegisterType("uniform", PartialType { - { TypeParameterCategory::StructType }, - [=](const TypeParameter* parameters, std::size_t parameterCount, const ShaderLang::SourceLocation& /*sourceLocation*/) -> ExpressionType - { - assert(parameterCount == 1); - assert(std::holds_alternative(*parameters)); - - const ExpressionType& exprType = std::get(*parameters); - assert(IsStructType(exprType)); - - StructType structType = std::get(exprType); - return UniformType { - structType - }; - } - }, std::nullopt, {}); - - // Intrinsics - RegisterIntrinsic("cross", IntrinsicType::CrossProduct); - RegisterIntrinsic("dot", IntrinsicType::DotProduct); - RegisterIntrinsic("exp", IntrinsicType::Exp); - RegisterIntrinsic("length", IntrinsicType::Length); - RegisterIntrinsic("max", IntrinsicType::Max); - RegisterIntrinsic("min", IntrinsicType::Min); - RegisterIntrinsic("normalize", IntrinsicType::Normalize); - RegisterIntrinsic("pow", IntrinsicType::Pow); - RegisterIntrinsic("reflect", IntrinsicType::Reflect); - } - - std::size_t SanitizeVisitor::RegisterAlias(std::string name, std::optional aliasData, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - if (FindIdentifier(name)) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - - std::size_t aliasIndex; - if (aliasData) - aliasIndex = m_context->aliases.Register(std::move(*aliasData), index, sourceLocation); - else if (index) - { - m_context->aliases.PreregisterIndex(*index, sourceLocation); - aliasIndex = *index; - } - else - aliasIndex = m_context->aliases.RegisterNewIndex(true); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - aliasIndex, - IdentifierCategory::Alias, - m_context->inConditionalStatement - }); - - return aliasIndex; - } - - std::size_t SanitizeVisitor::RegisterConstant(std::string name, std::optional value, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - if (FindIdentifier(name)) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - - std::size_t constantIndex; - if (value) - constantIndex = m_context->constantValues.Register(std::move(*value), index, sourceLocation); - else if (index) - { - m_context->constantValues.PreregisterIndex(*index, sourceLocation); - constantIndex = *index; - } - else - constantIndex = m_context->constantValues.RegisterNewIndex(true); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - constantIndex, - IdentifierCategory::Constant, - m_context->inConditionalStatement - }); - - return constantIndex; - } - - std::size_t SanitizeVisitor::RegisterFunction(std::string name, std::optional funcData, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - if (auto* identifier = FindIdentifier(name)) - { - // Functions can be conditionally defined and condition not resolved yet, allow duplicates when partially sanitizing - bool duplicate = !m_context->options.allowPartialSanitization; - - // Functions cannot be declared twice, except for entry ones if their stages are different - if (funcData) - { - if (funcData->node->entryStage.HasValue() && identifier->category == IdentifierCategory::Function) - { - auto& otherFunction = m_context->functions.Retrieve(identifier->index, sourceLocation); - if (funcData->node->entryStage.GetResultingValue() != otherFunction.node->entryStage.GetResultingValue()) - duplicate = false; - } - } - else - { - if (!m_context->options.allowPartialSanitization) - throw ShaderLang::AstInternalError{ sourceLocation, "unexpected missing function data" }; - - duplicate = false; - } - - if (duplicate) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - } - - std::size_t functionIndex; - if (funcData) - functionIndex = m_context->functions.Register(std::move(*funcData), index, sourceLocation); - else if (index) - { - m_context->functions.PreregisterIndex(*index, sourceLocation); - functionIndex = *index; - } - else - functionIndex = m_context->functions.RegisterNewIndex(true); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - functionIndex, - IdentifierCategory::Function, - m_context->inConditionalStatement - }); - - return functionIndex; - } - - std::size_t SanitizeVisitor::RegisterIntrinsic(std::string name, IntrinsicType type) - { - if (FindIdentifier(name)) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ {}, name }; - - std::size_t intrinsicIndex = m_context->intrinsics.Register(std::move(type), std::nullopt, {}); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - intrinsicIndex, - IdentifierCategory::Intrinsic, - m_context->inConditionalStatement - }); - - return intrinsicIndex; - } - - std::size_t SanitizeVisitor::RegisterModule(std::string moduleIdentifier, std::size_t index) - { - if (FindIdentifier(moduleIdentifier)) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ {}, moduleIdentifier }; - - std::size_t moduleIndex = m_context->moduleIndices.Register(index, std::nullopt, {}); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(moduleIdentifier), - moduleIndex, - IdentifierCategory::Module, - m_context->inConditionalStatement - }); - - return moduleIndex; - } - - std::size_t SanitizeVisitor::RegisterStruct(std::string name, std::optional description, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - bool unresolved = false; - if (const IdentifierData* identifierData = FindIdentifier(name)) - { - if (!m_context->inConditionalStatement || !identifierData->isConditional) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - else - unresolved = true; - } - - std::size_t structIndex; - if (description) - structIndex = m_context->structs.Register(*description, index, sourceLocation); - else if (index) - { - m_context->structs.PreregisterIndex(*index, sourceLocation); - structIndex = *index; - } - else - structIndex = m_context->structs.RegisterNewIndex(true); - - if (!unresolved) - { - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - { - structIndex, - IdentifierCategory::Struct, - m_context->inConditionalStatement - } - }); - } - else - RegisterUnresolved(std::move(name)); - - return structIndex; - } - - std::size_t SanitizeVisitor::RegisterType(std::string name, std::optional expressionType, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - if (FindIdentifier(name)) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - - std::size_t typeIndex; - if (expressionType) - typeIndex = m_context->types.Register(std::move(*expressionType), index, sourceLocation); - else if (index) - { - m_context->types.PreregisterIndex(*index, sourceLocation); - typeIndex = *index; - } - else - typeIndex = m_context->types.RegisterNewIndex(true); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - typeIndex, - IdentifierCategory::Type, - m_context->inConditionalStatement - }); - - return typeIndex; - } - - std::size_t SanitizeVisitor::RegisterType(std::string name, std::optional partialType, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - if (FindIdentifier(name)) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - - std::size_t typeIndex; - if (partialType) - { - NamedPartialType namedPartial; - namedPartial.name = name; - namedPartial.type = std::move(*partialType); - - typeIndex = m_context->types.Register(std::move(namedPartial), index, sourceLocation); - } - else if (index) - { - m_context->types.PreregisterIndex(*index, sourceLocation); - typeIndex = *index; - } - else - typeIndex = m_context->types.RegisterNewIndex(true); - - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - typeIndex, - IdentifierCategory::Type, - m_context->inConditionalStatement - }); - - return typeIndex; - } - - void SanitizeVisitor::RegisterUnresolved(std::string name) - { - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - std::numeric_limits::max(), - IdentifierCategory::Unresolved, - m_context->inConditionalStatement - }); - } - - std::size_t SanitizeVisitor::RegisterVariable(std::string name, std::optional type, std::optional index, const ShaderLang::SourceLocation& sourceLocation) - { - bool unresolved = false; - if (auto* identifier = FindIdentifier(name)) - { - // Allow variable shadowing - if (identifier->category != IdentifierCategory::Variable) - throw ShaderLang::CompilerIdentifierAlreadyUsedError{ sourceLocation, name }; - else if (identifier->isConditional && m_context->inConditionalStatement) - unresolved = true; //< right variable isn't know from this point - } - - std::size_t varIndex; - if (type) - varIndex = m_context->variableTypes.Register(std::move(*type), index, sourceLocation); - else if (index) - { - m_context->variableTypes.PreregisterIndex(*index, sourceLocation); - varIndex = *index; - } - else - varIndex = m_context->variableTypes.RegisterNewIndex(true); - - if (!unresolved) - { - m_context->currentEnv->identifiersInScope.push_back({ - std::move(name), - { - varIndex, - IdentifierCategory::Variable, - m_context->inConditionalStatement - } - }); - } - else - RegisterUnresolved(std::move(name)); - - return varIndex; - } - - auto SanitizeVisitor::ResolveAliasIdentifier(const Identifier* identifier, const ShaderLang::SourceLocation& sourceLocation) const -> const Identifier* - { - while (identifier->target.category == IdentifierCategory::Alias) - identifier = &m_context->aliases.Retrieve(identifier->target.index, sourceLocation); - - return identifier; - } - - void SanitizeVisitor::ResolveFunctions() - { - // Once every function is known, we can evaluate function content - for (auto& pendingFunc : m_context->pendingFunctions) - { - PushScope(); - - for (auto& parameter : pendingFunc.cloneNode->parameters) - { - if (!m_context->options.allowPartialSanitization || parameter.type.IsResultingValue()) - { - parameter.varIndex = RegisterVariable(parameter.name, parameter.type.GetResultingValue(), parameter.varIndex, parameter.sourceLocation); - SanitizeIdentifier(parameter.name); - } - else - RegisterUnresolved(parameter.name); - } - - CurrentFunctionData tempFuncData; - if (pendingFunc.cloneNode->entryStage.HasValue()) - tempFuncData.stageType = pendingFunc.cloneNode->entryStage.GetResultingValue(); - - m_context->currentFunction = &tempFuncData; - - std::vector* previousList = m_context->currentStatementList; - m_context->currentStatementList = &pendingFunc.cloneNode->statements; - - pendingFunc.cloneNode->statements.reserve(pendingFunc.node->statements.size()); - for (auto& statement : pendingFunc.node->statements) - pendingFunc.cloneNode->statements.push_back(CloneStatement(MandatoryStatement(statement, pendingFunc.cloneNode->sourceLocation))); - - m_context->currentStatementList = previousList; - m_context->currentFunction = nullptr; - - std::size_t funcIndex = *pendingFunc.cloneNode->funcIndex; - for (std::size_t i = tempFuncData.calledFunctions.FindFirst(); i != tempFuncData.calledFunctions.npos; i = tempFuncData.calledFunctions.FindNext(i)) - { - auto& targetFunc = m_context->functions.Retrieve(i, pendingFunc.cloneNode->sourceLocation); - targetFunc.calledByFunctions.UnboundedSet(funcIndex); - } - - PopScope(); - } - m_context->pendingFunctions.clear(); - - Bitset<> seen; - for (const auto& [funcIndex, funcData] : m_context->functions.values) - { - PropagateFunctionFlags(funcIndex, funcData.flags, seen); - seen.Clear(); - } - - for (const auto& [funcIndex, funcData] : m_context->functions.values) - { - if (funcData.flags.Test(FunctionFlag::DoesDiscard) && funcData.node->entryStage.HasValue() && funcData.node->entryStage.GetResultingValue() != ShaderStageType::Fragment) - throw ShaderLang::CompilerDiscardOutsideOfFragmentStageError{ funcData.node->sourceLocation, funcData.node->entryStage.GetResultingValue() }; - } - } - - std::size_t SanitizeVisitor::ResolveStruct(const AliasType& aliasType, const ShaderLang::SourceLocation& sourceLocation) - { - return ResolveStruct(aliasType.targetType->type, sourceLocation); - } - - std::size_t SanitizeVisitor::ResolveStruct(const ExpressionType& exprType, const ShaderLang::SourceLocation& sourceLocation) - { - return std::visit([&](auto&& arg) -> std::size_t - { - using T = std::decay_t; - - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) - return ResolveStruct(arg, sourceLocation); - else if constexpr (std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v) - { - throw ShaderLang::CompilerStructExpectedError{ sourceLocation, ToString(exprType, sourceLocation) }; - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, exprType); - } - - std::size_t SanitizeVisitor::ResolveStruct(const StructType& structType, const ShaderLang::SourceLocation& /*sourceLocation*/) - { - return structType.structIndex; - } - - std::size_t SanitizeVisitor::ResolveStruct(const UniformType& uniformType, const ShaderLang::SourceLocation& /*sourceLocation*/) - { - return uniformType.containedType.structIndex; - } - - ExpressionType SanitizeVisitor::ResolveType(const ExpressionType& exprType, bool resolveAlias, const ShaderLang::SourceLocation& sourceLocation) - { - if (!IsTypeExpression(exprType)) - { - if (resolveAlias || m_context->options.removeAliases) - return ResolveAlias(exprType); - else - return exprType; - } - - std::size_t typeIndex = std::get(exprType).typeIndex; - - const auto& type = m_context->types.Retrieve(typeIndex, sourceLocation); - if (!std::holds_alternative(type)) - throw ShaderLang::CompilerFullTypeExpectedError{ sourceLocation, ToString(type, sourceLocation) }; - - return std::get(type); - } - - std::optional SanitizeVisitor::ResolveTypeExpr(const ExpressionValue& exprTypeValue, bool resolveAlias, const ShaderLang::SourceLocation& sourceLocation) - { - if (!exprTypeValue.HasValue()) - return NoType{}; - - if (exprTypeValue.IsResultingValue()) - return ResolveType(exprTypeValue.GetResultingValue(), resolveAlias, sourceLocation); - - assert(exprTypeValue.IsExpression()); - ExpressionPtr expression = CloneExpression(exprTypeValue.GetExpression()); - const ExpressionType* exprType = GetExpressionType(*expression); - if (!exprType) - return std::nullopt; - - //if (!IsTypeType(exprType)) - // throw AstError{ "type expected" }; - - return ResolveType(*exprType, resolveAlias, sourceLocation); - } - - void SanitizeVisitor::SanitizeIdentifier(std::string& identifier) - { - // Append _ until the identifier is no longer found - while (m_context->options.reservedIdentifiers.find(identifier) != m_context->options.reservedIdentifiers.end()) - { - do - { - identifier += "_"; - } - while (FindIdentifier(identifier) != nullptr); - } - } - - MultiStatementPtr SanitizeVisitor::SanitizeInternal(MultiStatement& rootNode, std::string* error) - { - MultiStatementPtr output; - { - // First pass, evaluate everything except function code - try - { - output = StaticUniquePointerCast(AstCloner::Clone(rootNode)); - } - catch (const std::runtime_error& err) - { - if (!error) - throw; - - *error = err.what(); - } - - ResolveFunctions(); - } - - return output; - } - - std::string SanitizeVisitor::ToString(const ExpressionType& exprType, const ShaderLang::SourceLocation& sourceLocation) const - { - Stringifier stringifier; - stringifier.aliasStringifier = [&](std::size_t aliasIndex) - { - return m_context->aliases.Retrieve(aliasIndex, sourceLocation).name; - }; - - stringifier.structStringifier = [&](std::size_t structIndex) - { - return m_context->structs.Retrieve(structIndex, sourceLocation)->name; - }; - - stringifier.typeStringifier = [&](std::size_t typeIndex) - { - return ToString(m_context->types.Retrieve(typeIndex, sourceLocation), sourceLocation); - }; - - return ShaderAst::ToString(exprType, stringifier); - } - - std::string SanitizeVisitor::ToString(const NamedPartialType& partialType, const ShaderLang::SourceLocation& /*sourceLocation*/) const - { - return partialType.name + " (partial)"; - } - - template - std::string SanitizeVisitor::ToString(const std::variant& value, const ShaderLang::SourceLocation& sourceLocation) const - { - return std::visit([&](auto&& arg) - { - return ToString(arg, sourceLocation); - }, value); - } - - void SanitizeVisitor::TypeMustMatch(const ExpressionType& left, const ExpressionType& right, const ShaderLang::SourceLocation& sourceLocation) const - { - if (ResolveAlias(left) != ResolveAlias(right)) - throw ShaderLang::CompilerUnmatchingTypesError{ sourceLocation, ToString(left, sourceLocation), ToString(right, sourceLocation) }; - } - - auto SanitizeVisitor::TypeMustMatch(const ExpressionPtr& left, const ExpressionPtr& right, const ShaderLang::SourceLocation& sourceLocation) -> ValidationResult - { - const ExpressionType* leftType = GetExpressionType(*left); - const ExpressionType* rightType = GetExpressionType(*right); - if (!leftType || !rightType) - return ValidationResult::Unresolved; - - TypeMustMatch(*leftType, *rightType, sourceLocation); - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(DeclareAliasStatement& node) -> ValidationResult - { - if (node.name.empty()) - throw ShaderLang::AstEmptyIdentifierError{ node.sourceLocation }; - - const ExpressionType* exprType = GetExpressionType(*node.expression); - if (!exprType) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedType = ResolveAlias(*exprType); - - Identifier aliasIdentifier; - aliasIdentifier.name = node.name; - - if (IsStructType(resolvedType)) - { - std::size_t structIndex = ResolveStruct(resolvedType, node.expression->sourceLocation); - aliasIdentifier.target = { structIndex, IdentifierCategory::Struct }; - } - else if (IsFunctionType(resolvedType)) - { - std::size_t funcIndex = std::get(resolvedType).funcIndex; - aliasIdentifier.target = { funcIndex, IdentifierCategory::Function }; - } - else if (IsAliasType(resolvedType)) - { - const AliasType& alias = std::get(resolvedType); - aliasIdentifier.target = { alias.aliasIndex, IdentifierCategory::Alias }; - } - else - throw ShaderLang::CompilerAliasUnexpectedTypeError{ node.sourceLocation, ToString(*exprType, node.expression->sourceLocation) }; - - - node.aliasIndex = RegisterAlias(node.name, std::move(aliasIdentifier), node.aliasIndex, node.sourceLocation); - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(WhileStatement& node) -> ValidationResult - { - const ExpressionType* conditionType = GetExpressionType(MandatoryExpr(node.condition, node.sourceLocation)); - MandatoryStatement(node.body, node.sourceLocation); - - if (!conditionType) - return ValidationResult::Unresolved; - - if (ResolveAlias(*conditionType) != ExpressionType{ PrimitiveType::Boolean }) - throw ShaderLang::CompilerConditionExpectedBoolError{ node.condition->sourceLocation, ToString(*conditionType, node.condition->sourceLocation) }; - - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(AccessIndexExpression& node) -> ValidationResult - { - const ExpressionType* exprType = GetExpressionType(MandatoryExpr(node.expr, node.sourceLocation)); - if (!exprType) - return ValidationResult::Unresolved; - - ExpressionType resolvedExprType = ResolveAlias(*exprType); - - if (IsTypeExpression(resolvedExprType)) - { - std::size_t typeIndex = std::get(resolvedExprType).typeIndex; - const auto& type = m_context->types.Retrieve(typeIndex, node.sourceLocation); - - if (!std::holds_alternative(type)) - throw ShaderLang::CompilerExpectedPartialTypeError{ node.sourceLocation, ToString(std::get(type), node.sourceLocation) }; - - const auto& partialType = std::get(type); - if (partialType.type.parameters.size() != node.indices.size()) - throw ShaderLang::CompilerPartialTypeParameterCountMismatchError{ node.sourceLocation, SafeCast(partialType.type.parameters.size()), SafeCast(node.indices.size()) }; - - StackVector parameters = NazaraStackVector(TypeParameter, partialType.type.parameters.size()); - for (std::size_t i = 0; i < partialType.type.parameters.size(); ++i) - { - const ExpressionPtr& indexExpr = node.indices[i]; - switch (partialType.type.parameters[i]) - { - case TypeParameterCategory::ConstantValue: - { - std::optional value = ComputeConstantValue(*indexExpr); - if (!value.has_value()) - return ValidationResult::Unresolved; - - parameters.push_back(std::move(*value)); - break; - } - - case TypeParameterCategory::FullType: - case TypeParameterCategory::PrimitiveType: - case TypeParameterCategory::StructType: - { - const ExpressionType* indexExprType = GetExpressionType(*indexExpr); - if (!indexExprType) - return ValidationResult::Unresolved; - - ExpressionType resolvedType = ResolveType(*indexExprType, true, node.sourceLocation); - - switch (partialType.type.parameters[i]) - { - case TypeParameterCategory::PrimitiveType: - { - if (!IsPrimitiveType(resolvedType)) - throw ShaderLang::CompilerPartialTypeExpectError{ indexExpr->sourceLocation, "primitive", SafeCast(i) }; - - break; - } - - case TypeParameterCategory::StructType: - { - if (!IsStructType(resolvedType)) - throw ShaderLang::CompilerPartialTypeExpectError{ indexExpr->sourceLocation, "struct", SafeCast(i) }; - - break; - } - - default: - break; - } - - parameters.push_back(resolvedType); - break; - } - } - } - - assert(parameters.size() == partialType.type.parameters.size()); - node.cachedExpressionType = partialType.type.buildFunc(parameters.data(), parameters.size(), node.sourceLocation); - } - else - { - if (node.indices.size() != 1) - throw ShaderLang::AstNoIndexError{ node.sourceLocation }; - - for (const auto& indexExpr : node.indices) - { - const ExpressionType* indexType = GetExpressionType(*indexExpr); - if (!indexType) - return ValidationResult::Unresolved; - - if (!IsPrimitiveType(*indexType)) - throw ShaderLang::CompilerIndexRequiresIntegerIndicesError{ node.sourceLocation, ToString(*indexType, indexExpr->sourceLocation) }; - - PrimitiveType primitiveIndexType = std::get(*indexType); - if (primitiveIndexType != PrimitiveType::Int32 && primitiveIndexType != PrimitiveType::UInt32) - throw ShaderLang::CompilerIndexRequiresIntegerIndicesError{ node.sourceLocation, ToString(*indexType, indexExpr->sourceLocation) }; - - if (IsArrayType(resolvedExprType)) - { - const ArrayType& arrayType = std::get(resolvedExprType); - ExpressionType containedType = arrayType.containedType->type; //< Don't overwrite exprType directly since it contains arrayType - resolvedExprType = std::move(containedType); - } - else if (IsStructType(resolvedExprType)) - { - if (primitiveIndexType != PrimitiveType::Int32) - throw ShaderLang::CompilerIndexStructRequiresInt32IndicesError{ node.sourceLocation, ToString(*indexType, indexExpr->sourceLocation) }; - - ConstantValueExpression& constantExpr = static_cast(*indexExpr); - - Int32 index = std::get(constantExpr.value); - - std::size_t structIndex = ResolveStruct(resolvedExprType, indexExpr->sourceLocation); - const StructDescription* s = m_context->structs.Retrieve(structIndex, indexExpr->sourceLocation); - - std::optional resolvedExprTypeOpt = ResolveTypeExpr(s->members[index].type, true, indexExpr->sourceLocation); - if (!resolvedExprTypeOpt.has_value()) - return ValidationResult::Unresolved; - - resolvedExprType = std::move(resolvedExprTypeOpt).value(); - } - else if (IsMatrixType(resolvedExprType)) - { - // Matrix index (ex: mat[2]) - MatrixType matrixType = std::get(resolvedExprType); - - //TODO: Handle row-major matrices - resolvedExprType = VectorType{ matrixType.rowCount, matrixType.type }; - } - else if (IsVectorType(resolvedExprType)) - { - // Swizzle expression with one component (ex: vec[2]) - VectorType swizzledVec = std::get(resolvedExprType); - - resolvedExprType = swizzledVec.type; - } - else - throw ShaderLang::CompilerIndexUnexpectedTypeError{ node.sourceLocation, ToString(*indexType, indexExpr->sourceLocation) }; - } - - node.cachedExpressionType = std::move(resolvedExprType); - } - - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(AssignExpression& node) -> ValidationResult - { - const ExpressionType* leftExprType = GetExpressionType(MandatoryExpr(node.left, node.sourceLocation)); - if (!leftExprType) - return ValidationResult::Unresolved; - - const ExpressionType* rightExprType = GetExpressionType(MandatoryExpr(node.right, node.sourceLocation)); - if (!rightExprType) - return ValidationResult::Unresolved; - - if (GetExpressionCategory(*node.left) != ExpressionCategory::LValue) - throw ShaderLang::CompilerAssignTemporaryError{ node.sourceLocation }; - - std::optional binaryType; - switch (node.op) - { - case AssignType::Simple: - if (TypeMustMatch(node.left, node.right, node.sourceLocation) == ValidationResult::Unresolved) - return ValidationResult::Unresolved; - - break; - - case AssignType::CompoundAdd: binaryType = BinaryType::Add; break; - case AssignType::CompoundDivide: binaryType = BinaryType::Divide; break; - case AssignType::CompoundMultiply: binaryType = BinaryType::Multiply; break; - case AssignType::CompoundLogicalAnd: binaryType = BinaryType::LogicalAnd; break; - case AssignType::CompoundLogicalOr: binaryType = BinaryType::LogicalOr; break; - case AssignType::CompoundSubtract: binaryType = BinaryType::Subtract; break; - } - - if (binaryType) - { - ExpressionType expressionType = ValidateBinaryOp(*binaryType, ResolveAlias(*leftExprType), ResolveAlias(*rightExprType), node.sourceLocation); - TypeMustMatch(*leftExprType, expressionType, node.sourceLocation); - - if (m_context->options.removeCompoundAssignments) - { - node.op = AssignType::Simple; - node.right = ShaderBuilder::Binary(*binaryType, AstCloner::Clone(*node.left), std::move(node.right)); - node.right->cachedExpressionType = std::move(expressionType); - } - } - - node.cachedExpressionType = *leftExprType; - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(BinaryExpression& node) -> ValidationResult - { - const ExpressionType* leftExprType = GetExpressionType(MandatoryExpr(node.left, node.sourceLocation)); - if (!leftExprType) - return ValidationResult::Unresolved; - - const ExpressionType* rightExprType = GetExpressionType(MandatoryExpr(node.right, node.sourceLocation)); - if (!rightExprType) - return ValidationResult::Unresolved; - - node.cachedExpressionType = ValidateBinaryOp(node.op, ResolveAlias(*leftExprType), ResolveAlias(*rightExprType), node.sourceLocation); - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(CallFunctionExpression& node) -> ValidationResult - { - std::size_t targetFuncIndex; - if (node.targetFunction->GetType() == NodeType::FunctionExpression) - targetFuncIndex = static_cast(*node.targetFunction).funcId; - else if (node.targetFunction->GetType() == NodeType::AliasValueExpression) - { - const auto& alias = static_cast(*node.targetFunction); - - const Identifier* aliasIdentifier = ResolveAliasIdentifier(&m_context->aliases.Retrieve(alias.aliasId, node.sourceLocation), node.sourceLocation); - if (aliasIdentifier->target.category != IdentifierCategory::Function) - throw ShaderLang::CompilerFunctionCallExpectedFunctionError{ node.sourceLocation }; - - targetFuncIndex = aliasIdentifier->target.index; - } - else - throw ShaderLang::CompilerFunctionCallExpectedFunctionError{ node.sourceLocation }; - - auto& funcData = m_context->functions.Retrieve(targetFuncIndex, node.sourceLocation); - - const DeclareFunctionStatement* referenceDeclaration = funcData.node; - - if (referenceDeclaration->entryStage.HasValue()) - throw ShaderLang::CompilerFunctionCallUnexpectedEntryFunctionError{ node.sourceLocation, referenceDeclaration->name }; - - for (std::size_t i = 0; i < node.parameters.size(); ++i) - { - const ExpressionType* parameterType = GetExpressionType(*node.parameters[i]); - if (!parameterType) - return ValidationResult::Unresolved; - - if (ResolveAlias(*parameterType) != ResolveAlias(referenceDeclaration->parameters[i].type.GetResultingValue())) - throw ShaderLang::CompilerFunctionCallUnmatchingParameterTypeError{ node.sourceLocation, referenceDeclaration->name, SafeCast(i), ToString(referenceDeclaration->parameters[i].type.GetResultingValue(), referenceDeclaration->parameters[i].sourceLocation), ToString(*parameterType, node.parameters[i]->sourceLocation) }; - } - - if (node.parameters.size() != referenceDeclaration->parameters.size()) - throw ShaderLang::CompilerFunctionCallUnmatchingParameterCountError{ node.sourceLocation, referenceDeclaration->name, SafeCast(referenceDeclaration->parameters.size()), SafeCast(node.parameters.size()) }; - - node.cachedExpressionType = referenceDeclaration->returnType.GetResultingValue(); - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(CastExpression& node) -> ValidationResult - { - std::optional targetTypeOpt = ResolveTypeExpr(node.targetType, false, node.sourceLocation); - if (!targetTypeOpt) - return ValidationResult::Unresolved; - - const ExpressionType& targetType = ResolveAlias(*targetTypeOpt); - - auto& firstExprPtr = MandatoryExpr(node.expressions.front(), node.sourceLocation); - - std::size_t expressionCount = 0; - for (; expressionCount < node.expressions.size(); ++expressionCount) - { - if (!node.expressions[expressionCount]) - break; - } - - if (IsMatrixType(targetType)) - { - const MatrixType& targetMatrixType = std::get(targetType); - - const ExpressionType* firstExprType = GetExpressionType(firstExprPtr); - if (!firstExprType) - return ValidationResult::Unresolved; - - if (IsMatrixType(ResolveAlias(*firstExprType))) - { - if (expressionCount != 1) - throw ShaderLang::CompilerCastComponentMismatchError{ node.sourceLocation, SafeCast(expressionCount), 1 }; - - // Matrix to matrix cast: always valid - } - else - { - // Matrix builder (from vectors) - - assert(targetMatrixType.columnCount <= 4); - if (expressionCount != targetMatrixType.columnCount) - throw ShaderLang::CompilerCastComponentMismatchError{ node.sourceLocation, SafeCast(expressionCount), SafeCast(targetMatrixType.columnCount) }; - - for (std::size_t i = 0; i < targetMatrixType.columnCount; ++i) - { - const auto& exprPtr = node.expressions[i]; - assert(exprPtr); - - const ExpressionType* exprType = GetExpressionType(*exprPtr); - if (!exprType) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedExprType = ResolveAlias(*exprType); - if (!IsVectorType(resolvedExprType)) - throw ShaderLang::CompilerCastMatrixExpectedVectorError{ node.sourceLocation, ToString(resolvedExprType, node.expressions[i]->sourceLocation) }; - - const VectorType& vecType = std::get(resolvedExprType); - if (vecType.componentCount != targetMatrixType.rowCount) - throw ShaderLang::CompilerCastMatrixVectorComponentMismatchError{ node.expressions[i]->sourceLocation, SafeCast(vecType.componentCount), SafeCast(targetMatrixType.rowCount) }; - - if (vecType.type != targetMatrixType.type) - throw ShaderLang::CompilerCastIncompatibleBaseTypesError{ node.expressions[i]->sourceLocation, ToString(targetMatrixType.type, node.sourceLocation), ToString(vecType.type, node.sourceLocation) }; - } - } - } - else if (IsPrimitiveType(targetType)) - { - // Cast between primitive types - if (expressionCount != 1) - throw ShaderLang::CompilerCastComponentMismatchError{ node.sourceLocation, SafeCast(expressionCount), 1 }; - - const ExpressionType* fromType = GetExpressionType(*node.expressions[0]); - if (!fromType) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedFromType = ResolveAlias(*fromType); - if (!IsPrimitiveType(resolvedFromType)) - throw ShaderLang::CompilerCastIncompatibleTypesError{ node.expressions[0]->sourceLocation, ToString(targetType, node.sourceLocation), ToString(resolvedFromType, node.sourceLocation) }; - - PrimitiveType fromPrimitiveType = std::get(resolvedFromType); - PrimitiveType targetPrimitiveType = std::get(targetType); - - bool areTypeCompatibles = [&] - { - switch (targetPrimitiveType) - { - case PrimitiveType::Boolean: - case PrimitiveType::String: - return false; - - case PrimitiveType::Float32: - { - switch (fromPrimitiveType) - { - case PrimitiveType::Boolean: - case PrimitiveType::String: - return false; - - case PrimitiveType::Float32: - case PrimitiveType::Int32: - case PrimitiveType::UInt32: - return true; - } - } - - case PrimitiveType::Int32: - { - switch (fromPrimitiveType) - { - case PrimitiveType::Boolean: - case PrimitiveType::String: - case PrimitiveType::UInt32: - return false; - - case PrimitiveType::Float32: - case PrimitiveType::Int32: - return true; - } - } - - case PrimitiveType::UInt32: - { - switch (fromPrimitiveType) - { - case PrimitiveType::Boolean: - case PrimitiveType::String: - return false; - - case PrimitiveType::Float32: - case PrimitiveType::Int32: - case PrimitiveType::UInt32: - return true; - } - } - } - - throw ShaderLang::AstInternalError{ node.sourceLocation, "unexpected cast from " + ShaderAst::ToString(fromPrimitiveType) + " to " + ShaderAst::ToString(targetPrimitiveType) }; - }(); - - if (!areTypeCompatibles) - throw ShaderLang::CompilerCastIncompatibleTypesError{ node.expressions[0]->sourceLocation, ToString(targetType, node.sourceLocation), ToString(resolvedFromType, node.sourceLocation) }; - } - else if (IsVectorType(targetType)) - { - PrimitiveType targetBaseType = std::get(targetType).type; - - auto GetComponentCount = [](const ExpressionType& exprType) -> std::size_t - { - if (IsVectorType(exprType)) - return std::get(exprType).componentCount; - else - { - assert(IsPrimitiveType(exprType)); - return 1; - } - }; - - std::size_t componentCount = 0; - std::size_t requiredComponents = GetComponentCount(targetType); - - for (auto& exprPtr : node.expressions) - { - if (!exprPtr) - break; - - const ExpressionType* exprType = GetExpressionType(*exprPtr); - if (!exprType) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedExprType = ResolveAlias(*exprType); - if (IsPrimitiveType(resolvedExprType)) - { - PrimitiveType primitiveType = std::get(resolvedExprType); - if (primitiveType != targetBaseType) - throw ShaderLang::CompilerCastIncompatibleBaseTypesError{ exprPtr->sourceLocation, ToString(targetBaseType, node.sourceLocation), ToString(primitiveType, exprPtr->sourceLocation) }; - } - else if (IsVectorType(resolvedExprType)) - { - PrimitiveType primitiveType = std::get(resolvedExprType).type; - if (primitiveType != targetBaseType) - throw ShaderLang::CompilerCastIncompatibleBaseTypesError{ exprPtr->sourceLocation, ToString(targetBaseType, node.sourceLocation), ToString(primitiveType, exprPtr->sourceLocation) }; - } - else - throw ShaderLang::CompilerCastIncompatibleTypesError{ exprPtr->sourceLocation, ToString(targetType, node.sourceLocation), ToString(resolvedExprType, exprPtr->sourceLocation) }; - - componentCount += GetComponentCount(resolvedExprType); - } - - if (componentCount != requiredComponents) - throw ShaderLang::CompilerCastComponentMismatchError{ node.sourceLocation, SafeCast(componentCount), SafeCast(requiredComponents) }; - } - else - throw ShaderLang::CompilerInvalidCastError{ node.sourceLocation, ToString(targetType, node.sourceLocation) }; - - node.cachedExpressionType = targetType; - node.targetType = targetType; - - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(DeclareVariableStatement& node) -> ValidationResult - { - ExpressionType resolvedType; - if (!node.varType.HasValue()) - { - if (!node.initialExpression) - throw ShaderLang::CompilerVarDeclarationMissingTypeAndValueError{ node.sourceLocation }; - - const ExpressionType* initialExprType = GetExpressionType(*node.initialExpression); - if (!initialExprType) - { - RegisterUnresolved(node.varName); - return ValidationResult::Unresolved; - } - - resolvedType = *initialExprType; - } - else - { - std::optional varType = ResolveTypeExpr(node.varType, false, node.sourceLocation); - if (!varType) - { - RegisterUnresolved(node.varName); - return ValidationResult::Unresolved; - } - - resolvedType = std::move(varType).value(); - if (node.initialExpression) - { - const ExpressionType* initialExprType = GetExpressionType(*node.initialExpression); - if (!initialExprType) - { - RegisterUnresolved(node.varName); - return ValidationResult::Unresolved; - } - - TypeMustMatch(resolvedType, *initialExprType, node.sourceLocation); - } - } - - node.varIndex = RegisterVariable(node.varName, resolvedType, node.varIndex, node.sourceLocation); - node.varType = std::move(resolvedType); - - if (m_context->options.makeVariableNameUnique) - { - // Since we are registered, FindIdentifier will find us - auto IgnoreOurself = [varIndex = *node.varIndex](const IdentifierData& identifierData) - { - if (identifierData.category == IdentifierCategory::Variable && identifierData.index == varIndex) - return false; - - return true; - }; - - if (FindIdentifier(node.varName, IgnoreOurself) != nullptr) - { - // Try to make variable name unique by appending _X to its name (incrementing X until it's unique) to the variable name until by incrementing X - unsigned int cloneIndex = 2; - std::string candidateName; - do - { - candidateName = node.varName + "_" + std::to_string(cloneIndex++); - } - while (FindIdentifier(candidateName, IgnoreOurself) != nullptr); - - node.varName = std::move(candidateName); - } - } - - SanitizeIdentifier(node.varName); - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(IntrinsicExpression& node) -> ValidationResult - { - auto IsFloatingPointVector = [](const ExpressionType& type) - { - return type == ExpressionType{ VectorType{ 3, PrimitiveType::Float32 } }; - }; - - auto CheckNotBoolean = [](Expression& expression, const ExpressionType& type) - { - if ((IsPrimitiveType(type) && std::get(type) == PrimitiveType::Boolean) || - (IsVectorType(type) && std::get(type).type == PrimitiveType::Boolean)) - throw ShaderLang::CompilerIntrinsicUnexpectedBooleanError{ expression.sourceLocation }; - }; - - auto CheckFloatingPoint = [](Expression& expression, const ExpressionType& type) - { - if ((IsPrimitiveType(type) && std::get(type) != PrimitiveType::Float32) || - (IsVectorType(type) && std::get(type).type != PrimitiveType::Float32)) - throw ShaderLang::CompilerIntrinsicExpectedFloatError{ expression.sourceLocation }; - }; - - auto SetReturnTypeToFirstParameterType = [&] - { - node.cachedExpressionType = GetExpressionTypeSecure(*node.parameters.front()); - return ValidationResult::Validated; - }; - - auto SetReturnTypeToFirstParameterInnerType = [&] - { - node.cachedExpressionType = std::get(GetExpressionTypeSecure(*node.parameters.front())).type; - return ValidationResult::Validated; - }; - - auto IsUnresolved = [](ValidationResult result) { return result == ValidationResult::Unresolved; }; - - // Parameter validation and return type attribution - switch (node.intrinsic) - { - case IntrinsicType::CrossProduct: - if (IsUnresolved(ValidateIntrinsicParamCount<2>(node)) - || IsUnresolved(ValidateIntrinsicParamMatchingType(node)) - || IsUnresolved(ValidateIntrinsicParameterType<0>(node, IsFloatingPointVector, "floating-point vector"))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterType(); - - case IntrinsicType::DotProduct: - if (IsUnresolved(ValidateIntrinsicParamCount<2>(node)) - || IsUnresolved(ValidateIntrinsicParamMatchingType(node)) - || IsUnresolved(ValidateIntrinsicParameterType<0>(node, IsFloatingPointVector, "floating-point vector"))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterInnerType(); - - case IntrinsicType::Exp: - if (IsUnresolved(ValidateIntrinsicParamCount<1>(node)) - || IsUnresolved(ValidateIntrinsicParameter<0>(node, CheckFloatingPoint))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterType(); - - case IntrinsicType::Length: - if (IsUnresolved(ValidateIntrinsicParamCount<1>(node)) - || IsUnresolved(ValidateIntrinsicParameterType<0>(node, IsFloatingPointVector, "floating-point vector"))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterInnerType(); - - case IntrinsicType::Max: - case IntrinsicType::Min: - if (IsUnresolved(ValidateIntrinsicParamCount<2>(node)) - || IsUnresolved(ValidateIntrinsicParamMatchingType(node)) - || IsUnresolved(ValidateIntrinsicParameter<0>(node, CheckNotBoolean))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterType(); - - case IntrinsicType::Normalize: - if (IsUnresolved(ValidateIntrinsicParamCount<1>(node)) - || IsUnresolved(ValidateIntrinsicParameterType<0>(node, IsFloatingPointVector, "floating-point vector"))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterType(); - - case IntrinsicType::Pow: - if (IsUnresolved(ValidateIntrinsicParamCount<2>(node)) - || IsUnresolved(ValidateIntrinsicParamMatchingType(node)) - || IsUnresolved(ValidateIntrinsicParameter<0>(node, CheckFloatingPoint))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterType(); - - case IntrinsicType::Reflect: - if (IsUnresolved(ValidateIntrinsicParamCount<2>(node)) - || IsUnresolved(ValidateIntrinsicParamMatchingType(node)) - || IsUnresolved(ValidateIntrinsicParameterType<0>(node, IsFloatingPointVector, "floating-point vector"))) - return ValidationResult::Unresolved; - - return SetReturnTypeToFirstParameterType(); - - case IntrinsicType::SampleTexture: - { - if (IsUnresolved(ValidateIntrinsicParamCount<2>(node)) - || IsUnresolved(ValidateIntrinsicParameterType<0>(node, IsSamplerType, "sampler type"))) - return ValidationResult::Unresolved; - - // Special check: vector dimensions must match sample type - const SamplerType& samplerType = std::get(ResolveAlias(GetExpressionTypeSecure(*node.parameters[0]))); - std::size_t requiredComponentCount = 0; - switch (samplerType.dim) - { - case ImageType::E1D: - requiredComponentCount = 1; - break; - - case ImageType::E1D_Array: - case ImageType::E2D: - requiredComponentCount = 2; - break; - - case ImageType::E2D_Array: - case ImageType::E3D: - case ImageType::Cubemap: - requiredComponentCount = 3; - break; - } - - if (requiredComponentCount == 0) - throw ShaderLang::AstInternalError{ node.parameters[0]->sourceLocation, "unhandled sampler dimensions" }; - - auto IsRightType = [=](const ExpressionType& type) - { - return type == ExpressionType{ VectorType{ requiredComponentCount, PrimitiveType::Float32 } }; - }; - - if (IsUnresolved(ValidateIntrinsicParameterType<1>(node, IsRightType, "sampler of requirement components"))) - return ValidationResult::Unresolved; - - node.cachedExpressionType = VectorType{ 4, samplerType.sampledType }; - return ValidationResult::Validated; - } - } - - throw ShaderLang::AstInternalError{ node.sourceLocation, "unhandled intrinsic" }; - } - - auto SanitizeVisitor::Validate(SwizzleExpression& node) -> ValidationResult - { - const ExpressionType* exprType = GetExpressionType(MandatoryExpr(node.expression, node.sourceLocation)); - if (!exprType) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedExprType = ResolveAlias(*exprType); - - if (!IsPrimitiveType(resolvedExprType) && !IsVectorType(resolvedExprType)) - throw ShaderLang::CompilerSwizzleUnexpectedTypeError{ node.sourceLocation, ToString(*exprType, node.expression->sourceLocation) }; - - PrimitiveType baseType; - std::size_t componentCount; - if (IsPrimitiveType(resolvedExprType)) - { - if (m_context->options.removeScalarSwizzling) - throw ShaderLang::AstInternalError{ node.sourceLocation, "scalar swizzling should have been removed before validating" }; - - baseType = std::get(resolvedExprType); - componentCount = 1; - } - else - { - const VectorType& vecType = std::get(resolvedExprType); - baseType = vecType.type; - componentCount = vecType.componentCount; - } - - if (node.componentCount > 4) - throw ShaderLang::CompilerInvalidSwizzleError{ node.sourceLocation }; - - for (std::size_t i = 0; i < node.componentCount; ++i) - { - if (node.components[i] >= componentCount) - throw ShaderLang::CompilerInvalidSwizzleError{ node.sourceLocation }; - } - - if (node.componentCount > 1) - { - node.cachedExpressionType = VectorType{ - node.componentCount, - baseType - }; - } - else - node.cachedExpressionType = baseType; - - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(UnaryExpression& node) -> ValidationResult - { - const ExpressionType* exprType = GetExpressionType(MandatoryExpr(node.expression, node.sourceLocation)); - if (!exprType) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedExprType = ResolveAlias(*exprType); - - switch (node.op) - { - case UnaryType::LogicalNot: - { - if (resolvedExprType != ExpressionType(PrimitiveType::Boolean)) - throw ShaderLang::CompilerUnaryUnsupportedError{ node.sourceLocation, ToString(*exprType, node.sourceLocation) }; - - break; - } - - case UnaryType::Minus: - case UnaryType::Plus: - { - PrimitiveType basicType; - if (IsPrimitiveType(resolvedExprType)) - basicType = std::get(resolvedExprType); - else if (IsVectorType(resolvedExprType)) - basicType = std::get(resolvedExprType).type; - else - throw ShaderLang::CompilerUnaryUnsupportedError{ node.sourceLocation, ToString(*exprType, node.sourceLocation) }; - - if (basicType != PrimitiveType::Float32 && basicType != PrimitiveType::Int32 && basicType != PrimitiveType::UInt32) - throw ShaderLang::CompilerUnaryUnsupportedError{ node.sourceLocation, ToString(*exprType, node.sourceLocation) }; - - break; - } - } - - node.cachedExpressionType = *exprType; - return ValidationResult::Validated; - } - - auto SanitizeVisitor::Validate(VariableValueExpression& node) -> ValidationResult - { - node.cachedExpressionType = m_context->variableTypes.Retrieve(node.variableId, node.sourceLocation); - return ValidationResult::Validated; - } - - ExpressionType SanitizeVisitor::ValidateBinaryOp(BinaryType op, const ExpressionType& leftExprType, const ExpressionType& rightExprType, const ShaderLang::SourceLocation& sourceLocation) - { - if (!IsPrimitiveType(leftExprType) && !IsMatrixType(leftExprType) && !IsVectorType(leftExprType)) - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "left", ToString(leftExprType, sourceLocation) }; - - if (!IsPrimitiveType(rightExprType) && !IsMatrixType(rightExprType) && !IsVectorType(rightExprType)) - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "right", ToString(rightExprType, sourceLocation) }; - - if (IsPrimitiveType(leftExprType)) - { - PrimitiveType leftType = std::get(leftExprType); - switch (op) - { - case BinaryType::CompGe: - case BinaryType::CompGt: - case BinaryType::CompLe: - case BinaryType::CompLt: - if (leftType == PrimitiveType::Boolean) - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "left", ToString(leftExprType, sourceLocation) }; - - [[fallthrough]]; - case BinaryType::CompEq: - case BinaryType::CompNe: - { - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return PrimitiveType::Boolean; - } - - case BinaryType::Add: - case BinaryType::Subtract: - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return leftExprType; - - case BinaryType::Multiply: - case BinaryType::Divide: - { - switch (leftType) - { - case PrimitiveType::Float32: - case PrimitiveType::Int32: - case PrimitiveType::UInt32: - { - if (IsMatrixType(rightExprType)) - { - TypeMustMatch(leftType, std::get(rightExprType).type, sourceLocation); - return rightExprType; - } - else if (IsPrimitiveType(rightExprType)) - { - TypeMustMatch(leftType, rightExprType, sourceLocation); - return leftExprType; - } - else if (IsVectorType(rightExprType)) - { - TypeMustMatch(leftType, std::get(rightExprType).type, sourceLocation); - return rightExprType; - } - else - throw ShaderLang::CompilerBinaryIncompatibleTypesError{ sourceLocation, ToString(leftExprType, sourceLocation), ToString(rightExprType, sourceLocation) }; - - break; - } - - case PrimitiveType::Boolean: - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "left", ToString(leftExprType, sourceLocation) }; - - default: - throw ShaderLang::CompilerBinaryIncompatibleTypesError{ sourceLocation, ToString(leftExprType, sourceLocation), ToString(rightExprType, sourceLocation) }; - } - } - - case BinaryType::LogicalAnd: - case BinaryType::LogicalOr: - { - if (leftType != PrimitiveType::Boolean) - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "left", ToString(leftExprType, sourceLocation) }; - - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return PrimitiveType::Boolean; - } - } - } - else if (IsMatrixType(leftExprType)) - { - const MatrixType& leftType = std::get(leftExprType); - switch (op) - { - case BinaryType::CompGe: - case BinaryType::CompGt: - case BinaryType::CompLe: - case BinaryType::CompLt: - case BinaryType::CompEq: - case BinaryType::CompNe: - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return PrimitiveType::Boolean; - - case BinaryType::Add: - case BinaryType::Subtract: - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return leftExprType; - - case BinaryType::Multiply: - case BinaryType::Divide: - { - if (IsMatrixType(rightExprType)) - { - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return leftExprType; //< FIXME - } - else if (IsPrimitiveType(rightExprType)) - { - TypeMustMatch(leftType.type, rightExprType, sourceLocation); - return leftExprType; - } - else if (IsVectorType(rightExprType)) - { - const VectorType& rightType = std::get(rightExprType); - TypeMustMatch(leftType.type, rightType.type, sourceLocation); - - if (leftType.columnCount != rightType.componentCount) - throw ShaderLang::CompilerBinaryIncompatibleTypesError{ sourceLocation, ToString(leftExprType, sourceLocation), ToString(rightExprType, sourceLocation) }; - - return rightExprType; - } - else - throw ShaderLang::CompilerBinaryIncompatibleTypesError{ sourceLocation, ToString(leftExprType, sourceLocation), ToString(rightExprType, sourceLocation) }; - } - - case BinaryType::LogicalAnd: - case BinaryType::LogicalOr: - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "left", ToString(leftExprType, sourceLocation) }; - } - } - else if (IsVectorType(leftExprType)) - { - const VectorType& leftType = std::get(leftExprType); - switch (op) - { - case BinaryType::CompGe: - case BinaryType::CompGt: - case BinaryType::CompLe: - case BinaryType::CompLt: - case BinaryType::CompEq: - case BinaryType::CompNe: - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return PrimitiveType::Boolean; - - case BinaryType::Add: - case BinaryType::Subtract: - TypeMustMatch(leftExprType, rightExprType, sourceLocation); - return leftExprType; - - case BinaryType::Multiply: - case BinaryType::Divide: - { - if (IsPrimitiveType(rightExprType)) - { - TypeMustMatch(leftType.type, rightExprType, sourceLocation); - return leftExprType; - } - else if (IsVectorType(rightExprType)) - { - TypeMustMatch(leftType, rightExprType, sourceLocation); - return rightExprType; - } - else - throw ShaderLang::CompilerBinaryIncompatibleTypesError{ sourceLocation, ToString(leftExprType, sourceLocation), ToString(rightExprType, sourceLocation) }; - - break; - } - - case BinaryType::LogicalAnd: - case BinaryType::LogicalOr: - throw ShaderLang::CompilerBinaryUnsupportedError{ sourceLocation, "left", ToString(leftExprType, sourceLocation) }; - } - } - - throw ShaderLang::AstInternalError{ sourceLocation, "unchecked operation" }; - } - - - template - auto SanitizeVisitor::ValidateIntrinsicParamCount(IntrinsicExpression& node) -> ValidationResult - { - if (node.parameters.size() != N) - throw ShaderLang::CompilerIntrinsicExpectedParameterCountError{ node.sourceLocation, SafeCast(N) }; - - for (auto& param : node.parameters) - MandatoryExpr(param, node.sourceLocation); - - return ValidationResult::Validated; - } - - auto SanitizeVisitor::ValidateIntrinsicParamMatchingType(IntrinsicExpression& node) -> ValidationResult - { - const ExpressionType* firstParameterType = GetExpressionType(*node.parameters.front()); - if (!firstParameterType) - return ValidationResult::Unresolved; - - for (std::size_t i = 1; i < node.parameters.size(); ++i) - { - const ExpressionType* parameterType = GetExpressionType(*node.parameters[i]); - if (!parameterType) - return ValidationResult::Unresolved; - - if (ResolveAlias(*firstParameterType) != ResolveAlias(*parameterType)) - throw ShaderLang::CompilerIntrinsicUnmatchingParameterTypeError{ node.parameters[i]->sourceLocation }; - } - - return ValidationResult::Validated; - } - - template - auto SanitizeVisitor::ValidateIntrinsicParameter(IntrinsicExpression& node, F&& func) -> ValidationResult - { - assert(node.parameters.size() > N); - auto& parameter = MandatoryExpr(node.parameters[N], node.sourceLocation); - const ExpressionType* type = GetExpressionType(parameter); - if (!type) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedType = ResolveAlias(*type); - func(parameter, resolvedType); - - return ValidationResult::Validated; - } - - template - auto SanitizeVisitor::ValidateIntrinsicParameterType(IntrinsicExpression& node, F&& func, const char* typeStr) -> ValidationResult - { - assert(node.parameters.size() > N); - auto& parameter = MandatoryExpr(node.parameters[N], node.sourceLocation); - - const ExpressionType* type = GetExpressionType(parameter); - if (!type) - return ValidationResult::Unresolved; - - const ExpressionType& resolvedType = ResolveAlias(*type); - if (!func(resolvedType)) - throw ShaderLang::CompilerIntrinsicExpectedTypeError{ parameter.sourceLocation, SafeCast(N), typeStr, ToString(*type, parameter.sourceLocation)}; - - return ValidationResult::Validated; - } - - Expression& SanitizeVisitor::MandatoryExpr(const ExpressionPtr& node, const ShaderLang::SourceLocation& sourceLocation) - { - if (!node) - throw ShaderLang::AstMissingExpressionError{ sourceLocation }; - - return *node; - } - - Statement& SanitizeVisitor::MandatoryStatement(const StatementPtr& node, const ShaderLang::SourceLocation& sourceLocation) - { - if (!node) - throw ShaderLang::AstMissingStatementError{ sourceLocation }; - - return *node; - } - - StatementPtr SanitizeVisitor::Unscope(StatementPtr node) - { - assert(node); - - if (node->GetType() == NodeType::ScopedStatement) - return std::move(static_cast(*node).statement); - else - return node; - } - - UInt32 SanitizeVisitor::ToSwizzleIndex(char c, const ShaderLang::SourceLocation& sourceLocation) - { - switch (c) - { - case 'r': - case 'x': - case 's': - return 0u; - - case 'g': - case 'y': - case 't': - return 1u; - - case 'b': - case 'z': - case 'p': - return 2u; - - case 'a': - case 'w': - case 'q': - return 3u; - - default: - throw ShaderLang::CompilerInvalidSwizzleError{ sourceLocation, std::string(&c, 1) }; - } - } -} diff --git a/src/Nazara/Shader/Debug/NewOverload.cpp b/src/Nazara/Shader/Debug/NewOverload.cpp deleted file mode 100644 index ddf547fb1..000000000 --- a/src/Nazara/Shader/Debug/NewOverload.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#if NAZARA_SHADER_MANAGE_MEMORY - -#include -#include // Nécessaire ? - -void* operator new(std::size_t size) -{ - return Nz::MemoryManager::Allocate(size, false); -} - -void* operator new[](std::size_t size) -{ - return Nz::MemoryManager::Allocate(size, true); -} - -void operator delete(void* pointer) noexcept -{ - Nz::MemoryManager::Free(pointer, false); -} - -void operator delete[](void* pointer) noexcept -{ - Nz::MemoryManager::Free(pointer, true); -} - -#endif // NAZARA_SHADER_MANAGE_MEMORY diff --git a/src/Nazara/Shader/FieldOffsets.cpp b/src/Nazara/Shader/FieldOffsets.cpp deleted file mode 100644 index b6c062400..000000000 --- a/src/Nazara/Shader/FieldOffsets.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz -{ - std::size_t FieldOffsets::AddField(StructFieldType type) - { - std::size_t fieldAlignement = GetAlignement(m_layout, type); - - m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement); - - std::size_t offset = Align(m_size, Align(fieldAlignement, m_offsetRounding)); - m_size = offset + GetSize(type); - - m_offsetRounding = 1; - - return offset; - } - - std::size_t FieldOffsets::AddFieldArray(StructFieldType type, std::size_t arraySize) - { - std::size_t fieldAlignement = GetAlignement(m_layout, type); - if (m_layout == StructLayout::Std140) - fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout::Std140, StructFieldType::Float4)); - - m_largestFieldAlignment = std::max(fieldAlignement, m_largestFieldAlignment); - - std::size_t offset = Align(m_size, Align(fieldAlignement, m_offsetRounding)); - m_size = offset + GetSize(type) * arraySize; - - m_offsetRounding = 1; - - return offset; - } - - std::size_t FieldOffsets::AddMatrix(StructFieldType cellType, unsigned int columns, unsigned int rows, bool columnMajor) - { - assert(GetCount(cellType) == 1); - assert(columns >= 2 && columns <= 4); - assert(rows >= 2 && rows <= 4); - - if (columnMajor) - return AddFieldArray(static_cast(UnderlyingCast(cellType) + rows - 1), columns); - else - return AddFieldArray(static_cast(UnderlyingCast(cellType) + columns - 1), rows); - } - - std::size_t FieldOffsets::AddMatrixArray(StructFieldType cellType, unsigned int columns, unsigned int rows, bool columnMajor, std::size_t arraySize) - { - assert(GetCount(cellType) == 1); - assert(columns >= 2 && columns <= 4); - assert(rows >= 2 && rows <= 4); - - if (columnMajor) - return AddFieldArray(static_cast(UnderlyingCast(cellType) + rows - 1), columns * arraySize); - else - return AddFieldArray(static_cast(UnderlyingCast(cellType) + columns - 1), rows * arraySize); - } - - std::size_t FieldOffsets::AddStruct(const FieldOffsets& fieldStruct) - { - std::size_t fieldAlignement = fieldStruct.GetLargestFieldAlignement(); - if (m_layout == StructLayout::Std140) - fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout::Std140, StructFieldType::Float4)); - - m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement); - - std::size_t offset = Align(m_size, Align(fieldAlignement, m_offsetRounding)); - m_size = offset + fieldStruct.GetSize(); - - m_offsetRounding = std::max(Align(fieldStruct.GetSize(), fieldAlignement) - fieldStruct.GetSize(), 1); - - return offset; - } - - std::size_t FieldOffsets::AddStructArray(const FieldOffsets& fieldStruct, std::size_t arraySize) - { - assert(arraySize > 0); - - std::size_t fieldAlignement = fieldStruct.GetLargestFieldAlignement(); - if (m_layout == StructLayout::Std140) - fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout::Std140, StructFieldType::Float4)); - - m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement); - - std::size_t offset = Align(m_size, Align(fieldAlignement, m_offsetRounding)); - m_size = offset - + fieldStruct.GetSize() * arraySize - + (Align(fieldStruct.GetSize(), fieldAlignement) - fieldStruct.GetSize()) * (arraySize - 1); - - m_offsetRounding = fieldAlignement; - - return offset; - } -} diff --git a/src/Nazara/Shader/FilesystemModuleResolver.cpp b/src/Nazara/Shader/FilesystemModuleResolver.cpp deleted file mode 100644 index 5350070c3..000000000 --- a/src/Nazara/Shader/FilesystemModuleResolver.cpp +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - FilesystemModuleResolver::FilesystemModuleResolver() - { - m_fileWatcher = efsw_create(0); - efsw_watch(m_fileWatcher); - } - - FilesystemModuleResolver::~FilesystemModuleResolver() - { - if (m_fileWatcher) - efsw_release(m_fileWatcher); - } - - void FilesystemModuleResolver::RegisterModule(const std::filesystem::path& realPath) - { - ShaderAst::ModulePtr module; - try - { - std::string ext = realPath.extension().generic_u8string(); - if (ext == CompiledModuleExtension) - { - Nz::File file(realPath); - if (!file.Open(Nz::OpenMode::ReadOnly | Nz::OpenMode::Text)) - throw std::runtime_error("failed to open " + realPath.generic_u8string()); - - std::size_t length = static_cast(file.GetSize()); - - std::vector content(length); - if (length > 0 && file.Read(&content[0], length) != length) - throw std::runtime_error("failed to read " + realPath.generic_u8string()); - - module = ShaderAst::UnserializeShader(content.data(), content.size()); - } - else if (ext == ModuleExtension) - module = ShaderLang::ParseFromFile(realPath); - else - throw std::runtime_error("unknown extension " + ext); - } - catch (const std::exception& e) - { - NazaraError("failed to register module from file " + realPath.generic_u8string() + ": " + e.what()); - return; - } - - if (!module) - return; - - std::string moduleName = module->metadata->moduleName; - RegisterModule(std::move(module)); - - std::filesystem::path canonicalPath = std::filesystem::canonical(realPath); - m_moduleByFilepath.emplace(canonicalPath.generic_u8string(), std::move(moduleName)); - } - - void FilesystemModuleResolver::RegisterModule(std::string_view moduleSource) - { - ShaderAst::ModulePtr module = ShaderLang::Parse(moduleSource); - if (!module) - return; - - return RegisterModule(std::move(module)); - } - - void FilesystemModuleResolver::RegisterModule(ShaderAst::ModulePtr module) - { - assert(module); - - std::string moduleName = module->metadata->moduleName; - if (moduleName.empty()) - throw std::runtime_error("cannot register anonymous module"); - - auto it = m_modules.find(moduleName); - if (it != m_modules.end()) - { - it->second = std::move(module); - - OnModuleUpdated(this, moduleName); - } - else - m_modules.emplace(std::move(moduleName), std::move(module)); - } - - void FilesystemModuleResolver::RegisterModuleDirectory(const std::filesystem::path& realPath, bool watchDirectory) - { - if (!std::filesystem::is_directory(realPath)) - return; - - auto FileSystemCallback = [](efsw_watcher /*watcher*/, efsw_watchid /*watchid*/, const char* dir, const char* filename, efsw_action action, const char* oldFileName, void* param) - { - FilesystemModuleResolver* resolver = static_cast(param); - - switch (action) - { - case EFSW_ADD: - resolver->OnFileAdded(dir, filename); - break; - - case EFSW_DELETE: - resolver->OnFileRemoved(dir, filename); - break; - - case EFSW_MODIFIED: - resolver->OnFileUpdated(dir, filename); - break; - - case EFSW_MOVED: - resolver->OnFileMoved(dir, filename, (oldFileName) ? oldFileName : std::string_view()); - break; - } - }; - - if (watchDirectory) - efsw_addwatch(m_fileWatcher, realPath.generic_u8string().c_str(), FileSystemCallback, 1, this); - - for (const auto& entry : std::filesystem::recursive_directory_iterator(realPath)) - { - if (entry.is_regular_file() && CheckExtension(entry.path().generic_u8string())) - { - try - { - RegisterModule(entry.path()); - } - catch (const std::exception& e) - { - NazaraWarning("failed to register module " + entry.path().generic_u8string() + ": " + e.what()); - } - } - } - } - - ShaderAst::ModulePtr FilesystemModuleResolver::Resolve(const std::string& moduleName) - { - auto it = m_modules.find(moduleName); - if (it == m_modules.end()) - return {}; - - return it->second; - } - - void FilesystemModuleResolver::OnFileAdded(std::string_view directory, std::string_view filename) - { - if (!CheckExtension(filename)) - return; - - RegisterModule(std::filesystem::path(directory) / filename); - } - - void FilesystemModuleResolver::OnFileRemoved(std::string_view directory, std::string_view filename) - { - if (!CheckExtension(filename)) - return; - - std::filesystem::path canonicalPath = std::filesystem::canonical(std::filesystem::path(directory) / filename); - - auto it = m_moduleByFilepath.find(canonicalPath.generic_u8string()); - if (it != m_moduleByFilepath.end()) - { - m_modules.erase(it->second); - m_moduleByFilepath.erase(it); - } - } - - void FilesystemModuleResolver::OnFileMoved(std::string_view directory, std::string_view filename, std::string_view oldFilename) - { - if (oldFilename.empty() || !CheckExtension(oldFilename)) - return; - - std::filesystem::path canonicalPath = std::filesystem::canonical(std::filesystem::path(directory) / oldFilename); - auto it = m_moduleByFilepath.find(canonicalPath.generic_u8string()); - if (it != m_moduleByFilepath.end()) - { - std::filesystem::path newCanonicalPath = std::filesystem::canonical(std::filesystem::path(directory) / filename); - - std::string moduleName = std::move(it->second); - m_moduleByFilepath.erase(it); - - m_moduleByFilepath.emplace(newCanonicalPath.generic_u8string(), std::move(moduleName)); - } - } - - void FilesystemModuleResolver::OnFileUpdated(std::string_view directory, std::string_view filename) - { - if (!CheckExtension(filename)) - return; - - RegisterModule(std::filesystem::path(directory) / filename); - } - - bool FilesystemModuleResolver::CheckExtension(std::string_view filename) - { - return EndsWith(filename, ModuleExtension, Nz::CaseIndependent{}) || EndsWith(filename, CompiledModuleExtension, Nz::CaseIndependent{}); - } -} diff --git a/src/Nazara/Shader/GlslWriter.cpp b/src/Nazara/Shader/GlslWriter.cpp deleted file mode 100644 index 67ad1c02f..000000000 --- a/src/Nazara/Shader/GlslWriter.cpp +++ /dev/null @@ -1,1423 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - namespace - { - static const char* s_glslWriterFlipYUniformName = "_NzFlipYValue"; - static const char* s_glslWriterInputPrefix = "_NzIn_"; - static const char* s_glslWriterOutputPrefix = "_NzOut_"; - static const char* s_glslWriterOutputVarName = "_nzOutput"; - - struct GlslWriterPreVisitor : ShaderAst::AstRecursiveVisitor - { - using AstRecursiveVisitor::Visit; - - void Visit(ShaderAst::CallFunctionExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - assert(currentFunction); - currentFunction->calledFunctions.UnboundedSet(std::get(*GetExpressionType(*node.targetFunction)).funcIndex); - } - - void Visit(ShaderAst::ConditionalExpression& /*node*/) override - { - throw std::runtime_error("unexpected conditional expression, is shader sanitized?"); - } - - void Visit(ShaderAst::ConditionalStatement& /*node*/) override - { - throw std::runtime_error("unexpected conditional statement, is shader sanitized?"); - } - - void Visit(ShaderAst::DeclareFunctionStatement& node) override - { - // Dismiss function if it's an entry point of another type than the one selected - if (node.entryStage.HasValue()) - { - if (selectedStage) - { - if (!node.entryStage.IsResultingValue()) - throw std::runtime_error("unexpected unresolved value for entry attribute, is shader sanitized?"); - - ShaderStageType stage = node.entryStage.GetResultingValue(); - if (stage != *selectedStage) - return; - - assert(!entryPoint); - entryPoint = &node; - } - else - { - if (entryPoint) - throw std::runtime_error("multiple entry point functions found, this is not allowed in GLSL, please select one"); - - entryPoint = &node; - } - } - - assert(node.funcIndex); - assert(functions.find(node.funcIndex.value()) == functions.end()); - FunctionData& funcData = functions[node.funcIndex.value()]; - funcData.name = node.name + moduleSuffix; - funcData.node = &node; - - currentFunction = &funcData; - - AstRecursiveVisitor::Visit(node); - - currentFunction = nullptr; - } - - struct FunctionData - { - std::string name; - Bitset<> calledFunctions; - ShaderAst::DeclareFunctionStatement* node; - }; - - FunctionData* currentFunction = nullptr; - - std::optional selectedStage; - std::string moduleSuffix; - std::unordered_map functions; - ShaderAst::DeclareFunctionStatement* entryPoint = nullptr; - }; - - struct GlslBuiltin - { - std::string_view identifier; - ShaderStageTypeFlags stageFlags; - }; - - constexpr auto s_glslBuiltinMapping = frozen::make_unordered_map({ - { ShaderAst::BuiltinEntry::FragCoord, { "gl_FragCoord", ShaderStageType::Fragment } }, - { ShaderAst::BuiltinEntry::FragDepth, { "gl_FragDepth", ShaderStageType::Fragment } }, - { ShaderAst::BuiltinEntry::VertexPosition, { "gl_Position", ShaderStageType::Vertex } } - }); - } - - - struct GlslWriter::State - { - State(const GlslWriter::BindingMapping& bindings) : - bindingMapping(bindings) - { - } - - struct InOutField - { - std::string memberName; - std::string targetName; - }; - - struct StructData - { - std::string nameOverride; - const ShaderAst::StructDescription* desc; - }; - - std::optional stage; - std::string moduleSuffix; - std::stringstream stream; - std::unordered_map structs; - std::unordered_map variableNames; - std::vector inputFields; - std::vector outputFields; - Bitset<> declaredFunctions; - const GlslWriter::BindingMapping& bindingMapping; - GlslWriterPreVisitor previsitor; - const States* states = nullptr; - bool isInEntryPoint = false; - unsigned int indentLevel = 0; - }; - - std::string GlslWriter::Generate(std::optional shaderStage, const ShaderAst::Module& module, const BindingMapping& bindingMapping, const States& states) - { - State state(bindingMapping); - state.stage = shaderStage; - - m_currentState = &state; - CallOnExit onExit([this]() - { - m_currentState = nullptr; - }); - - ShaderAst::ModulePtr sanitizedModule; - const ShaderAst::Module* targetModule; - if (!states.sanitized) - { - ShaderAst::SanitizeVisitor::Options options = GetSanitizeOptions(); - options.optionValues = states.optionValues; - options.moduleResolver = states.shaderModuleResolver; - - sanitizedModule = ShaderAst::Sanitize(module, options); - targetModule = sanitizedModule.get(); - } - else - targetModule = &module; - - ShaderAst::ModulePtr optimizedModule; - if (states.optimize) - { - ShaderAst::StatementPtr tempAst; - - ShaderAst::DependencyCheckerVisitor::Config dependencyConfig; - if (shaderStage) - dependencyConfig.usedShaderStages = *shaderStage; - - optimizedModule = ShaderAst::PropagateConstants(*targetModule); - optimizedModule = ShaderAst::EliminateUnusedPass(*optimizedModule, dependencyConfig); - - targetModule = optimizedModule.get(); - } - - // Previsitor - state.previsitor.selectedStage = shaderStage; - - for (const auto& importedModule : targetModule->importedModules) - { - state.previsitor.moduleSuffix = importedModule.identifier; - importedModule.module->rootNode->Visit(state.previsitor); - } - - state.previsitor.moduleSuffix = {}; - targetModule->rootNode->Visit(state.previsitor); - - if (!state.previsitor.entryPoint) - throw std::runtime_error("not entry point found"); - - assert(state.previsitor.entryPoint->entryStage.HasValue()); - m_currentState->stage = state.previsitor.entryPoint->entryStage.GetResultingValue(); - - // Code generation - AppendHeader(); - - for (const auto& importedModule : targetModule->importedModules) - { - AppendComment("Module " + importedModule.module->metadata->moduleName); - AppendLine(); - - m_currentState->moduleSuffix = importedModule.identifier; - importedModule.module->rootNode->Visit(*this); - - AppendLine(); - } - - if (!targetModule->importedModules.empty()) - { - AppendComment("Main file"); - AppendLine(); - } - - m_currentState->moduleSuffix = {}; - targetModule->rootNode->Visit(*this); - - return state.stream.str(); - } - - void GlslWriter::SetEnv(Environment environment) - { - m_environment = std::move(environment); - } - - const char* GlslWriter::GetFlipYUniformName() - { - return s_glslWriterFlipYUniformName; - } - - ShaderAst::SanitizeVisitor::Options GlslWriter::GetSanitizeOptions() - { - // Always sanitize for reserved identifiers - ShaderAst::SanitizeVisitor::Options options; - options.makeVariableNameUnique = true; - options.reduceLoopsToWhile = true; - options.removeAliases = true; - options.removeCompoundAssignments = false; - options.removeConstDeclaration = true; - options.removeOptionDeclaration = true; - options.removeScalarSwizzling = true; - options.reservedIdentifiers = { - // All reserved GLSL keywords as of GLSL ES 3.2 - "active", "asm", "atomic_uint", "attribute", "bool", "break", "buffer", "bvec2", "bvec3", "bvec4", "case", "cast", "centroid", "class", "coherent", "common", "const", "continue", "default", "discard", "dmat2", "dmat2x2", "dmat2x3", "dmat2x4", "dmat3", "dmat3x2", "dmat3x3", "dmat3x4", "dmat4", "dmat4x2", "dmat4x3", "dmat4x4", "do", "double", "dvec2", "dvec3", "dvec4", "else", "enum", "extern", "external", "false", "filter", "fixed", "flat", "float", "for", "fvec2", "fvec3", "fvec4", "goto", "half", "highp", "hvec2", "hvec3", "hvec4", "if", "iimage1D", "iimage1DArray", "iimage2D", "iimage2DArray", "iimage2DMS", "iimage2DMSArray", "iimage2DRect", "iimage3D", "iimageBuffer", "iimageCube", "iimageCubeArray", "image1D", "image1DArray", "image2D", "image2DArray", "image2DMS", "image2DMSArray", "image2DRect", "image3D", "imageBuffer", "imageCube", "imageCubeArray", "in", "inline", "inout", "input", "int", "interface", "invariant", "isampler1D", "isampler1DArray", "isampler2D", "isampler2DArray", "isampler2DMS", "isampler2DMSArray", "isampler2DRect", "isampler3D", "isamplerBuffer", "isamplerCube", "isamplerCubeArray", "isubpassInput", "isubpassInputMS", "itexture2D", "itexture2DArray", "itexture2DMS", "itexture2DMSArray", "itexture3D", "itextureBuffer", "itextureCube", "itextureCubeArray", "ivec2", "ivec3", "ivec4", "layout", "long", "lowp", "mat2", "mat2x2", "mat2x3", "mat2x4", "mat3", "mat3x2", "mat3x3", "mat3x4", "mat4", "mat4x2", "mat4x3", "mat4x4", "mediump", "namespace", "noinline", "noperspective", "out", "output", "partition", "patch", "precise", "precision", "public", "readonly", "resource", "restrict", "return", "sample", "sampler", "sampler1D", "sampler1DArray", "sampler1DArrayShadow", "sampler1DShadow", "sampler2D", "sampler2DArray", "sampler2DArrayShadow", "sampler2DMS", "sampler2DMSArray", "sampler2DRect", "sampler2DRectShadow", "sampler2DShadow", "sampler3D", "sampler3DRect", "samplerBuffer", "samplerCube", "samplerCubeArray", "samplerCubeArrayShadow", "samplerCubeShadow", "samplerShadow", "shared", "short", "sizeof", "smooth", "static", "struct", "subpassInput", "subpassInputMS", "subroutine", "superp", "switch", "template", "texture2D", "texture2DArray", "texture2DMS", "texture2DMSArray", "texture3D", "textureBuffer", "textureCube", "textureCubeArray", "this", "true", "typedef", "uimage1D", "uimage1DArray", "uimage2D", "uimage2DArray", "uimage2DMS", "uimage2DMSArray", "uimage2DRect", "uimage3D", "uimageBuffer", "uimageCube", "uimageCubeArray", "uint", "uniform", "union", "unsigned", "usampler1D", "usampler1DArray", "usampler2D", "usampler2DArray", "usampler2DMS", "usampler2DMSArray", "usampler2DRect", "usampler3D", "usamplerBuffer", "usamplerCube", "usamplerCubeArray", "using", "usubpassInput", "usubpassInputMS", "utexture2D", "utexture2DArray", "utexture2DMS", "utexture2DMSArray", "utexture3D", "utextureBuffer", "utextureCube", "utextureCubeArray", "uvec2", "uvec3", "uvec4", "varying", "vec2", "vec3", "vec4", "void", "volatile", "while", "writeonly" - // GLSL functions - "cross", "dot", "exp", "length", "max", "min", "pow", "texture" - }; - - return options; - } - - void GlslWriter::Append(const ShaderAst::AliasType& /*aliasType*/) - { - throw std::runtime_error("unexpected AliasType"); - } - - void GlslWriter::Append(const ShaderAst::ArrayType& /*type*/) - { - throw std::runtime_error("unexpected ArrayType"); - } - - void GlslWriter::Append(ShaderAst::BuiltinEntry builtin) - { - switch (builtin) - { - case ShaderAst::BuiltinEntry::FragCoord: - Append("gl_FragCoord"); - break; - - case ShaderAst::BuiltinEntry::FragDepth: - Append("gl_FragDepth"); - break; - - case ShaderAst::BuiltinEntry::VertexPosition: - Append("gl_Position"); - break; - } - } - - void GlslWriter::Append(const ShaderAst::ExpressionType& type) - { - std::visit([&](auto&& arg) - { - Append(arg); - }, type); - } - - void GlslWriter::Append(const ShaderAst::ExpressionValue& type) - { - Append(type.GetResultingValue()); - } - - void GlslWriter::Append(const ShaderAst::FunctionType& /*functionType*/) - { - throw std::runtime_error("unexpected FunctionType"); - } - - void GlslWriter::Append(const ShaderAst::IntrinsicFunctionType& /*intrinsicFunctionType*/) - { - throw std::runtime_error("unexpected intrinsic function type"); - } - - void GlslWriter::Append(const ShaderAst::MatrixType& matrixType) - { - if (matrixType.columnCount == matrixType.rowCount) - { - Append("mat"); - Append(matrixType.columnCount); - } - else - { - Append("mat"); - Append(matrixType.columnCount); - Append("x"); - Append(matrixType.rowCount); - } - } - - void GlslWriter::Append(const ShaderAst::MethodType& /*methodType*/) - { - throw std::runtime_error("unexpected method type"); - } - - void GlslWriter::Append(ShaderAst::PrimitiveType type) - { - switch (type) - { - case ShaderAst::PrimitiveType::Boolean: return Append("bool"); - case ShaderAst::PrimitiveType::Float32: return Append("float"); - case ShaderAst::PrimitiveType::Int32: return Append("int"); - case ShaderAst::PrimitiveType::UInt32: return Append("uint"); - case ShaderAst::PrimitiveType::String: throw std::runtime_error("unexpected string constant"); - } - } - - void GlslWriter::Append(const ShaderAst::SamplerType& samplerType) - { - switch (samplerType.sampledType) - { - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::Float32: - break; - - case ShaderAst::PrimitiveType::Int32: Append("i"); break; - case ShaderAst::PrimitiveType::UInt32: Append("u"); break; - - case ShaderAst::PrimitiveType::String: throw std::runtime_error("unexpected string type"); - } - - Append("sampler"); - - switch (samplerType.dim) - { - case ImageType::E1D: Append("1D"); break; - case ImageType::E1D_Array: Append("1DArray"); break; - case ImageType::E2D: Append("2D"); break; - case ImageType::E2D_Array: Append("2DArray"); break; - case ImageType::E3D: Append("3D"); break; - case ImageType::Cubemap: Append("Cube"); break; - } - } - - void GlslWriter::Append(const ShaderAst::StructType& structType) - { - const auto& structData = Retrieve(m_currentState->structs, structType.structIndex); - Append(structData.nameOverride); - } - - void GlslWriter::Append(const ShaderAst::Type& /*type*/) - { - throw std::runtime_error("unexpected Type"); - } - - void GlslWriter::Append(const ShaderAst::UniformType& /*uniformType*/) - { - throw std::runtime_error("unexpected UniformType"); - } - - void GlslWriter::Append(const ShaderAst::VectorType& vecType) - { - switch (vecType.type) - { - case ShaderAst::PrimitiveType::Boolean: Append("b"); break; - case ShaderAst::PrimitiveType::Float32: break; - case ShaderAst::PrimitiveType::Int32: Append("i"); break; - case ShaderAst::PrimitiveType::UInt32: Append("u"); break; - case ShaderAst::PrimitiveType::String: throw std::runtime_error("unexpected string type"); - } - - Append("vec"); - Append(vecType.componentCount); - } - - void GlslWriter::Append(ShaderAst::MemoryLayout layout) - { - switch (layout) - { - case ShaderAst::MemoryLayout::Std140: - Append("std140"); - break; - } - } - - void GlslWriter::Append(ShaderAst::NoType) - { - return Append("void"); - } - - template - void GlslWriter::Append(const T& param) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->stream << param; - } - - template - void GlslWriter::Append(const T1& firstParam, const T2& secondParam, Args&&... params) - { - Append(firstParam); - Append(secondParam, std::forward(params)...); - } - - void GlslWriter::AppendComment(const std::string& section) - { - std::size_t lineFeed = section.find('\n'); - if (lineFeed != section.npos) - { - std::size_t previousCut = 0; - - AppendLine("/*"); - do - { - AppendLine(section.substr(previousCut, lineFeed - previousCut)); - previousCut = lineFeed + 1; - } while ((lineFeed = section.find('\n', previousCut)) != section.npos); - AppendLine(section.substr(previousCut)); - AppendLine("*/"); - } - else - AppendLine("// ", section); - } - - void GlslWriter::AppendCommentSection(const std::string& section) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - std::string stars((section.size() < 33) ? (36 - section.size()) / 2 : 3, '*'); - m_currentState->stream << "/*" << stars << ' ' << section << ' ' << stars << "*/"; - AppendLine(); - } - - void GlslWriter::AppendFunctionDeclaration(const ShaderAst::DeclareFunctionStatement& node, const std::string& nameOverride, bool forward) - { - Append(node.returnType, " ", nameOverride, "("); - - bool first = true; - for (const auto& parameter : node.parameters) - { - if (!first) - Append(", "); - - first = false; - - AppendVariableDeclaration(parameter.type.GetResultingValue(), parameter.name); - } - AppendLine((forward) ? ");" : ")"); - } - - void GlslWriter::AppendHeader() - { - unsigned int glslVersion; - unsigned int glVersion = m_environment.glMajorVersion * 100 + m_environment.glMinorVersion * 10; - if (m_environment.glES) - { - if (glVersion >= 300) - glslVersion = glVersion; - else if (m_environment.glMajorVersion >= 2) - glslVersion = 100; - else - throw std::runtime_error("This version of OpenGL ES does not support shaders"); - } - else - { - if (glVersion >= 330) - glslVersion = glVersion; - else if (glVersion >= 320) - glslVersion = 150; - else if (glVersion >= 310) - glslVersion = 140; - else if (glVersion >= 300) - glslVersion = 130; - else if (glVersion >= 210) - glslVersion = 120; - else if (glVersion >= 200) - glslVersion = 110; - else - throw std::runtime_error("This version of OpenGL does not support shaders"); - } - - // Header - Append("#version "); - Append(glslVersion); - if (m_environment.glES) - Append(" es"); - - AppendLine(); - AppendLine(); - - // Comments - std::string fileTitle; - - assert(m_currentState->stage); - switch (*m_currentState->stage) - { - case ShaderStageType::Fragment: fileTitle += "fragment shader - "; break; - case ShaderStageType::Vertex: fileTitle += "vertex shader - "; break; - } - - fileTitle += "this file was generated by Nazara Engine"; - - AppendComment(fileTitle); - AppendLine(); - - // Extensions - - std::vector requiredExtensions; - - if (!m_environment.glES && m_environment.extCallback) - { - // GL_ARB_shading_language_420pack (required for layout(binding = X)) - if (glslVersion < 420) - { - if (m_environment.extCallback("GL_ARB_shading_language_420pack")) - requiredExtensions.emplace_back("GL_ARB_shading_language_420pack"); - } - - // GL_ARB_separate_shader_objects (required for layout(location = X)) - if (glslVersion < 410) - { - if (m_environment.extCallback("GL_ARB_separate_shader_objects")) - requiredExtensions.emplace_back("GL_ARB_separate_shader_objects"); - } - } - - if (!requiredExtensions.empty()) - { - for (const std::string& ext : requiredExtensions) - AppendLine("#extension " + ext + " : require"); - - AppendLine(); - } - - if (m_environment.glES) - { - AppendLine("#if GL_FRAGMENT_PRECISION_HIGH"); - AppendLine("precision highp float;"); - AppendLine("#else"); - AppendLine("precision mediump float;"); - AppendLine("#endif"); - AppendLine(); - } - } - - void GlslWriter::AppendLine(const std::string& txt) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->stream << txt << '\n' << std::string(m_currentState->indentLevel, '\t'); - } - - template - void GlslWriter::AppendLine(Args&&... params) - { - (Append(std::forward(params)), ...); - AppendLine(); - } - - void GlslWriter::AppendStatementList(std::vector& statements) - { - bool first = true; - for (const ShaderAst::StatementPtr& statement : statements) - { - if (statement->GetType() == ShaderAst::NodeType::NoOpStatement) - continue; - - if (!first) - AppendLine(); - - statement->Visit(*this); - - first = false; - } - } - - void GlslWriter::AppendVariableDeclaration(const ShaderAst::ExpressionType& varType, const std::string& varName) - { - if (ShaderAst::IsArrayType(varType)) - { - std::vector lengths; - - const ShaderAst::ExpressionType* exprType = &varType; - while (ShaderAst::IsArrayType(*exprType)) - { - const auto& arrayType = std::get(*exprType); - lengths.push_back(arrayType.length); - - exprType = &arrayType.containedType->type; - } - - assert(!ShaderAst::IsArrayType(*exprType)); - Append(*exprType, " ", varName); - - for (UInt32 lengthAttribute : lengths) - Append("[", lengthAttribute, "]"); - } - else - Append(varType, " ", varName); - } - - void GlslWriter::EnterScope() - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->indentLevel++; - AppendLine("{"); - } - - void GlslWriter::LeaveScope(bool skipLine) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->indentLevel--; - AppendLine(); - - if (skipLine) - AppendLine("}"); - else - Append("}"); - } - - void GlslWriter::HandleEntryPoint(ShaderAst::DeclareFunctionStatement& node) - { - if (node.entryStage.GetResultingValue() == ShaderStageType::Fragment && node.earlyFragmentTests.HasValue() && node.earlyFragmentTests.GetResultingValue()) - { - unsigned int glVersion = m_environment.glMajorVersion * 100 + m_environment.glMinorVersion * 10; - if ((m_environment.glES && glVersion >= 310) || (!m_environment.glES && glVersion >= 420) || (m_environment.extCallback && m_environment.extCallback("GL_ARB_shader_image_load_store"))) - { - AppendLine("layout(early_fragment_tests) in;"); - AppendLine(); - } - } - - HandleInOut(); - AppendLine("void main()"); - EnterScope(); - { - if (!m_currentState->inputFields.empty()) - { - assert(!node.parameters.empty()); - - auto& parameter = node.parameters.front(); - const std::string& varName = parameter.name; - RegisterVariable(*parameter.varIndex, varName); - - assert(IsStructType(parameter.type.GetResultingValue())); - std::size_t structIndex = std::get(parameter.type.GetResultingValue()).structIndex; - const auto& structData = Retrieve(m_currentState->structs, structIndex); - - AppendLine(structData.nameOverride, " ", varName, ";"); - for (const auto& [memberName, targetName] : m_currentState->inputFields) - AppendLine(varName, ".", memberName, " = ", targetName, ";"); - - AppendLine(); - } - - // Output struct is handled on return node - m_currentState->isInEntryPoint = true; - - AppendStatementList(node.statements); - - m_currentState->isInEntryPoint = false; - } - LeaveScope(); - } - - void GlslWriter::HandleInOut() - { - auto AppendInOut = [this](const State::StructData& structData, std::vector& fields, const char* keyword, const char* targetPrefix) - { - for (const auto& member : structData.desc->members) - { - if (member.cond.HasValue() && !member.cond.GetResultingValue()) - continue; - - if (member.builtin.HasValue()) - { - auto it = s_glslBuiltinMapping.find(member.builtin.GetResultingValue()); - assert(it != s_glslBuiltinMapping.end()); - - const GlslBuiltin& builtin = it->second; - if (m_currentState->stage && !builtin.stageFlags.Test(*m_currentState->stage)) - continue; //< This builtin is not active in this stage, skip it - - fields.push_back({ - member.name, - std::string(builtin.identifier) - }); - } - else - { - if (member.locationIndex.HasValue()) - { - Append("layout(location = "); - Append(member.locationIndex.GetResultingValue()); - Append(") "); - } - - Append(keyword, " "); - AppendVariableDeclaration(member.type.GetResultingValue(), targetPrefix + member.name); - AppendLine(";"); - - fields.push_back({ - member.name, - targetPrefix + member.name - }); - } - } - AppendLine(); - }; - - const ShaderAst::DeclareFunctionStatement& node = *m_currentState->previsitor.entryPoint; - - if (!node.parameters.empty()) - { - assert(node.parameters.size() == 1); - auto& parameter = node.parameters.front(); - assert(std::holds_alternative(parameter.type.GetResultingValue())); - - std::size_t inputStructIndex = std::get(parameter.type.GetResultingValue()).structIndex; - const auto& inputStruct = Retrieve(m_currentState->structs, inputStructIndex); - - AppendCommentSection("Inputs"); - AppendInOut(inputStruct, m_currentState->inputFields, "in", s_glslWriterInputPrefix); - } - - if (m_currentState->stage == ShaderStageType::Vertex && m_environment.flipYPosition) - { - AppendLine("uniform float ", s_glslWriterFlipYUniformName, ";"); - AppendLine(); - } - - if (node.returnType.HasValue() && !IsNoType(node.returnType.GetResultingValue())) - { - assert(std::holds_alternative(node.returnType.GetResultingValue())); - std::size_t outputStructIndex = std::get(node.returnType.GetResultingValue()).structIndex; - - const auto& outputStruct = Retrieve(m_currentState->structs, outputStructIndex); - - AppendCommentSection("Outputs"); - AppendInOut(outputStruct, m_currentState->outputFields, "out", s_glslWriterOutputPrefix); - } - } - - void GlslWriter::RegisterStruct(std::size_t structIndex, ShaderAst::StructDescription* desc, std::string structName) - { - assert(m_currentState->structs.find(structIndex) == m_currentState->structs.end()); - State::StructData structData; - structData.desc = desc; - structData.nameOverride = std::move(structName); - - m_currentState->structs.emplace(structIndex, std::move(structData)); - } - - void GlslWriter::RegisterVariable(std::size_t varIndex, std::string varName) - { - assert(m_currentState->variableNames.find(varIndex) == m_currentState->variableNames.end()); - m_currentState->variableNames.emplace(varIndex, std::move(varName)); - } - - void GlslWriter::ScopeVisit(ShaderAst::Statement& node) - { - if (node.GetType() != ShaderAst::NodeType::ScopedStatement) - { - EnterScope(); - node.Visit(*this); - LeaveScope(true); - } - else - node.Visit(*this); - } - - void GlslWriter::Visit(ShaderAst::ExpressionPtr& expr, bool encloseIfRequired) - { - bool enclose = encloseIfRequired && (GetExpressionCategory(*expr) != ShaderAst::ExpressionCategory::LValue); - - if (enclose) - Append("("); - - expr->Visit(*this); - - if (enclose) - Append(")"); - } - - void GlslWriter::Visit(ShaderAst::AccessIdentifierExpression& node) - { - Visit(node.expr, true); - - const ShaderAst::ExpressionType* exprType = GetExpressionType(*node.expr); - assert(exprType); - assert(IsStructType(*exprType)); - - for (const auto& identifierEntry : node.identifiers) - Append(".", identifierEntry.identifier); - } - - void GlslWriter::Visit(ShaderAst::AccessIndexExpression& node) - { - Visit(node.expr, true); - - const ShaderAst::ExpressionType* exprType = GetExpressionType(*node.expr); - assert(exprType); - assert(!IsStructType(*exprType)); - - // Array access - assert(node.indices.size() == 1); - Append("["); - Visit(node.indices.front()); - Append("]"); - } - - void GlslWriter::Visit(ShaderAst::AliasValueExpression& /*node*/) - { - // all aliases should have been handled by sanitizer - throw std::runtime_error("unexpected alias value, is shader sanitized?"); - } - - void GlslWriter::Visit(ShaderAst::AssignExpression& node) - { - node.left->Visit(*this); - - switch (node.op) - { - case ShaderAst::AssignType::Simple: Append(" = "); break; - case ShaderAst::AssignType::CompoundAdd: Append(" += "); break; - case ShaderAst::AssignType::CompoundDivide: Append(" /= "); break; - case ShaderAst::AssignType::CompoundMultiply: Append(" *= "); break; - case ShaderAst::AssignType::CompoundLogicalAnd: Append(" &&= "); break; - case ShaderAst::AssignType::CompoundLogicalOr: Append(" ||= "); break; - case ShaderAst::AssignType::CompoundSubtract: Append(" -= "); break; - } - - node.right->Visit(*this); - } - - void GlslWriter::Visit(ShaderAst::BinaryExpression& node) - { - Visit(node.left, true); - - switch (node.op) - { - case ShaderAst::BinaryType::Add: Append(" + "); break; - case ShaderAst::BinaryType::Subtract: Append(" - "); break; - case ShaderAst::BinaryType::Multiply: Append(" * "); break; - case ShaderAst::BinaryType::Divide: Append(" / "); break; - - case ShaderAst::BinaryType::CompEq: Append(" == "); break; - case ShaderAst::BinaryType::CompGe: Append(" >= "); break; - case ShaderAst::BinaryType::CompGt: Append(" > "); break; - case ShaderAst::BinaryType::CompLe: Append(" <= "); break; - case ShaderAst::BinaryType::CompLt: Append(" < "); break; - case ShaderAst::BinaryType::CompNe: Append(" != "); break; - - case ShaderAst::BinaryType::LogicalAnd: Append(" && "); break; - case ShaderAst::BinaryType::LogicalOr: Append(" || "); break; - } - - Visit(node.right, true); - } - - void GlslWriter::Visit(ShaderAst::CallFunctionExpression& node) - { - node.targetFunction->Visit(*this); - - Append("("); - for (std::size_t i = 0; i < node.parameters.size(); ++i) - { - if (i != 0) - Append(", "); - - node.parameters[i]->Visit(*this); - } - Append(")"); - } - - void GlslWriter::Visit(ShaderAst::CastExpression& node) - { - Append(node.targetType); - Append("("); - - bool first = true; - for (const auto& exprPtr : node.expressions) - { - if (!exprPtr) - break; - - if (!first) - m_currentState->stream << ", "; - - exprPtr->Visit(*this); - first = false; - } - - Append(")"); - } - - void GlslWriter::Visit(ShaderAst::ConstantValueExpression& node) - { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) - Append("i"); //< for ivec - - if constexpr (std::is_same_v) - throw std::runtime_error("invalid type (value expected)"); - else if constexpr (std::is_same_v) - throw std::runtime_error("unexpected string litteral"); - else if constexpr (std::is_same_v) - Append((arg) ? "true" : "false"); - else if constexpr (std::is_same_v || std::is_same_v) - Append(std::to_string(arg)); - else if constexpr (std::is_same_v) - Append(std::to_string(arg), "u"); - else if constexpr (std::is_same_v || std::is_same_v) - Append("vec2(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ")"); - else if constexpr (std::is_same_v || std::is_same_v) - Append("vec3(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ")"); - else if constexpr (std::is_same_v || std::is_same_v) - Append("vec4(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ", " + std::to_string(arg.w) + ")"); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, node.value); - } - - void GlslWriter::Visit(ShaderAst::FunctionExpression& node) - { - const auto& funcData = Retrieve(m_currentState->previsitor.functions, node.funcId); - Append(funcData.name); - } - - void GlslWriter::Visit(ShaderAst::IntrinsicExpression& node) - { - switch (node.intrinsic) - { - case ShaderAst::IntrinsicType::CrossProduct: - Append("cross"); - break; - - case ShaderAst::IntrinsicType::DotProduct: - Append("dot"); - break; - - case ShaderAst::IntrinsicType::Exp: - Append("exp"); - break; - - case ShaderAst::IntrinsicType::Length: - Append("length"); - break; - - case ShaderAst::IntrinsicType::Max: - Append("max"); - break; - - case ShaderAst::IntrinsicType::Min: - Append("min"); - break; - - case ShaderAst::IntrinsicType::Normalize: - Append("normalize"); - break; - - case ShaderAst::IntrinsicType::Pow: - Append("pow"); - break; - - case ShaderAst::IntrinsicType::Reflect: - Append("reflect"); - break; - - case ShaderAst::IntrinsicType::SampleTexture: - Append("texture"); - break; - } - - Append("("); - for (std::size_t i = 0; i < node.parameters.size(); ++i) - { - if (i != 0) - Append(", "); - - node.parameters[i]->Visit(*this); - } - Append(")"); - } - - void GlslWriter::Visit(ShaderAst::SwizzleExpression& node) - { - Visit(node.expression, true); - Append("."); - - const char* componentStr = "xyzw"; - for (std::size_t i = 0; i < node.componentCount; ++i) - Append(componentStr[node.components[i]]); - } - - void GlslWriter::Visit(ShaderAst::UnaryExpression& node) - { - switch (node.op) - { - case ShaderAst::UnaryType::LogicalNot: - Append("!"); - break; - - case ShaderAst::UnaryType::Minus: - Append("-"); - break; - - case ShaderAst::UnaryType::Plus: - Append("+"); - break; - } - - Visit(node.expression); - } - - void GlslWriter::Visit(ShaderAst::VariableValueExpression& node) - { - const std::string& varName = Retrieve(m_currentState->variableNames, node.variableId); - Append(varName); - } - - - void GlslWriter::Visit(ShaderAst::BranchStatement& node) - { - assert(!node.isConst); - - bool first = true; - for (const auto& statement : node.condStatements) - { - if (!first) - Append("else "); - - Append("if ("); - statement.condition->Visit(*this); - AppendLine(")"); - - ScopeVisit(*statement.statement); - - first = false; - } - - if (node.elseStatement) - { - AppendLine("else"); - - ScopeVisit(*node.elseStatement); - } - } - - void GlslWriter::Visit(ShaderAst::DeclareAliasStatement& /*node*/) - { - // all aliases should have been handled by sanitizer - throw std::runtime_error("unexpected alias declaration, is shader sanitized?"); - } - - void GlslWriter::Visit(ShaderAst::DeclareConstStatement& /*node*/) - { - // all consts should have been handled by sanitizer - throw std::runtime_error("unexpected const declaration, is shader sanitized?"); - } - - void GlslWriter::Visit(ShaderAst::DeclareExternalStatement& node) - { - for (const auto& externalVar : node.externalVars) - { - bool isStd140 = false; - if (IsUniformType(externalVar.type.GetResultingValue())) - { - auto& uniform = std::get(externalVar.type.GetResultingValue()); - const auto& structInfo = Retrieve(m_currentState->structs, uniform.containedType.structIndex); - if (structInfo.desc->layout.HasValue()) - isStd140 = structInfo.desc->layout.GetResultingValue() == StructLayout::Std140; - } - - std::string varName = externalVar.name + m_currentState->moduleSuffix; - - if (!m_currentState->bindingMapping.empty() || isStd140) - Append("layout("); - - if (!m_currentState->bindingMapping.empty()) - { - assert(externalVar.bindingIndex.HasValue()); - - UInt64 bindingIndex = externalVar.bindingIndex.GetResultingValue(); - UInt64 bindingSet; - if (externalVar.bindingSet.HasValue()) - bindingSet = externalVar.bindingSet.GetResultingValue(); - else - bindingSet = 0; - - auto bindingIt = m_currentState->bindingMapping.find(bindingSet << 32 | bindingIndex); - if (bindingIt == m_currentState->bindingMapping.end()) - throw std::runtime_error("no binding found for (set=" + std::to_string(bindingSet) + ", binding=" + std::to_string(bindingIndex) + ")"); - - Append("binding = ", bindingIt->second); - if (isStd140) - Append(", "); - } - - if (isStd140) - Append("std140"); - - if (!m_currentState->bindingMapping.empty() || isStd140) - Append(") "); - - Append("uniform "); - - if (IsUniformType(externalVar.type.GetResultingValue())) - { - Append("_NzBinding_"); - AppendLine(varName); - - EnterScope(); - { - const auto& uniform = std::get(externalVar.type.GetResultingValue()); - const auto& structData = Retrieve(m_currentState->structs, uniform.containedType.structIndex); - - bool first = true; - for (const auto& member : structData.desc->members) - { - if (member.cond.HasValue() && !member.cond.GetResultingValue()) - continue; - - if (!first) - AppendLine(); - - first = false; - - AppendVariableDeclaration(member.type.GetResultingValue(), member.name); - Append(";"); - } - } - LeaveScope(false); - - Append(" "); - Append(varName); - } - else - AppendVariableDeclaration(externalVar.type.GetResultingValue(), varName); - - AppendLine(";"); - - if (IsUniformType(externalVar.type.GetResultingValue())) - AppendLine(); - - assert(externalVar.varIndex); - RegisterVariable(*externalVar.varIndex, varName); - } - } - - void GlslWriter::Visit(ShaderAst::DeclareFunctionStatement& node) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - if (node.entryStage.HasValue() && m_currentState->previsitor.entryPoint != &node) - return; //< Ignore other entry points - - assert(node.funcIndex); - auto& funcData = Retrieve(m_currentState->previsitor.functions, node.funcIndex.value()); - - // Declare functions called by this function which aren't already defined - bool hasPredeclaration = false; - for (std::size_t i = funcData.calledFunctions.FindFirst(); i != funcData.calledFunctions.npos; i = funcData.calledFunctions.FindNext(i)) - { - if (!m_currentState->declaredFunctions.UnboundedTest(i)) - { - hasPredeclaration = true; - - auto& targetFunc = Retrieve(m_currentState->previsitor.functions, i); - AppendFunctionDeclaration(*targetFunc.node, targetFunc.name, true); - - m_currentState->declaredFunctions.UnboundedSet(i); - } - } - - if (hasPredeclaration) - AppendLine(); - - if (node.entryStage.HasValue()) - return HandleEntryPoint(node); - - for (const auto& parameter : node.parameters) - { - assert(parameter.varIndex); - RegisterVariable(*parameter.varIndex, parameter.name); - } - - AppendFunctionDeclaration(node, funcData.name); - EnterScope(); - { - AppendStatementList(node.statements); - } - LeaveScope(); - - m_currentState->declaredFunctions.UnboundedSet(node.funcIndex.value()); - } - - void GlslWriter::Visit(ShaderAst::DeclareOptionStatement& /*node*/) - { - // all options should have been handled by sanitizer - throw std::runtime_error("unexpected option declaration, is shader sanitized?"); - } - - void GlslWriter::Visit(ShaderAst::DeclareStructStatement& node) - { - std::string structName = node.description.name + m_currentState->moduleSuffix; - - assert(node.structIndex); - RegisterStruct(*node.structIndex, &node.description, structName); - - Append("struct "); - AppendLine(structName); - EnterScope(); - { - bool first = true; - for (const auto& member : node.description.members) - { - if (member.cond.HasValue() && !member.cond.GetResultingValue()) - continue; - - if (!first) - AppendLine(); - - first = false; - - AppendVariableDeclaration(member.type.GetResultingValue(), member.name); - Append(";"); - } - - // Empty structs are not allowed in GLSL - if (first) - AppendLine("int dummy;"); - } - LeaveScope(false); - AppendLine(";"); - } - - void GlslWriter::Visit(ShaderAst::DeclareVariableStatement& node) - { - assert(node.varIndex); - RegisterVariable(*node.varIndex, node.varName); - - AppendVariableDeclaration(node.varType.GetResultingValue(), node.varName); - if (node.initialExpression) - { - Append(" = "); - node.initialExpression->Visit(*this); - } - - Append(";"); - } - - void GlslWriter::Visit(ShaderAst::DiscardStatement& /*node*/) - { - Append("discard;"); - } - - void GlslWriter::Visit(ShaderAst::ExpressionStatement& node) - { - node.expression->Visit(*this); - Append(";"); - } - - void GlslWriter::Visit(ShaderAst::ImportStatement& /*node*/) - { - throw std::runtime_error("unexpected import statement, is the shader sanitized properly?"); - } - - void GlslWriter::Visit(ShaderAst::MultiStatement& node) - { - AppendStatementList(node.statements); - } - - void GlslWriter::Visit(ShaderAst::NoOpStatement& /*node*/) - { - /* nothing to do */ - } - - void GlslWriter::Visit(ShaderAst::ReturnStatement& node) - { - if (m_currentState->isInEntryPoint) - { - assert(node.returnExpr); - - const ShaderAst::ExpressionType* returnType = GetExpressionType(*node.returnExpr); - assert(returnType); - assert(IsStructType(*returnType)); - std::size_t structIndex = std::get(*returnType).structIndex; - const auto& structData = Retrieve(m_currentState->structs, structIndex); - - std::string outputStructVarName; - if (node.returnExpr->GetType() == ShaderAst::NodeType::VariableValueExpression) - outputStructVarName = Retrieve(m_currentState->variableNames, static_cast(*node.returnExpr).variableId); - else - { - AppendLine(); - Append(structData.nameOverride, " ", s_glslWriterOutputVarName, " = "); - node.returnExpr->Visit(*this); - AppendLine(";"); - - outputStructVarName = s_glslWriterOutputVarName; - } - - AppendLine(); - - for (const auto& [name, targetName] : m_currentState->outputFields) - { - bool isOutputPosition = (m_currentState->stage == ShaderStageType::Vertex && targetName == "gl_Position"); - - AppendLine(targetName, " = ", outputStructVarName, ".", name, ";"); - if (isOutputPosition) - { - // https://veldrid.dev/articles/backend-differences.html - if (m_environment.flipYPosition) - AppendLine(targetName, ".y *= ", s_glslWriterFlipYUniformName, ";"); - - if (m_environment.remapZPosition) - AppendLine(targetName, ".z = ", targetName, ".z * 2.0 - ", targetName, ".w; "); - } - } - - Append("return;"); //< TODO: Don't return if it's the last statement of the function - } - else - { - if (node.returnExpr) - { - Append("return "); - node.returnExpr->Visit(*this); - Append(";"); - } - else - Append("return;"); - } - } - - void GlslWriter::Visit(ShaderAst::ScopedStatement& node) - { - EnterScope(); - node.statement->Visit(*this); - LeaveScope(true); - } - - void GlslWriter::Visit(ShaderAst::WhileStatement& node) - { - Append("while ("); - node.condition->Visit(*this); - AppendLine(")"); - - ScopeVisit(*node.body); - } - - bool GlslWriter::HasExplicitBinding(ShaderAst::StatementPtr& shader) - { - /*for (const auto& uniform : shader.GetUniforms()) - { - if (uniform.bindingIndex.has_value()) - return true; - }*/ - - return false; - } - - bool GlslWriter::HasExplicitLocation(ShaderAst::StatementPtr& shader) - { - /*for (const auto& input : shader.GetInputs()) - { - if (input.locationIndex.has_value()) - return true; - } - - for (const auto& output : shader.GetOutputs()) - { - if (output.locationIndex.has_value()) - return true; - }*/ - - return false; - } -} diff --git a/src/Nazara/Shader/LangWriter.cpp b/src/Nazara/Shader/LangWriter.cpp deleted file mode 100644 index f5d042da9..000000000 --- a/src/Nazara/Shader/LangWriter.cpp +++ /dev/null @@ -1,1287 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - struct LangWriter::BindingAttribute - { - const ShaderAst::ExpressionValue& bindingIndex; - - bool HasValue() const { return bindingIndex.HasValue(); } - }; - - struct LangWriter::BuiltinAttribute - { - const ShaderAst::ExpressionValue& builtin; - - bool HasValue() const { return builtin.HasValue(); } - }; - - struct LangWriter::DepthWriteAttribute - { - const ShaderAst::ExpressionValue& writeMode; - - bool HasValue() const { return writeMode.HasValue(); } - }; - - struct LangWriter::EarlyFragmentTestsAttribute - { - const ShaderAst::ExpressionValue& earlyFragmentTests; - - bool HasValue() const { return earlyFragmentTests.HasValue(); } - }; - - struct LangWriter::EntryAttribute - { - const ShaderAst::ExpressionValue& stageType; - - bool HasValue() const { return stageType.HasValue(); } - }; - - struct LangWriter::LangVersionAttribute - { - UInt32 version; - - bool HasValue() const { return true; } - }; - - struct LangWriter::LayoutAttribute - { - const ShaderAst::ExpressionValue& layout; - - bool HasValue() const { return layout.HasValue(); } - }; - - struct LangWriter::LocationAttribute - { - const ShaderAst::ExpressionValue& locationIndex; - - bool HasValue() const { return locationIndex.HasValue(); } - }; - - struct LangWriter::SetAttribute - { - const ShaderAst::ExpressionValue& setIndex; - - bool HasValue() const { return setIndex.HasValue(); } - }; - - struct LangWriter::UnrollAttribute - { - const ShaderAst::ExpressionValue& unroll; - - bool HasValue() const { return unroll.HasValue(); } - }; - - struct LangWriter::UuidAttribute - { - Uuid uuid; - - bool HasValue() const { return true; } - }; - - struct LangWriter::State - { - struct Identifier - { - std::size_t moduleIndex; - std::string name; - }; - - const States* states = nullptr; - const ShaderAst::Module* module; - std::size_t currentModuleIndex; - std::stringstream stream; - std::unordered_map aliases; - std::unordered_map constants; - std::unordered_map functions; - std::unordered_map structs; - std::unordered_map variables; - std::vector moduleNames; - bool isInEntryPoint = false; - unsigned int indentLevel = 0; - }; - - std::string LangWriter::Generate(const ShaderAst::Module& module, const States& /*states*/) - { - State state; - m_currentState = &state; - CallOnExit onExit([this]() - { - m_currentState = nullptr; - }); - - state.module = &module; - - AppendHeader(); - - // Register imported modules - m_currentState->currentModuleIndex = 0; - for (const auto& importedModule : module.importedModules) - { - AppendAttributes(true, LangVersionAttribute{ importedModule.module->metadata->shaderLangVersion }); - AppendAttributes(true, UuidAttribute{ importedModule.module->metadata->moduleId }); - AppendLine("module ", importedModule.identifier); - EnterScope(); - importedModule.module->rootNode->Visit(*this); - LeaveScope(true); - - m_currentState->currentModuleIndex++; - m_currentState->moduleNames.push_back(importedModule.identifier); - } - - m_currentState->currentModuleIndex = std::numeric_limits::max(); - module.rootNode->Visit(*this); - - return state.stream.str(); - } - - void LangWriter::SetEnv(Environment environment) - { - m_environment = std::move(environment); - } - - void LangWriter::Append(const ShaderAst::AliasType& type) - { - AppendIdentifier(m_currentState->aliases, type.aliasIndex); - } - - void LangWriter::Append(const ShaderAst::ArrayType& type) - { - Append("array[", type.containedType->type, ", ", type.length, "]"); - } - - void LangWriter::Append(const ShaderAst::ExpressionType& type) - { - std::visit([&](auto&& arg) - { - Append(arg); - }, type); - } - - void LangWriter::Append(const ShaderAst::ExpressionValue& type) - { - assert(type.HasValue()); - if (type.IsResultingValue()) - Append(type.GetResultingValue()); - else - type.GetExpression()->Visit(*this); - } - - void LangWriter::Append(const ShaderAst::FunctionType& /*functionType*/) - { - throw std::runtime_error("unexpected function type"); - } - - void LangWriter::Append(const ShaderAst::IntrinsicFunctionType& /*functionType*/) - { - throw std::runtime_error("unexpected intrinsic function type"); - } - - void LangWriter::Append(const ShaderAst::MatrixType& matrixType) - { - if (matrixType.columnCount == matrixType.rowCount) - { - Append("mat"); - Append(matrixType.columnCount); - } - else - { - Append("mat"); - Append(matrixType.columnCount); - Append("x"); - Append(matrixType.rowCount); - } - - Append("[", matrixType.type, "]"); - } - - void LangWriter::Append(const ShaderAst::MethodType& /*functionType*/) - { - throw std::runtime_error("unexpected method type"); - } - - void LangWriter::Append(ShaderAst::PrimitiveType type) - { - switch (type) - { - case ShaderAst::PrimitiveType::Boolean: return Append("bool"); - case ShaderAst::PrimitiveType::Float32: return Append("f32"); - case ShaderAst::PrimitiveType::Int32: return Append("i32"); - case ShaderAst::PrimitiveType::UInt32: return Append("u32"); - case ShaderAst::PrimitiveType::String: return Append("string"); - } - } - - void LangWriter::Append(const ShaderAst::SamplerType& samplerType) - { - Append("sampler"); - - switch (samplerType.dim) - { - case ImageType::E1D: Append("1D"); break; - case ImageType::E1D_Array: Append("1DArray"); break; - case ImageType::E2D: Append("2D"); break; - case ImageType::E2D_Array: Append("2DArray"); break; - case ImageType::E3D: Append("3D"); break; - case ImageType::Cubemap: Append("Cube"); break; - } - - Append("[", samplerType.sampledType, "]"); - } - - void LangWriter::Append(const ShaderAst::StructType& structType) - { - AppendIdentifier(m_currentState->structs, structType.structIndex); - } - - void LangWriter::Append(const ShaderAst::Type& /*type*/) - { - throw std::runtime_error("unexpected type?"); - } - - void LangWriter::Append(const ShaderAst::UniformType& uniformType) - { - Append("uniform[", uniformType.containedType, "]"); - } - - void LangWriter::Append(const ShaderAst::VectorType& vecType) - { - Append("vec", vecType.componentCount, "[", vecType.type, "]"); - } - - void LangWriter::Append(ShaderAst::NoType) - { - return Append("()"); - } - - template - void LangWriter::Append(const T& param) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->stream << param; - } - - template - void LangWriter::Append(const T1& firstParam, const T2& secondParam, Args&&... params) - { - Append(firstParam); - Append(secondParam, std::forward(params)...); - } - - template - void LangWriter::AppendAttributes(bool appendLine, Args&&... params) - { - bool hasAnyAttribute = (params.HasValue() || ...); - if (!hasAnyAttribute) - return; - - bool first = true; - - Append("["); - AppendAttributesInternal(first, std::forward(params)...); - Append("]"); - - if (appendLine) - AppendLine(); - else - Append(" "); - } - - template - void LangWriter::AppendAttributesInternal(bool& first, const T& param) - { - if (!param.HasValue()) - return; - - if (!first) - Append(", "); - - first = false; - - AppendAttribute(param); - } - - template - void LangWriter::AppendAttributesInternal(bool& first, const T1& firstParam, const T2& secondParam, Rest&&... params) - { - AppendAttributesInternal(first, firstParam); - AppendAttributesInternal(first, secondParam, std::forward(params)...); - } - - void LangWriter::AppendAttribute(BindingAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("binding("); - - if (attribute.bindingIndex.IsResultingValue()) - Append(attribute.bindingIndex.GetResultingValue()); - else - attribute.bindingIndex.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(BuiltinAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("builtin("); - - if (attribute.builtin.IsResultingValue()) - { - switch (attribute.builtin.GetResultingValue()) - { - case ShaderAst::BuiltinEntry::FragCoord: - Append("fragcoord"); - break; - - case ShaderAst::BuiltinEntry::FragDepth: - Append("fragdepth"); - break; - - case ShaderAst::BuiltinEntry::VertexPosition: - Append("position"); - break; - } - } - else - attribute.builtin.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(DepthWriteAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("depth_write("); - - if (attribute.writeMode.IsResultingValue()) - { - switch (attribute.writeMode.GetResultingValue()) - { - case ShaderAst::DepthWriteMode::Greater: - Append("greater"); - break; - - case ShaderAst::DepthWriteMode::Less: - Append("less"); - break; - - case ShaderAst::DepthWriteMode::Replace: - Append("replace"); - break; - - case ShaderAst::DepthWriteMode::Unchanged: - Append("unchanged"); - break; - } - } - else - attribute.writeMode.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(EarlyFragmentTestsAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("early_fragment_tests("); - - if (attribute.earlyFragmentTests.IsResultingValue()) - { - if (attribute.earlyFragmentTests.GetResultingValue()) - Append("true"); - else - Append("false"); - } - else - attribute.earlyFragmentTests.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(EntryAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("entry("); - - if (attribute.stageType.IsResultingValue()) - { - switch (attribute.stageType.GetResultingValue()) - { - case ShaderStageType::Fragment: - Append("frag"); - break; - - case ShaderStageType::Vertex: - Append("vert"); - break; - } - } - else - attribute.stageType.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(LangVersionAttribute attribute) - { - UInt32 shaderLangVersion = attribute.version; - UInt32 majorVersion = shaderLangVersion / 100; - shaderLangVersion -= majorVersion * 100; - - UInt32 minorVersion = shaderLangVersion / 10; - shaderLangVersion -= minorVersion * 100; - - UInt32 patchVersion = shaderLangVersion; - - // nzsl_version - Append("nzsl_version(\"", majorVersion, ".", minorVersion); - if (patchVersion != 0) - Append(".", patchVersion); - - Append("\")"); - } - - void LangWriter::AppendAttribute(LayoutAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("layout("); - if (attribute.layout.IsResultingValue()) - { - switch (attribute.layout.GetResultingValue()) - { - case StructLayout::Packed: - Append("packed"); - break; - - case StructLayout::Std140: - Append("std140"); - break; - } - } - else - attribute.layout.GetExpression()->Visit(*this); - Append(")"); - } - - void LangWriter::AppendAttribute(LocationAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("location("); - - if (attribute.locationIndex.IsResultingValue()) - Append(attribute.locationIndex.GetResultingValue()); - else - attribute.locationIndex.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(SetAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("set("); - - if (attribute.setIndex.IsResultingValue()) - Append(attribute.setIndex.GetResultingValue()); - else - attribute.setIndex.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(UnrollAttribute attribute) - { - if (!attribute.HasValue()) - return; - - Append("unroll("); - - if (attribute.unroll.IsResultingValue()) - { - switch (attribute.unroll.GetResultingValue()) - { - case ShaderAst::LoopUnroll::Always: - Append("always"); - break; - - case ShaderAst::LoopUnroll::Hint: - Append("hint"); - break; - - case ShaderAst::LoopUnroll::Never: - Append("never"); - break; - - default: - break; - } - } - else - attribute.unroll.GetExpression()->Visit(*this); - - Append(")"); - } - - void LangWriter::AppendAttribute(UuidAttribute attribute) - { - Append("uuid(\"", attribute.uuid.ToString(), "\")"); - } - - void LangWriter::AppendComment(const std::string& section) - { - std::size_t lineFeed = section.find('\n'); - if (lineFeed != section.npos) - { - std::size_t previousCut = 0; - - AppendLine("/*"); - do - { - AppendLine(section.substr(previousCut, lineFeed - previousCut)); - previousCut = lineFeed + 1; - } - while ((lineFeed = section.find('\n', previousCut)) != section.npos); - AppendLine(section.substr(previousCut)); - AppendLine("*/"); - } - else - AppendLine("// ", section); - } - - void LangWriter::AppendCommentSection(const std::string& section) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - std::string stars((section.size() < 33) ? (36 - section.size()) / 2 : 3, '*'); - m_currentState->stream << "/*" << stars << ' ' << section << ' ' << stars << "*/"; - AppendLine(); - } - - void LangWriter::AppendLine(const std::string& txt) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->stream << txt << '\n' << std::string(m_currentState->indentLevel, '\t'); - } - - template - void LangWriter::AppendIdentifier(const T& map, std::size_t id) - { - const auto& structIdentifier = Retrieve(map, id); - if (structIdentifier.moduleIndex != m_currentState->currentModuleIndex) - Append(m_currentState->moduleNames[structIdentifier.moduleIndex], '.'); - - Append(structIdentifier.name); - } - - template - void LangWriter::AppendLine(Args&&... params) - { - (Append(std::forward(params)), ...); - AppendLine(); - } - - void LangWriter::AppendStatementList(std::vector& statements) - { - bool first = true; - for (const ShaderAst::StatementPtr& statement : statements) - { - if (statement->GetType() == ShaderAst::NodeType::NoOpStatement) - continue; - - if (!first) - AppendLine(); - - statement->Visit(*this); - - first = false; - } - } - - void LangWriter::EnterScope() - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->indentLevel++; - AppendLine("{"); - } - - void LangWriter::LeaveScope(bool skipLine) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - m_currentState->indentLevel--; - AppendLine(); - - if (skipLine) - AppendLine("}"); - else - Append("}"); - } - - void LangWriter::RegisterAlias(std::size_t aliasIndex, std::string aliasName) - { - State::Identifier identifier; - identifier.moduleIndex = m_currentState->currentModuleIndex; - identifier.name = std::move(aliasName); - - assert(m_currentState->aliases.find(aliasIndex) == m_currentState->aliases.end()); - m_currentState->aliases.emplace(aliasIndex, std::move(identifier)); - } - - void LangWriter::RegisterConstant(std::size_t constantIndex, std::string constantName) - { - State::Identifier identifier; - identifier.moduleIndex = m_currentState->currentModuleIndex; - identifier.name = std::move(constantName); - - assert(m_currentState->constants.find(constantIndex) == m_currentState->constants.end()); - m_currentState->constants.emplace(constantIndex, std::move(identifier)); - } - - void LangWriter::RegisterFunction(std::size_t funcIndex, std::string functionName) - { - State::Identifier identifier; - identifier.moduleIndex = m_currentState->currentModuleIndex; - identifier.name = std::move(functionName); - - assert(m_currentState->functions.find(funcIndex) == m_currentState->functions.end()); - m_currentState->functions.emplace(funcIndex, std::move(identifier)); - } - - void LangWriter::RegisterStruct(std::size_t structIndex, std::string structName) - { - State::Identifier identifier; - identifier.moduleIndex = m_currentState->currentModuleIndex; - identifier.name = std::move(structName); - - assert(m_currentState->structs.find(structIndex) == m_currentState->structs.end()); - m_currentState->structs.emplace(structIndex, std::move(identifier)); - } - - void LangWriter::RegisterVariable(std::size_t varIndex, std::string varName) - { - State::Identifier identifier; - identifier.moduleIndex = m_currentState->currentModuleIndex; - identifier.name = std::move(varName); - - assert(m_currentState->variables.find(varIndex) == m_currentState->variables.end()); - m_currentState->variables.emplace(varIndex, std::move(identifier)); - } - - void LangWriter::ScopeVisit(ShaderAst::Statement& node) - { - if (node.GetType() != ShaderAst::NodeType::ScopedStatement) - { - EnterScope(); - node.Visit(*this); - LeaveScope(true); - } - else - node.Visit(*this); - } - - void LangWriter::Visit(ShaderAst::ExpressionPtr& expr, bool encloseIfRequired) - { - bool enclose = encloseIfRequired && (GetExpressionCategory(*expr) != ShaderAst::ExpressionCategory::LValue); - - if (enclose) - Append("("); - - expr->Visit(*this); - - if (enclose) - Append(")"); - } - - void LangWriter::Visit(ShaderAst::AccessIdentifierExpression& node) - { - Visit(node.expr, true); - - for (const auto& identifierEntry : node.identifiers) - Append(".", identifierEntry.identifier); - } - - void LangWriter::Visit(ShaderAst::AccessIndexExpression& node) - { - Visit(node.expr, true); - - // Array access - Append("["); - - bool first = true; - for (ShaderAst::ExpressionPtr& expr : node.indices) - { - if (!first) - Append(", "); - - expr->Visit(*this); - first = false; - } - - Append("]"); - } - - void LangWriter::Visit(ShaderAst::AliasValueExpression& node) - { - AppendIdentifier(m_currentState->aliases, node.aliasId); - } - - void LangWriter::Visit(ShaderAst::AssignExpression& node) - { - node.left->Visit(*this); - - switch (node.op) - { - case ShaderAst::AssignType::Simple: Append(" = "); break; - case ShaderAst::AssignType::CompoundAdd: Append(" += "); break; - case ShaderAst::AssignType::CompoundDivide: Append(" /= "); break; - case ShaderAst::AssignType::CompoundMultiply: Append(" *= "); break; - case ShaderAst::AssignType::CompoundLogicalAnd: Append(" &&= "); break; - case ShaderAst::AssignType::CompoundLogicalOr: Append(" ||= "); break; - case ShaderAst::AssignType::CompoundSubtract: Append(" -= "); break; - } - - node.right->Visit(*this); - } - - void LangWriter::Visit(ShaderAst::BranchStatement& node) - { - bool first = true; - for (const auto& statement : node.condStatements) - { - if (first) - { - if (node.isConst) - Append("const "); - } - else - Append("else "); - - Append("if ("); - statement.condition->Visit(*this); - AppendLine(")"); - - ScopeVisit(*statement.statement); - - first = false; - } - - if (node.elseStatement) - { - AppendLine("else"); - - ScopeVisit(*node.elseStatement); - } - } - - void LangWriter::Visit(ShaderAst::BinaryExpression& node) - { - Visit(node.left, true); - - switch (node.op) - { - case ShaderAst::BinaryType::Add: Append(" + "); break; - case ShaderAst::BinaryType::Subtract: Append(" - "); break; - case ShaderAst::BinaryType::Multiply: Append(" * "); break; - case ShaderAst::BinaryType::Divide: Append(" / "); break; - - case ShaderAst::BinaryType::CompEq: Append(" == "); break; - case ShaderAst::BinaryType::CompGe: Append(" >= "); break; - case ShaderAst::BinaryType::CompGt: Append(" > "); break; - case ShaderAst::BinaryType::CompLe: Append(" <= "); break; - case ShaderAst::BinaryType::CompLt: Append(" < "); break; - case ShaderAst::BinaryType::CompNe: Append(" != "); break; - - case ShaderAst::BinaryType::LogicalAnd: Append(" && "); break; - case ShaderAst::BinaryType::LogicalOr: Append(" || "); break; - } - - Visit(node.right, true); - } - - void LangWriter::Visit(ShaderAst::CallFunctionExpression& node) - { - node.targetFunction->Visit(*this); - - Append("("); - for (std::size_t i = 0; i < node.parameters.size(); ++i) - { - if (i != 0) - Append(", "); - - node.parameters[i]->Visit(*this); - } - Append(")"); - } - - void LangWriter::Visit(ShaderAst::CastExpression& node) - { - Append(node.targetType); - Append("("); - - bool first = true; - for (const auto& exprPtr : node.expressions) - { - if (!exprPtr) - break; - - if (!first) - m_currentState->stream << ", "; - - exprPtr->Visit(*this); - first = false; - } - - Append(")"); - } - - void LangWriter::Visit(ShaderAst::ConditionalExpression& node) - { - Append("const_select("); - node.condition->Visit(*this); - Append(", "); - node.truePath->Visit(*this); - Append(", "); - node.falsePath->Visit(*this); - Append(")"); - } - - void LangWriter::Visit(ShaderAst::ConditionalStatement& node) - { - Append("[cond("); - node.condition->Visit(*this); - AppendLine(")]"); - node.statement->Visit(*this); - } - - void LangWriter::Visit(ShaderAst::DeclareAliasStatement& node) - { - if (node.aliasIndex) - RegisterAlias(*node.aliasIndex, node.name); - - Append("alias ", node.name, " = "); - assert(node.expression); - node.expression->Visit(*this); - AppendLine(";"); - } - - void LangWriter::Visit(ShaderAst::DeclareConstStatement& node) - { - if (node.constIndex) - RegisterConstant(*node.constIndex, node.name); - - Append("const ", node.name); - if (node.type.HasValue()) - Append(": ", node.type); - - if (node.expression) - { - Append(" = "); - node.expression->Visit(*this); - } - - AppendLine(";"); - } - - void LangWriter::Visit(ShaderAst::ConstantValueExpression& node) - { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - throw std::runtime_error("invalid type (value expected)"); - else if constexpr (std::is_same_v) - Append((arg) ? "true" : "false"); - else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) - Append(std::to_string(arg)); - else if constexpr (std::is_same_v) - Append('"', arg, '"'); //< TODO: Escape string - else if constexpr (std::is_same_v) - Append("vec2[f32](" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ")"); - else if constexpr (std::is_same_v) - Append("vec2(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ")"); - else if constexpr (std::is_same_v) - Append("vec3[f32](" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ")"); - else if constexpr (std::is_same_v) - Append("vec3(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ")"); - else if constexpr (std::is_same_v) - Append("vec4[f32](" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ", " + std::to_string(arg.w) + ")"); - else if constexpr (std::is_same_v) - Append("vec4(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ", " + std::to_string(arg.w) + ")"); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, node.value); - } - - void LangWriter::Visit(ShaderAst::ConstantExpression& node) - { - AppendIdentifier(m_currentState->constants, node.constantId); - } - - void LangWriter::Visit(ShaderAst::FunctionExpression& node) - { - AppendIdentifier(m_currentState->functions, node.funcId); - } - - void LangWriter::Visit(ShaderAst::IdentifierExpression& node) - { - Append(node.identifier); - } - - void LangWriter::Visit(ShaderAst::DeclareExternalStatement& node) - { - AppendLine("external"); - EnterScope(); - - bool first = true; - for (const auto& externalVar : node.externalVars) - { - if (!first) - AppendLine(","); - - first = false; - - AppendAttributes(false, SetAttribute{ externalVar.bindingSet }, BindingAttribute{ externalVar.bindingIndex }); - Append(externalVar.name, ": ", externalVar.type); - - if (externalVar.varIndex) - RegisterVariable(*externalVar.varIndex, externalVar.name); - } - - LeaveScope(); - } - - void LangWriter::Visit(ShaderAst::DeclareFunctionStatement& node) - { - NazaraAssert(m_currentState, "This function should only be called while processing an AST"); - - if (node.funcIndex) - RegisterFunction(*node.funcIndex, node.name); - - AppendAttributes(true, EntryAttribute{ node.entryStage }, EarlyFragmentTestsAttribute{ node.earlyFragmentTests }, DepthWriteAttribute{ node.depthWrite }); - Append("fn ", node.name, "("); - for (std::size_t i = 0; i < node.parameters.size(); ++i) - { - const auto& parameter = node.parameters[i]; - - if (i != 0) - Append(", "); - - Append(parameter.name); - Append(": "); - Append(parameter.type); - - if (parameter.varIndex) - RegisterVariable(*parameter.varIndex, parameter.name); - } - Append(")"); - if (node.returnType.HasValue()) - { - if (!node.returnType.IsResultingValue() || !IsNoType(node.returnType.GetResultingValue())) - Append(" -> ", node.returnType); - } - - AppendLine(); - EnterScope(); - { - AppendStatementList(node.statements); - } - LeaveScope(); - } - - void LangWriter::Visit(ShaderAst::DeclareOptionStatement& node) - { - if (node.optIndex) - RegisterConstant(*node.optIndex, node.optName); - - Append("option ", node.optName); - if (node.optType.HasValue()) - Append(": ", node.optType); - - if (node.defaultValue) - { - Append(" = "); - node.defaultValue->Visit(*this); - } - - Append(";"); - } - - void LangWriter::Visit(ShaderAst::DeclareStructStatement& node) - { - if (node.structIndex) - RegisterStruct(*node.structIndex, node.description.name); - - AppendAttributes(true, LayoutAttribute{ node.description.layout }); - Append("struct "); - AppendLine(node.description.name); - EnterScope(); - { - bool first = true; - for (const auto& member : node.description.members) - { - if (!first) - AppendLine(","); - - first = false; - - AppendAttributes(false, LocationAttribute{ member.locationIndex }, BuiltinAttribute{ member.builtin }); - Append(member.name, ": ", member.type); - } - } - LeaveScope(); - } - - void LangWriter::Visit(ShaderAst::DeclareVariableStatement& node) - { - if (node.varIndex) - RegisterVariable(*node.varIndex, node.varName); - - Append("let ", node.varName); - if (node.varType.HasValue()) - Append(": ", node.varType); - - if (node.initialExpression) - { - Append(" = "); - node.initialExpression->Visit(*this); - } - - Append(";"); - } - - void LangWriter::Visit(ShaderAst::DiscardStatement& /*node*/) - { - Append("discard;"); - } - - void LangWriter::Visit(ShaderAst::ExpressionStatement& node) - { - node.expression->Visit(*this); - Append(";"); - } - - void LangWriter::Visit(ShaderAst::ForStatement& node) - { - if (node.varIndex) - RegisterVariable(*node.varIndex, node.varName); - - AppendAttributes(true, UnrollAttribute{ node.unroll }); - Append("for ", node.varName, " in "); - node.fromExpr->Visit(*this); - Append(" -> "); - node.toExpr->Visit(*this); - - if (node.stepExpr) - { - Append(" : "); - node.stepExpr->Visit(*this); - } - - AppendLine(); - - ScopeVisit(*node.statement); - } - - void LangWriter::Visit(ShaderAst::ForEachStatement& node) - { - if (node.varIndex) - RegisterVariable(*node.varIndex, node.varName); - - AppendAttributes(true, UnrollAttribute{ node.unroll }); - Append("for ", node.varName, " in "); - node.expression->Visit(*this); - AppendLine(); - - ScopeVisit(*node.statement); - } - - void LangWriter::Visit(ShaderAst::ImportStatement& node) - { - Append("import ", node.moduleName, ";"); - } - - void LangWriter::Visit(ShaderAst::IntrinsicExpression& node) - { - bool method = false; - switch (node.intrinsic) - { - case ShaderAst::IntrinsicType::CrossProduct: - Append("cross"); - break; - - case ShaderAst::IntrinsicType::DotProduct: - Append("dot"); - break; - - case ShaderAst::IntrinsicType::Exp: - Append("exp"); - break; - - case ShaderAst::IntrinsicType::Length: - Append("length"); - break; - - case ShaderAst::IntrinsicType::Max: - Append("max"); - break; - - case ShaderAst::IntrinsicType::Min: - Append("min"); - break; - - case ShaderAst::IntrinsicType::Normalize: - Append("normalize"); - break; - - case ShaderAst::IntrinsicType::Pow: - Append("pow"); - break; - - case ShaderAst::IntrinsicType::Reflect: - Append("reflect"); - break; - - case ShaderAst::IntrinsicType::SampleTexture: - assert(!node.parameters.empty()); - Visit(node.parameters.front(), true); - Append(".Sample"); - method = true; - break; - } - - Append("("); - bool first = true; - for (std::size_t i = (method) ? 1 : 0; i < node.parameters.size(); ++i) - { - if (!first) - Append(", "); - - first = false; - - node.parameters[i]->Visit(*this); - } - Append(")"); - } - - void LangWriter::Visit(ShaderAst::StructTypeExpression& node) - { - AppendIdentifier(m_currentState->structs, node.structTypeId); - } - - void LangWriter::Visit(ShaderAst::MultiStatement& node) - { - AppendStatementList(node.statements); - } - - void LangWriter::Visit(ShaderAst::NoOpStatement& /*node*/) - { - /* nothing to do */ - } - - void LangWriter::Visit(ShaderAst::ReturnStatement& node) - { - if (node.returnExpr) - { - Append("return "); - node.returnExpr->Visit(*this); - Append(";"); - } - else - Append("return;"); - } - - void LangWriter::Visit(ShaderAst::ScopedStatement& node) - { - EnterScope(); - node.statement->Visit(*this); - LeaveScope(); - } - - void LangWriter::Visit(ShaderAst::SwizzleExpression& node) - { - Visit(node.expression, true); - Append("."); - - const char* componentStr = "xyzw"; - for (std::size_t i = 0; i < node.componentCount; ++i) - Append(componentStr[node.components[i]]); - } - - void LangWriter::Visit(ShaderAst::VariableValueExpression& node) - { - AppendIdentifier(m_currentState->variables, node.variableId); - } - - void LangWriter::Visit(ShaderAst::UnaryExpression& node) - { - switch (node.op) - { - case ShaderAst::UnaryType::LogicalNot: - Append("!"); - break; - - case ShaderAst::UnaryType::Minus: - Append("-"); - break; - - case ShaderAst::UnaryType::Plus: - Append("+"); - break; - } - - node.expression->Visit(*this); - } - - void LangWriter::Visit(ShaderAst::WhileStatement& node) - { - Append("while ("); - node.condition->Visit(*this); - AppendLine(")"); - - ScopeVisit(*node.body); - } - - void LangWriter::AppendHeader() - { - AppendAttributes(true, LangVersionAttribute{ m_currentState->module->metadata->shaderLangVersion }); - AppendLine("module;"); - AppendLine(); - } -} diff --git a/src/Nazara/Shader/Shader.cpp b/src/Nazara/Shader/Shader.cpp deleted file mode 100644 index b70114ef2..000000000 --- a/src/Nazara/Shader/Shader.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - Shader::Shader(Config /*config*/) : - ModuleBase("Shader", this) - { - } - - Shader* Shader::s_instance = nullptr; -} diff --git a/src/Nazara/Shader/ShaderLangErrors.cpp b/src/Nazara/Shader/ShaderLangErrors.cpp deleted file mode 100644 index d4cd756f9..000000000 --- a/src/Nazara/Shader/ShaderLangErrors.cpp +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -// https://fmt.dev/latest/api.html#udt -template <> -struct fmt::formatter : formatter -{ - template - auto format(const Nz::ShaderAst::AttributeType& p, FormatContext& ctx) -> decltype(ctx.out()) - { - // TODO: Add ToString - std::string_view name = ""; - switch (p) - { - case Nz::ShaderAst::AttributeType::Binding: name = "binding"; break; - case Nz::ShaderAst::AttributeType::Builtin: name = "builtin"; break; - case Nz::ShaderAst::AttributeType::Cond: name = "cond"; break; - case Nz::ShaderAst::AttributeType::DepthWrite: name = "depth_write"; break; - case Nz::ShaderAst::AttributeType::EarlyFragmentTests: name = "early_fragment_tests"; break; - case Nz::ShaderAst::AttributeType::Entry: name = "entry"; break; - case Nz::ShaderAst::AttributeType::Export: name = "export"; break; - case Nz::ShaderAst::AttributeType::Layout: name = "layout"; break; - case Nz::ShaderAst::AttributeType::Location: name = "location"; break; - case Nz::ShaderAst::AttributeType::LangVersion: name = "nzsl_version"; break; - case Nz::ShaderAst::AttributeType::Set: name = "set"; break; - case Nz::ShaderAst::AttributeType::Unroll: name = "unroll"; break; - case Nz::ShaderAst::AttributeType::Uuid: name = "uuid"; break; - } - - return formatter::format(name, ctx); - } -}; - -template <> -struct fmt::formatter : formatter -{ - template - auto format(const Nz::ShaderLang::ErrorCategory& p, FormatContext& ctx) -> decltype(ctx.out()) - { - return formatter::format(ToString(p), ctx); - } -}; - -template <> -struct fmt::formatter : formatter -{ - template - auto format(const Nz::ShaderLang::ErrorType& p, FormatContext& ctx) -> decltype(ctx.out()) - { - return formatter::format(ToString(p), ctx); - } -}; - -template <> -struct fmt::formatter : formatter -{ - template - auto format(const Nz::ShaderStageType& p, FormatContext& ctx) -> decltype(ctx.out()) - { - // TODO: Add ToString - std::string_view name = ""; - switch (p) - { - case Nz::ShaderStageType::Fragment: name = "fragment"; break; - case Nz::ShaderStageType::Vertex: name = "vertex"; break; - } - - return formatter::format(name, ctx); - } -}; - -template <> -struct fmt::formatter : formatter -{ - template - auto format(const Nz::ShaderLang::TokenType& p, FormatContext& ctx) -> decltype(ctx.out()) - { - return formatter::format(ToString(p), ctx); - } -}; - -namespace Nz::ShaderLang -{ - std::string_view ToString(ErrorCategory errorCategory) - { - switch (errorCategory) - { - case ErrorCategory::Ast: return "Ast"; - case ErrorCategory::Compilation: return "Compilation"; - case ErrorCategory::Lexing: return "Lexing"; - case ErrorCategory::Parsing: return "Parsing"; - } - - return ""; - } - - std::string_view ToString(ErrorType errorType) - { - switch (errorType) - { -#define NAZARA_SHADERLANG_ERROR(ErrorPrefix, ErrorName, ...) case ErrorType:: ErrorPrefix ## ErrorName: return #ErrorPrefix #ErrorName; - -#include - } - - return ""; - } - - const std::string& Error::GetErrorMessage() const - { - if (m_errorMessage.empty()) - m_errorMessage = BuildErrorMessage(); - - return m_errorMessage; - } - - const std::string& Error::GetFullErrorMessage() const - { - if (m_fullErrorMessage.empty()) - { - if (m_sourceLocation.IsValid()) - { - std::string_view sourceFile; - if (m_sourceLocation.file) - sourceFile = *m_sourceLocation.file; - - if (m_sourceLocation.startLine != m_sourceLocation.endLine) - m_fullErrorMessage = fmt::format("{}({} -> {},{} -> {}): {} error: {}", sourceFile, m_sourceLocation.startLine, m_sourceLocation.endLine, m_sourceLocation.startColumn, m_sourceLocation.endColumn, m_errorType, GetErrorMessage()); - else if (m_sourceLocation.startColumn != m_sourceLocation.endColumn) - m_fullErrorMessage = fmt::format("{}({},{} -> {}): {} error: {}", sourceFile, m_sourceLocation.startLine, m_sourceLocation.startColumn, m_sourceLocation.endColumn, m_errorType, GetErrorMessage()); - else - m_fullErrorMessage = fmt::format("{}({}, {}): {} error: {}", sourceFile, m_sourceLocation.startLine, m_sourceLocation.startColumn, m_errorType, GetErrorMessage()); - } - else - m_fullErrorMessage = fmt::format("?: {} error: {}", m_errorType, GetErrorMessage()); - } - - return m_fullErrorMessage; - } - - const char* Error::what() const noexcept - { - return GetFullErrorMessage().c_str(); - } - -#define NAZARA_SHADERLANG_NEWERRORTYPE(Prefix, ErrorType, ErrorName, ErrorString, ...) \ - std::string Prefix ## ErrorName ## Error::BuildErrorMessage() const \ - { \ - return std::apply([&](const auto... args) { return fmt::format(ErrorString, args...); }, m_parameters); \ - } - -#define NAZARA_SHADERLANG_AST_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Ast, A, ErrorName, ErrorString, __VA_ARGS__) -#define NAZARA_SHADERLANG_LEXER_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Lexer, L, ErrorName, ErrorString, __VA_ARGS__) -#define NAZARA_SHADERLANG_PARSER_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Parser, P, ErrorName, ErrorString, __VA_ARGS__) -#define NAZARA_SHADERLANG_COMPILER_ERROR(ErrorName, ErrorString, ...) NAZARA_SHADERLANG_NEWERRORTYPE(Compiler, C, ErrorName, ErrorString, __VA_ARGS__) - -#include - -#undef NAZARA_SHADERLANG_NEWERRORTYPE -} diff --git a/src/Nazara/Shader/ShaderLangLexer.cpp b/src/Nazara/Shader/ShaderLangLexer.cpp deleted file mode 100644 index 1f6f0834c..000000000 --- a/src/Nazara/Shader/ShaderLangLexer.cpp +++ /dev/null @@ -1,562 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderLang -{ - namespace - { - class ForceCLocale - { - public: - ForceCLocale() - { - m_previousLocale = std::locale::global(std::locale::classic()); - } - - ~ForceCLocale() - { - std::locale::global(m_previousLocale); - } - - private: - std::locale m_previousLocale; - }; - - constexpr auto s_reservedKeywords = frozen::make_unordered_map({ - { "alias", TokenType::Alias }, - { "const", TokenType::Const }, - { "const_select", TokenType::ConstSelect }, - { "discard", TokenType::Discard }, - { "else", TokenType::Else }, - { "external", TokenType::External }, - { "false", TokenType::BoolFalse }, - { "fn", TokenType::FunctionDeclaration }, - { "for", TokenType::For }, - { "if", TokenType::If }, - { "import", TokenType::Import }, - { "in", TokenType::In }, - { "let", TokenType::Let }, - { "module", TokenType::Module }, - { "option", TokenType::Option }, - { "return", TokenType::Return }, - { "struct", TokenType::Struct }, - { "true", TokenType::BoolTrue }, - { "while", TokenType::While } - }); - } - - std::vector Tokenize(const std::string_view& str, const std::string& filePath) - { - // Can't use std::from_chars for double, thanks to libc++ and libstdc++ developers for being lazy, so we have to force C locale - ForceCLocale forceCLocale; - - std::size_t currentPos = 0; - - auto Peek = [&](std::size_t advance = 1) -> char - { - if (currentPos + advance < str.size() && str[currentPos + advance] != '\0') - return str[currentPos + advance]; - else - return '\0'; - }; - - auto IsAlphaNum = [&](const char c) - { - return std::isalnum(c) || c == '_'; - }; - - UInt32 currentLine = 1; - std::size_t lineStartPos = 0; - std::vector tokens; - - auto HandleNewLine = [&] - { - currentLine++; - lineStartPos = currentPos + 1; - }; - - std::shared_ptr currentFile; - if (!filePath.empty()) - currentFile = std::make_shared(filePath); - - for (;;) - { - char c = Peek(0); - - Token token; - token.location.startColumn = SafeCast(currentPos - lineStartPos) + 1; - token.location.startLine = currentLine; - token.location.file = currentFile; - - if (c == '\0') - { - token.type = TokenType::EndOfStream; - tokens.push_back(std::move(token)); - break; - } - - std::optional tokenType; - switch (c) - { - case ' ': - case '\t': - case '\r': - break; //< Ignore blank spaces - - case '\n': - HandleNewLine(); - break; - - case '-': - { - char next = Peek(); - if (next == '>') - { - currentPos++; - tokenType = TokenType::Arrow; - break; - } - else if (next == '=') - { - currentPos++; - tokenType = TokenType::MinusAssign; - } - else - tokenType = TokenType::Minus; - - break; - } - - case '/': - { - char next = Peek(); - if (next == '/') - { - // Line comment - do - { - currentPos++; - next = Peek(); - } - while (next != -1 && next != '\n'); - } - else if (next == '*') - { - // Block comment - do - { - currentPos++; - next = Peek(); - - if (next == '*') - { - currentPos++; - if (Peek() == '/') - { - currentPos++; - break; - } - } - else if (next == '\n') - HandleNewLine(); - } - while (next != -1); - } - else if (next == '=') - { - currentPos++; - tokenType = TokenType::DivideAssign; - } - else - tokenType = TokenType::Divide; - - break; - } - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - bool floatingPoint = false; - - std::size_t start = currentPos; - char next = Peek(); - - if (next == 'x' || next == 'X') - currentPos++; - - for (;;) - { - next = Peek(); - - if (!isdigit(next)) - { - if (next != '.') - break; - - if (floatingPoint) - break; - - floatingPoint = true; - } - - currentPos++; - } - - token.location.endColumn = SafeCast(currentPos - lineStartPos) + 1; - token.location.endLine = currentLine; - - if (floatingPoint) - { - tokenType = TokenType::FloatingPointValue; - - std::string valueStr(str.substr(start, currentPos - start + 1)); - - const char* ptr = valueStr.c_str(); - - char* end; - double value = std::strtod(ptr, &end); - if (end != &ptr[valueStr.size()]) - throw LexerBadNumberError{ token.location }; - - token.data = value; - } - else - { - tokenType = TokenType::IntegerValue; - - // avoid std::string_view operator[] assertions (if &str[currentPos + 1] is out of the string) - const char* first = &str[start]; - const char* last = first + (currentPos - start + 1); - - long long value; - std::from_chars_result r = std::from_chars(first, last, value); - if (r.ptr == last && r.ec == std::errc{}) - token.data = value; - else if (r.ec == std::errc::result_out_of_range) - throw LexerNumberOutOfRangeError{ token.location }; - else - throw LexerBadNumberError{ token.location }; - } - - break; - } - - case '=': - { - char next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::Equal; - } - else - tokenType = TokenType::Assign; - - break; - } - - case '|': - { - char next = Peek(); - if (next == '|') - { - currentPos++; - next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::LogicalOrAssign; - } - else - tokenType = TokenType::LogicalOr; - } - else - throw LexerUnrecognizedTokenError{ token.location }; //< TODO: Add BOR (a | b) - - break; - } - - case '&': - { - char next = Peek(); - if (next == '&') - { - currentPos++; - next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::LogicalAndAssign; - } - else - tokenType = TokenType::LogicalAnd; - } - else - throw LexerUnrecognizedTokenError{ token.location }; //< TODO: Add BAND (a & b) - - break; - } - - case '<': - { - char next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::LessThanEqual; - } - else - tokenType = TokenType::LessThan; - - break; - } - - case '>': - { - char next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::GreaterThanEqual; - } - else - tokenType = TokenType::GreaterThan; - - break; - } - - case '!': - { - char next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::NotEqual; - } - else - tokenType = TokenType::Not; - - break; - } - - case '+': - { - char next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::PlusAssign; - } - else - tokenType = TokenType::Plus; - - break; - } - - case '*': - { - char next = Peek(); - if (next == '=') - { - currentPos++; - tokenType = TokenType::MultiplyAssign; - } - else - tokenType = TokenType::Multiply; - - break; - } - - case ':': tokenType = TokenType::Colon; break; - case ';': tokenType = TokenType::Semicolon; break; - case '.': tokenType = TokenType::Dot; break; - case ',': tokenType = TokenType::Comma; break; - case '{': tokenType = TokenType::OpenCurlyBracket; break; - case '}': tokenType = TokenType::ClosingCurlyBracket; break; - case '(': tokenType = TokenType::OpenParenthesis; break; - case ')': tokenType = TokenType::ClosingParenthesis; break; - case '[': tokenType = TokenType::OpenSquareBracket; break; - case ']': tokenType = TokenType::ClosingSquareBracket; break; - - case '"': - { - // string litteral - currentPos++; - - std::string litteral; - - char current; - while ((current = Peek(0)) != '"') - { - char character; - switch (current) - { - case '\0': - case '\n': - case '\r': - token.location.endColumn = SafeCast(currentPos - lineStartPos) + 1; - token.location.endLine = currentLine; - throw LexerUnfinishedStringError{ token.location }; - - case '\\': - { - currentPos++; - char next = Peek(0); - switch (next) - { - case 'n': character = '\n'; break; - case 'r': character = '\r'; break; - case 't': character = '\t'; break; - case '"': character = '"'; break; - case '\\': character = '\\'; break; - default: - token.location.endColumn = SafeCast(currentPos - lineStartPos) + 1; - token.location.endLine = currentLine; - throw LexerUnrecognizedCharError{ token.location }; - } - break; - } - - default: - character = current; - break; - } - - litteral.push_back(character); - currentPos++; - } - - tokenType = TokenType::StringValue; - token.data = std::move(litteral); - break; - } - - default: - { - if (IsAlphaNum(c)) - { - std::size_t start = currentPos; - - while (IsAlphaNum(Peek())) - currentPos++; - - std::string_view identifier = str.substr(start, currentPos - start + 1); - if (auto it = s_reservedKeywords.find(identifier); it == s_reservedKeywords.end()) - { - tokenType = TokenType::Identifier; - token.data = std::string(identifier); - } - else - tokenType = it->second; - - break; - } - else - { - token.location.endColumn = SafeCast(currentPos - lineStartPos) + 1; - token.location.endLine = currentLine; - throw LexerUnrecognizedTokenError{ token.location }; - } - } - } - - if (tokenType) - { - token.location.endColumn = SafeCast(currentPos - lineStartPos) + 1; - token.location.endLine = currentLine; - token.type = *tokenType; - - tokens.push_back(std::move(token)); - } - - currentPos++; - } - - return tokens; - } - - const char* ToString(TokenType tokenType) - { - switch (tokenType) - { -#define NAZARA_SHADERLANG_TOKEN(X) case TokenType:: X: return #X; - -#include - } - - return ""; - } - - std::string ToString(const std::vector& tokens, bool pretty) - { - if (tokens.empty()) - return {}; - - unsigned int lastLineNumber = tokens.front().location.startLine; - - std::stringstream ss; - bool empty = true; - - for (const Token& token : tokens) - { - if (token.location.startLine != lastLineNumber && pretty) - { - lastLineNumber = token.location.startLine; - if (!empty) - ss << '\n'; - } - else if (!empty) - ss << ' '; - - ss << ToString(token.type); - switch (token.type) - { - case TokenType::FloatingPointValue: - ss << "(" << std::get(token.data) << ")"; - break; - - case TokenType::Identifier: - ss << "(" << std::get(token.data) << ")"; - break; - - case TokenType::IntegerValue: - ss << "(" << std::get(token.data) << ")"; - break; - - case TokenType::StringValue: - ss << "(\"" << std::get(token.data) << "\")"; - break; - - default: - break; - } - - empty = false; - } - - return std::move(ss).str(); - } -} diff --git a/src/Nazara/Shader/ShaderLangParser.cpp b/src/Nazara/Shader/ShaderLangParser.cpp deleted file mode 100644 index 9a3eed375..000000000 --- a/src/Nazara/Shader/ShaderLangParser.cpp +++ /dev/null @@ -1,1563 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz::ShaderLang -{ - namespace NAZARA_ANONYMOUS_NAMESPACE - { - constexpr auto s_depthWriteModes = frozen::make_unordered_map({ - { "greater", ShaderAst::DepthWriteMode::Greater }, - { "less", ShaderAst::DepthWriteMode::Less }, - { "replace", ShaderAst::DepthWriteMode::Replace }, - { "unchanged", ShaderAst::DepthWriteMode::Unchanged }, - }); - - constexpr auto s_identifierToAttributeType = frozen::make_unordered_map({ - { "binding", ShaderAst::AttributeType::Binding }, - { "builtin", ShaderAst::AttributeType::Builtin }, - { "cond", ShaderAst::AttributeType::Cond }, - { "depth_write", ShaderAst::AttributeType::DepthWrite }, - { "early_fragment_tests", ShaderAst::AttributeType::EarlyFragmentTests }, - { "entry", ShaderAst::AttributeType::Entry }, - { "export", ShaderAst::AttributeType::Export }, - { "layout", ShaderAst::AttributeType::Layout }, - { "location", ShaderAst::AttributeType::Location }, - { "nzsl_version", ShaderAst::AttributeType::LangVersion }, - { "set", ShaderAst::AttributeType::Set }, - { "unroll", ShaderAst::AttributeType::Unroll }, - { "uuid", ShaderAst::AttributeType::Uuid }, - }); - - constexpr auto s_entryPoints = frozen::make_unordered_map({ - { "frag", ShaderStageType::Fragment }, - { "vert", ShaderStageType::Vertex }, - }); - - constexpr auto s_builtinMapping = frozen::make_unordered_map({ - { "fragcoord", ShaderAst::BuiltinEntry::FragCoord }, - { "fragdepth", ShaderAst::BuiltinEntry::FragDepth }, - { "position", ShaderAst::BuiltinEntry::VertexPosition } - }); - - constexpr auto s_layoutMapping = frozen::make_unordered_map({ - { "std140", StructLayout::Std140 } - }); - - constexpr auto s_unrollModes = frozen::make_unordered_map({ - { "always", ShaderAst::LoopUnroll::Always }, - { "hint", ShaderAst::LoopUnroll::Hint }, - { "never", ShaderAst::LoopUnroll::Never } - }); - } - - ShaderAst::ModulePtr Parser::Parse(const std::vector& tokens) - { - Context context; - context.tokenCount = tokens.size(); - context.tokens = tokens.data(); - - m_context = &context; - - std::vector attributes; - - for (;;) - { - ShaderAst::StatementPtr statement = ParseRootStatement(); - if (!m_context->module) - { - const Token& nextToken = Peek(); - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - } - - if (!statement) - break; - - m_context->module->rootNode->statements.push_back(std::move(statement)); - } - - return std::move(context.module); - } - - const Token& Parser::Advance() - { - const Token& token = Peek(); - m_context->tokenIndex++; - - return token; - } - - void Parser::Consume(std::size_t count) - { - assert(m_context->tokenIndex + count < m_context->tokenCount); - m_context->tokenIndex += count; - } - - const Token& Parser::Expect(const Token& token, TokenType type) - { - if (token.type != type) - throw ParserExpectedTokenError{ token.location, type, token.type }; - - return token; - } - - const Token& Parser::ExpectNot(const Token& token, TokenType type) - { - if (token.type == type) - throw ParserUnexpectedTokenError{ token.location, type }; - - return token; - } - - const Token& Parser::Expect(TokenType type) - { - const Token& token = Peek(); - Expect(token, type); - - return token; - } - - const Token& Parser::Peek(std::size_t advance) - { - assert(m_context->tokenIndex + advance < m_context->tokenCount); - return m_context->tokens[m_context->tokenIndex + advance]; - } - - std::vector Parser::ParseAttributes() - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - std::vector attributes; - - Expect(Advance(), TokenType::OpenSquareBracket); - - bool expectComma = false; - for (;;) - { - const Token& t = Peek(); - ExpectNot(t, TokenType::EndOfStream); - - if (t.type == TokenType::ClosingSquareBracket) - { - // Parse [attribute1] [attribute2] the same as [attribute1, attribute2] - if (Peek(1).type == TokenType::OpenSquareBracket) - { - Consume(2); - expectComma = false; - continue; - } - - break; - } - - if (expectComma) - Expect(Advance(), TokenType::Comma); - - const Token& identifierToken = Expect(Advance(), TokenType::Identifier); - std::string_view identifier = std::get(identifierToken.data); - - SourceLocation attributeLocation = identifierToken.location; - - auto it = s_identifierToAttributeType.find(identifier); - if (it == s_identifierToAttributeType.end()) - throw ParserUnknownAttributeError{ identifierToken.location }; - - ShaderAst::AttributeType attributeType = it->second; - - ShaderAst::ExpressionPtr arg; - if (Peek().type == TokenType::OpenParenthesis) - { - Consume(); - - arg = ParseExpression(); - - const Token& closeToken = Expect(Advance(), TokenType::ClosingParenthesis); - attributeLocation.ExtendToRight(closeToken.location); - } - - expectComma = true; - - attributes.push_back({ - attributeType, - std::move(arg), - attributeLocation - }); - } - - Expect(Advance(), TokenType::ClosingSquareBracket); - - return attributes; - } - - void Parser::ParseModuleStatement(std::vector attributes) - { - if (m_context->parsingImportedModule) - { - const Token& token = Peek(); - throw ParserUnexpectedTokenError{ token.location, token.type }; - } - - const Token& moduleToken = Expect(Advance(), TokenType::Module); - - std::optional moduleVersion; - std::optional moduleId; - - for (auto&& [attributeType, expr, location] : attributes) - { - switch (attributeType) - { - case ShaderAst::AttributeType::LangVersion: - { - // Version parsing - if (moduleVersion.has_value()) - throw ParserAttributeMultipleUniqueError{ location, attributeType }; - - if (!expr) - throw ParserAttributeMissingParameterError{ location, attributeType }; - - if (expr->GetType() != ShaderAst::NodeType::ConstantValueExpression) - throw ParserAttributeExpectStringError{ location, attributeType }; - - auto& constantValue = SafeCast(*expr); - if (ShaderAst::GetConstantType(constantValue.value) != ShaderAst::ExpressionType{ ShaderAst::PrimitiveType::String }) - throw ParserAttributeExpectStringError{ location, attributeType }; - - const std::string& versionStr = std::get(constantValue.value); - - std::regex versionRegex(R"(^(\d+)(\.(\d+)(\.(\d+))?)?$)", std::regex::ECMAScript); - - std::smatch versionMatch; - if (!std::regex_match(versionStr, versionMatch, versionRegex)) - throw ParserInvalidVersionError{ location, versionStr }; - - assert(versionMatch.size() == 6); - - std::uint32_t version = 0; - version += std::stoi(versionMatch[1]) * 100; - - if (versionMatch.length(3) > 0) - version += std::stoi(versionMatch[3]) * 10; - - if (versionMatch.length(5) > 0) - version += std::stoi(versionMatch[5]) * 1; - - moduleVersion = version; - break; - } - - case ShaderAst::AttributeType::Uuid: - { - if (moduleId.has_value()) - throw ParserAttributeMultipleUniqueError{ location, attributeType }; - - if (!expr) - throw ParserAttributeMissingParameterError{ location, attributeType }; - - if (expr->GetType() != ShaderAst::NodeType::ConstantValueExpression) - throw ParserAttributeExpectStringError{ location, attributeType }; - - auto& constantValue = SafeCast(*expr); - if (ShaderAst::GetConstantType(constantValue.value) != ShaderAst::ExpressionType{ ShaderAst::PrimitiveType::String }) - throw ParserAttributeExpectStringError{ location, attributeType }; - - const std::string& uuidStr = std::get(constantValue.value); - - Uuid uuid = Uuid::FromString(uuidStr); - if (uuid.IsNull()) - throw ParserInvalidUuidError{ location, uuidStr }; - - moduleId = uuid; - break; - } - - default: - throw ParserUnexpectedAttributeError{ location, attributeType }; - } - } - - if (!moduleVersion.has_value()) - throw ParserMissingAttributeError{ moduleToken.location, ShaderAst::AttributeType::LangVersion }; - - if (!moduleId) - moduleId = Uuid::Generate(); - - if (m_context->module) - { - std::string moduleName = ParseModuleName(); - auto module = std::make_shared(*moduleVersion, std::move(moduleName), *moduleId); - - // Imported module - Expect(Advance(), TokenType::OpenCurlyBracket); - - m_context->parsingImportedModule = true; - - while (Peek().type != TokenType::ClosingCurlyBracket) - { - ShaderAst::StatementPtr statement = ParseRootStatement(); - if (!statement) - { - const Token& token = Peek(); - throw ParserUnexpectedEndOfFileError{ token.location }; - } - - module->rootNode->statements.push_back(std::move(statement)); - } - Consume(); //< Consume ClosingCurlyBracket - - m_context->parsingImportedModule = false; - - auto& importedModule = m_context->module->importedModules.emplace_back(); - importedModule.module = std::move(module); - importedModule.identifier = importedModule.module->metadata->moduleName; - } - else - { - std::string moduleName; - if (Peek().type == TokenType::Identifier) - moduleName = ParseModuleName(); - - auto module = std::make_shared(*moduleVersion, std::move(moduleName), *moduleId); - - // First declaration - Expect(Advance(), TokenType::Semicolon); - - if (m_context->module) - throw ParserDuplicateModuleError{ moduleToken.location }; - - m_context->module = std::move(module); - } - } - - void Parser::ParseVariableDeclaration(std::string& name, ShaderAst::ExpressionValue& type, ShaderAst::ExpressionPtr& initialValue, SourceLocation& sourceLocation) - { - name = ParseIdentifierAsName(nullptr); - - if (Peek().type == TokenType::Colon) - { - Expect(Advance(), TokenType::Colon); - - type = ParseType(); - } - - if (!type.HasValue() || Peek().type == TokenType::Assign) - { - Expect(Advance(), TokenType::Assign); - initialValue = ParseExpression(); - } - - const Token& endToken = Expect(Advance(), TokenType::Semicolon); - sourceLocation.ExtendToRight(endToken.location); - } - - ShaderAst::ExpressionPtr Parser::BuildIdentifierAccess(ShaderAst::ExpressionPtr lhs, ShaderAst::ExpressionPtr rhs) - { - if (rhs->GetType() == ShaderAst::NodeType::IdentifierExpression) - { - SourceLocation location = SourceLocation::BuildFromTo(lhs->sourceLocation, rhs->sourceLocation); - - auto accessMemberExpr = ShaderBuilder::AccessMember(std::move(lhs), { std::move(SafeCast(*rhs).identifier) }); - accessMemberExpr->sourceLocation = std::move(location); - - return accessMemberExpr; - } - else - return BuildIndexAccess(std::move(lhs), std::move(rhs)); - } - - ShaderAst::ExpressionPtr Parser::BuildIndexAccess(ShaderAst::ExpressionPtr lhs, ShaderAst::ExpressionPtr rhs) - { - SourceLocation location = SourceLocation::BuildFromTo(lhs->sourceLocation, rhs->sourceLocation); - - auto accessIndexExpr = ShaderBuilder::AccessIndex(std::move(lhs), std::move(rhs)); - accessIndexExpr->sourceLocation = std::move(location); - - return accessIndexExpr; - } - - ShaderAst::ExpressionPtr Parser::BuildBinary(ShaderAst::BinaryType binaryType, ShaderAst::ExpressionPtr lhs, ShaderAst::ExpressionPtr rhs) - { - SourceLocation location = SourceLocation::BuildFromTo(lhs->sourceLocation, rhs->sourceLocation); - - auto accessIndexExpr = ShaderBuilder::Binary(binaryType, std::move(lhs), std::move(rhs)); - accessIndexExpr->sourceLocation = std::move(location); - - return accessIndexExpr; - } - - ShaderAst::StatementPtr Parser::ParseAliasDeclaration() - { - const Token& aliasToken = Expect(Advance(), TokenType::Alias); - - std::string name = ParseIdentifierAsName(nullptr); - - Expect(Advance(), TokenType::Assign); - - ShaderAst::ExpressionPtr expr = ParseExpression(); - - const Token& endToken = Expect(Advance(), TokenType::Semicolon); - - auto aliasStatement = ShaderBuilder::DeclareAlias(std::move(name), std::move(expr)); - aliasStatement->sourceLocation = SourceLocation::BuildFromTo(aliasToken.location, endToken.location); - - return aliasStatement; - } - - ShaderAst::StatementPtr Parser::ParseBranchStatement() - { - std::unique_ptr branch = std::make_unique(); - - bool first = true; - for (;;) - { - if (!first) - Expect(Advance(), TokenType::Else); - - const Token& ifToken = Expect(Advance(), TokenType::If); - if (first) - branch->sourceLocation = ifToken.location; - - first = false; - - auto& condStatement = branch->condStatements.emplace_back(); - - Expect(Advance(), TokenType::OpenParenthesis); - - condStatement.condition = ParseExpression(); - - Expect(Advance(), TokenType::ClosingParenthesis); - - condStatement.statement = ParseStatement(); - branch->sourceLocation.ExtendToRight(condStatement.statement->sourceLocation); - - if (Peek().type != TokenType::Else || Peek(1).type != TokenType::If) - break; - } - - if (Peek().type == TokenType::Else) - { - Consume(); - branch->elseStatement = ParseStatement(); - branch->sourceLocation.ExtendToRight(branch->elseStatement->sourceLocation); - } - - return branch; - } - - ShaderAst::StatementPtr Parser::ParseConstStatement() - { - const Token& constToken = Expect(Advance(), TokenType::Const); - - SourceLocation constLocation = constToken.location; - - const Token& token = Peek(); - switch (token.type) - { - case TokenType::Identifier: - { - std::string constName; - ShaderAst::ExpressionValue constType; - ShaderAst::ExpressionPtr initialValue; - - ParseVariableDeclaration(constName, constType, initialValue, constLocation); - - auto constDeclaration = ShaderBuilder::DeclareConst(std::move(constName), std::move(constType), std::move(initialValue)); - constDeclaration->sourceLocation = std::move(constLocation); - - return constDeclaration; - } - - case TokenType::If: - { - auto branch = ParseBranchStatement(); - SafeCast(*branch).isConst = true; - branch->sourceLocation.ExtendToLeft(constLocation); - - return branch; - } - - default: - throw ParserUnexpectedTokenError{ token.location, token.type }; - } - } - - ShaderAst::StatementPtr Parser::ParseDiscardStatement() - { - const Token& discardToken = Expect(Advance(), TokenType::Discard); - const Token& endToken = Expect(Advance(), TokenType::Semicolon); - - auto discardStatement = ShaderBuilder::Discard(); - discardStatement->sourceLocation = SourceLocation::BuildFromTo(discardToken.location, endToken.location); - - return discardStatement; - } - - ShaderAst::StatementPtr Parser::ParseExternalBlock(std::vector attributes) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - const Token& externalToken = Expect(Advance(), TokenType::External); - Expect(Advance(), TokenType::OpenCurlyBracket); - - std::unique_ptr externalStatement = std::make_unique(); - externalStatement->sourceLocation = externalToken.location; - - ShaderAst::ExpressionValue condition; - - for (auto&& attribute : attributes) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Cond: - HandleUniqueAttribute(condition, std::move(attribute)); - break; - - case ShaderAst::AttributeType::Set: - HandleUniqueAttribute(externalStatement->bindingSet, std::move(attribute)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - - bool first = true; - for (;;) - { - if (!first) - { - const Token& nextToken = Peek(); - if (nextToken.type == TokenType::Comma) - Consume(); - else - { - Expect(nextToken, TokenType::ClosingCurlyBracket); - break; - } - } - - first = false; - - const Token& token = Peek(); - if (token.type == TokenType::ClosingCurlyBracket) - break; - - auto& extVar = externalStatement->externalVars.emplace_back(); - - if (token.type == TokenType::OpenSquareBracket) - { - for (auto&& attribute : ParseAttributes()) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Binding: - HandleUniqueAttribute(extVar.bindingIndex, std::move(attribute)); - break; - - case ShaderAst::AttributeType::Set: - HandleUniqueAttribute(extVar.bindingSet, std::move(attribute)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - } - - extVar.name = ParseIdentifierAsName(&extVar.sourceLocation); - Expect(Advance(), TokenType::Colon); - - auto typeExpr = ParseType(); - extVar.sourceLocation.ExtendToRight(typeExpr->sourceLocation); - - extVar.type = std::move(typeExpr); - } - - Expect(Advance(), TokenType::ClosingCurlyBracket); - - if (condition.HasValue()) - return ShaderBuilder::ConditionalStatement(std::move(condition).GetExpression(), std::move(externalStatement)); - else - return externalStatement; - } - - ShaderAst::StatementPtr Parser::ParseForDeclaration(std::vector attributes) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - const Token& forToken = Expect(Advance(), TokenType::For); - - std::string varName = ParseIdentifierAsName(nullptr); - - Expect(Advance(), TokenType::In); - - ShaderAst::ExpressionPtr expr = ParseExpression(); - - if (Peek().type == TokenType::Arrow) - { - // Numerical for - Consume(); - - ShaderAst::ExpressionPtr toExpr = ParseExpression(); - - ShaderAst::ExpressionPtr stepExpr; - if (Peek().type == TokenType::Colon) - { - Consume(); - stepExpr = ParseExpression(); - } - - ShaderAst::StatementPtr statement = ParseStatement(); - - auto forNode = ShaderBuilder::For(std::move(varName), std::move(expr), std::move(toExpr), std::move(stepExpr), std::move(statement)); - forNode->sourceLocation = SourceLocation::BuildFromTo(forToken.location, forNode->statement->sourceLocation); - - // TODO: Deduplicate code - for (auto&& attribute : attributes) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Unroll: - HandleUniqueStringAttribute(forNode->unroll, std::move(attribute), s_unrollModes, std::make_optional(ShaderAst::LoopUnroll::Always)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - - return forNode; - } - else - { - // For each - ShaderAst::StatementPtr statement = ParseStatement(); - - auto forEachNode = ShaderBuilder::ForEach(std::move(varName), std::move(expr), std::move(statement)); - forEachNode->sourceLocation = SourceLocation::BuildFromTo(forToken.location, forEachNode->statement->sourceLocation); - - // TODO: Deduplicate code - for (auto&& attribute : attributes) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Unroll: - HandleUniqueStringAttribute(forEachNode->unroll, std::move(attribute), s_unrollModes, std::make_optional(ShaderAst::LoopUnroll::Always)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - - return forEachNode; - } - } - - ShaderAst::StatementPtr Parser::ParseFunctionDeclaration(std::vector attributes) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - const auto& funcToken = Expect(Advance(), TokenType::FunctionDeclaration); - - std::string functionName = ParseIdentifierAsName(nullptr); - - Expect(Advance(), TokenType::OpenParenthesis); - - std::vector parameters; - - bool firstParameter = true; - for (;;) - { - const Token& t = Peek(); - ExpectNot(t, TokenType::EndOfStream); - - if (t.type == TokenType::ClosingParenthesis) - break; - - if (!firstParameter) - Expect(Advance(), TokenType::Comma); - - parameters.push_back(ParseFunctionParameter()); - firstParameter = false; - } - - Expect(Advance(), TokenType::ClosingParenthesis); - - ShaderAst::ExpressionValue returnType; - if (Peek().type == TokenType::Arrow) - { - Consume(); - returnType = ParseType(); - } - - SourceLocation functionLocation; - std::vector functionBody = ParseStatementList(&functionLocation); - - functionLocation.ExtendToLeft(funcToken.location); - - auto func = ShaderBuilder::DeclareFunction(std::move(functionName), std::move(parameters), std::move(functionBody), std::move(returnType)); - func->sourceLocation = std::move(functionLocation); - - ShaderAst::ExpressionValue condition; - - for (auto&& attribute : attributes) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Cond: - HandleUniqueAttribute(condition, std::move(attribute)); - break; - - case ShaderAst::AttributeType::Entry: - HandleUniqueStringAttribute(func->entryStage, std::move(attribute), s_entryPoints); - break; - - case ShaderAst::AttributeType::Export: - HandleUniqueAttribute(func->isExported, std::move(attribute), true); - break; - - case ShaderAst::AttributeType::DepthWrite: - HandleUniqueStringAttribute(func->depthWrite, std::move(attribute), s_depthWriteModes); - break; - - case ShaderAst::AttributeType::EarlyFragmentTests: - HandleUniqueAttribute(func->earlyFragmentTests, std::move(attribute)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - - if (condition.HasValue()) - return ShaderBuilder::ConditionalStatement(std::move(condition).GetExpression(), std::move(func)); - else - return func; - } - - ShaderAst::DeclareFunctionStatement::Parameter Parser::ParseFunctionParameter() - { - ShaderAst::DeclareFunctionStatement::Parameter parameter; - - parameter.name = ParseIdentifierAsName(¶meter.sourceLocation); - - Expect(Advance(), TokenType::Colon); - - auto typeExpr = ParseType(); - parameter.sourceLocation.ExtendToRight(typeExpr->sourceLocation); - - parameter.type = std::move(typeExpr); - - return parameter; - } - - ShaderAst::StatementPtr Parser::ParseImportStatement() - { - const Token& importToken = Expect(Advance(), TokenType::Import); - - std::string moduleName = ParseModuleName(); - - const Token& endtoken = Expect(Advance(), TokenType::Semicolon); - - auto importStatement = ShaderBuilder::Import(std::move(moduleName)); - importStatement->sourceLocation = SourceLocation::BuildFromTo(importToken.location, endtoken.location); - - return importStatement; - } - - ShaderAst::StatementPtr Parser::ParseOptionDeclaration() - { - const Token& optionToken = Expect(Advance(), TokenType::Option); - - std::string optionName = ParseIdentifierAsName(nullptr); - - Expect(Advance(), TokenType::Colon); - - ShaderAst::ExpressionPtr optionType = ParseType(); - - ShaderAst::ExpressionPtr initialValue; - if (Peek().type == TokenType::Assign) - { - Consume(); - - initialValue = ParseExpression(); - } - - const Token& endToken = Expect(Advance(), TokenType::Semicolon); - - auto optionDeclarationStatement = ShaderBuilder::DeclareOption(std::move(optionName), std::move(optionType), std::move(initialValue)); - optionDeclarationStatement->sourceLocation = SourceLocation::BuildFromTo(optionToken.location, endToken.location); - - return optionDeclarationStatement; - } - - ShaderAst::StatementPtr Parser::ParseReturnStatement() - { - const Token& returnToken = Expect(Advance(), TokenType::Return); - - ShaderAst::ExpressionPtr expr; - if (Peek().type != TokenType::Semicolon) - expr = ParseExpression(); - - const Token& endToken = Expect(Advance(), TokenType::Semicolon); - - auto returnStatement = ShaderBuilder::Return(std::move(expr)); - returnStatement->sourceLocation = SourceLocation::BuildFromTo(returnToken.location, endToken.location); - - return returnStatement; - } - - ShaderAst::StatementPtr Parser::ParseRootStatement(std::vector attributes) - { - const Token& nextToken = Peek(); - switch (nextToken.type) - { - case TokenType::Alias: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - - return ParseAliasDeclaration(); - - case TokenType::Const: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - - return ParseConstStatement(); - - case TokenType::EndOfStream: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - - return {}; - - case TokenType::External: - return ParseExternalBlock(std::move(attributes)); - - case TokenType::Import: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - - return ParseImportStatement(); - - case TokenType::OpenSquareBracket: - assert(attributes.empty()); - return ParseRootStatement(ParseAttributes()); - - case TokenType::Module: - ParseModuleStatement(std::move(attributes)); - return ParseRootStatement(); - - case TokenType::Option: - { - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - - return ParseOptionDeclaration(); - } - - case TokenType::FunctionDeclaration: - return ParseFunctionDeclaration(std::move(attributes)); - - case TokenType::Struct: - return ParseStructDeclaration(std::move(attributes)); - - default: - throw ParserUnexpectedTokenError{ nextToken.location, nextToken.type }; - } - } - - ShaderAst::StatementPtr Parser::ParseSingleStatement() - { - std::vector attributes; - ShaderAst::StatementPtr statement; - do - { - const Token& token = Peek(); - switch (token.type) - { - case TokenType::Const: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - statement = ParseConstStatement(); - break; - - case TokenType::Discard: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - statement = ParseDiscardStatement(); - break; - - case TokenType::For: - statement = ParseForDeclaration(std::move(attributes)); - attributes.clear(); - break; - - case TokenType::Let: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - statement = ParseVariableDeclaration(); - break; - - case TokenType::Identifier: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - statement = ShaderBuilder::ExpressionStatement(ParseVariableAssignation()); - Expect(Advance(), TokenType::Semicolon); - break; - - case TokenType::If: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - statement = ParseBranchStatement(); - break; - - case TokenType::OpenSquareBracket: - assert(attributes.empty()); - attributes = ParseAttributes(); - break; - - case TokenType::Return: - if (!attributes.empty()) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - statement = ParseReturnStatement(); - break; - - case TokenType::While: - statement = ParseWhileStatement(std::move(attributes)); - attributes.clear(); - break; - - default: - throw ParserUnexpectedTokenError{ token.location, token.type }; - } - } - while (!statement); //< small trick to repeat parsing once we got attributes - - return statement; - } - - ShaderAst::StatementPtr Parser::ParseStatement() - { - if (Peek().type == TokenType::OpenCurlyBracket) - { - auto multiStatement = ShaderBuilder::MultiStatement(); - multiStatement->statements = ParseStatementList(&multiStatement->sourceLocation); - - return ShaderBuilder::Scoped(std::move(multiStatement)); - } - else - return ParseSingleStatement(); - } - - std::vector Parser::ParseStatementList(SourceLocation* sourceLocation) - { - const Token& openToken = Expect(Advance(), TokenType::OpenCurlyBracket); - - std::vector statements; - while (Peek().type != TokenType::ClosingCurlyBracket) - { - ExpectNot(Peek(), TokenType::EndOfStream); - statements.push_back(ParseStatement()); - } - const Token& closeToken = Expect(Advance(), TokenType::ClosingCurlyBracket); - - if (sourceLocation) - *sourceLocation = SourceLocation::BuildFromTo(openToken.location, closeToken.location); - - return statements; - } - - ShaderAst::StatementPtr Parser::ParseStructDeclaration(std::vector attributes) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - const auto& structToken = Expect(Advance(), TokenType::Struct); - - ShaderAst::StructDescription description; - description.name = ParseIdentifierAsName(nullptr); - - ShaderAst::ExpressionValue condition; - ShaderAst::ExpressionValue exported; - - for (auto&& attribute : attributes) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Cond: - HandleUniqueAttribute(condition, std::move(attribute)); - break; - - case ShaderAst::AttributeType::Export: - HandleUniqueAttribute(exported, std::move(attribute), true); - break; - - case ShaderAst::AttributeType::Layout: - HandleUniqueStringAttribute(description.layout, std::move(attribute), s_layoutMapping); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - - Expect(Advance(), TokenType::OpenCurlyBracket); - - bool first = true; - - for (;;) - { - if (!first) - { - const Token& nextToken = Peek(); - if (nextToken.type == TokenType::Comma) - Consume(); - else - { - Expect(nextToken, TokenType::ClosingCurlyBracket); - break; - } - } - - first = false; - - const Token& token = Peek(); - if (token.type == TokenType::ClosingCurlyBracket) - break; - - auto& structField = description.members.emplace_back(); - - if (token.type == TokenType::OpenSquareBracket) - { - for (auto&& attribute : ParseAttributes()) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Builtin: - HandleUniqueStringAttribute(structField.builtin, std::move(attribute), s_builtinMapping); - break; - - case ShaderAst::AttributeType::Cond: - HandleUniqueAttribute(structField.cond, std::move(attribute)); - break; - - case ShaderAst::AttributeType::Location: - HandleUniqueAttribute(structField.locationIndex, std::move(attribute)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - } - - structField.name = ParseIdentifierAsName(&structField.sourceLocation); - - Expect(Advance(), TokenType::Colon); - - structField.type = ParseType(); - } - - const Token& endToken = Expect(Advance(), TokenType::ClosingCurlyBracket); - - auto structDeclStatement = ShaderBuilder::DeclareStruct(std::move(description), std::move(exported)); - structDeclStatement->sourceLocation = SourceLocation::BuildFromTo(structToken.location, endToken.location); - - if (condition.HasValue()) - { - auto condStatement = ShaderBuilder::ConditionalStatement(std::move(condition).GetExpression(), std::move(structDeclStatement)); - condStatement->sourceLocation = condStatement->statement->sourceLocation; - - return condStatement; - } - else - return structDeclStatement; - } - - ShaderAst::ExpressionPtr Parser::ParseVariableAssignation() - { - // Variable expression - ShaderAst::ExpressionPtr left = ParseExpression(); - - // Assignation type - ShaderAst::AssignType assignType; - - const Token& token = Peek(); - switch (token.type) - { - case TokenType::Assign: assignType = ShaderAst::AssignType::Simple; break; - case TokenType::DivideAssign: assignType = ShaderAst::AssignType::CompoundDivide; break; - case TokenType::LogicalAndAssign: assignType = ShaderAst::AssignType::CompoundLogicalAnd; break; - case TokenType::LogicalOrAssign: assignType = ShaderAst::AssignType::CompoundLogicalOr; break; - case TokenType::MultiplyAssign: assignType = ShaderAst::AssignType::CompoundMultiply; break; - case TokenType::MinusAssign: assignType = ShaderAst::AssignType::CompoundSubtract; break; - case TokenType::PlusAssign: assignType = ShaderAst::AssignType::CompoundAdd; break; - - default: - throw ParserUnexpectedTokenError{ token.location, token.type }; - } - - Consume(); - - // Value expression - ShaderAst::ExpressionPtr right = ParseExpression(); - - auto assignExpr = ShaderBuilder::Assign(assignType, std::move(left), std::move(right)); - assignExpr->sourceLocation = SourceLocation::BuildFromTo(assignExpr->left->sourceLocation, assignExpr->right->sourceLocation); - - return assignExpr; - } - - ShaderAst::StatementPtr Parser::ParseVariableDeclaration() - { - const auto& letToken = Expect(Advance(), TokenType::Let); - - SourceLocation letLocation = letToken.location; - - std::string variableName; - ShaderAst::ExpressionValue variableType; - ShaderAst::ExpressionPtr expression; - - ParseVariableDeclaration(variableName, variableType, expression, letLocation); - - auto variableDeclStatement = ShaderBuilder::DeclareVariable(std::move(variableName), std::move(variableType), std::move(expression)); - variableDeclStatement->sourceLocation = std::move(letLocation); - - return variableDeclStatement; - } - - ShaderAst::StatementPtr Parser::ParseWhileStatement(std::vector attributes) - { - NAZARA_USE_ANONYMOUS_NAMESPACE - - const Token& whileToken = Expect(Advance(), TokenType::While); - - Expect(Advance(), TokenType::OpenParenthesis); - - ShaderAst::ExpressionPtr condition = ParseExpression(); - - Expect(Advance(), TokenType::ClosingParenthesis); - - ShaderAst::StatementPtr body = ParseStatement(); - - auto whileStatement = ShaderBuilder::While(std::move(condition), std::move(body)); - whileStatement->sourceLocation = SourceLocation::BuildFromTo(whileToken.location, whileStatement->body->sourceLocation); - - for (auto&& attribute : attributes) - { - switch (attribute.type) - { - case ShaderAst::AttributeType::Unroll: - HandleUniqueStringAttribute(whileStatement->unroll, std::move(attribute), s_unrollModes, std::make_optional(ShaderAst::LoopUnroll::Always)); - break; - - default: - throw ParserUnexpectedAttributeError{ attribute.sourceLocation, attribute.type }; - } - } - - return whileStatement; - } - - ShaderAst::ExpressionPtr Parser::ParseBinOpRhs(int exprPrecedence, ShaderAst::ExpressionPtr lhs) - { - for (;;) - { - const Token& token = Peek(); - TokenType currentTokenType = token.type; - if (currentTokenType == TokenType::EndOfStream) - throw ParserUnexpectedTokenError{ token.location, token.type }; - - int tokenPrecedence = GetTokenPrecedence(currentTokenType); - if (tokenPrecedence < exprPrecedence) - return lhs; - - if (currentTokenType == TokenType::OpenParenthesis) - { - Consume(); - - // Function call - SourceLocation closingLocation; - auto parameters = ParseExpressionList(TokenType::ClosingParenthesis, &closingLocation); - - const SourceLocation& lhsLoc = lhs->sourceLocation; - lhs = ShaderBuilder::CallFunction(std::move(lhs), std::move(parameters)); - lhs->sourceLocation = SourceLocation::BuildFromTo(lhsLoc, closingLocation); - continue; - } - - if (currentTokenType == TokenType::OpenSquareBracket) - { - Consume(); - - // Indices - SourceLocation closingLocation; - auto parameters = ParseExpressionList(TokenType::ClosingSquareBracket, &closingLocation); - - const SourceLocation& lhsLoc = lhs->sourceLocation; - lhs = ShaderBuilder::AccessIndex(std::move(lhs), std::move(parameters)); - lhs->sourceLocation = SourceLocation::BuildFromTo(lhsLoc, closingLocation); - continue; - } - - Consume(); - ShaderAst::ExpressionPtr rhs = ParsePrimaryExpression(); - - const Token& nextOp = Peek(); - - int nextTokenPrecedence = GetTokenPrecedence(nextOp.type); - if (tokenPrecedence < nextTokenPrecedence) - rhs = ParseBinOpRhs(tokenPrecedence + 1, std::move(rhs)); - - lhs = [&] - { - switch (currentTokenType) - { - case TokenType::Dot: - return BuildIdentifierAccess(std::move(lhs), std::move(rhs)); - - case TokenType::Divide: return BuildBinary(ShaderAst::BinaryType::Divide, std::move(lhs), std::move(rhs)); - case TokenType::Equal: return BuildBinary(ShaderAst::BinaryType::CompEq, std::move(lhs), std::move(rhs)); - case TokenType::LessThan: return BuildBinary(ShaderAst::BinaryType::CompLt, std::move(lhs), std::move(rhs)); - case TokenType::LessThanEqual: return BuildBinary(ShaderAst::BinaryType::CompLe, std::move(lhs), std::move(rhs)); - case TokenType::LogicalAnd: return BuildBinary(ShaderAst::BinaryType::LogicalAnd, std::move(lhs), std::move(rhs)); - case TokenType::LogicalOr: return BuildBinary(ShaderAst::BinaryType::LogicalOr, std::move(lhs), std::move(rhs)); - case TokenType::GreaterThan: return BuildBinary(ShaderAst::BinaryType::CompGt, std::move(lhs), std::move(rhs)); - case TokenType::GreaterThanEqual: return BuildBinary(ShaderAst::BinaryType::CompGe, std::move(lhs), std::move(rhs)); - case TokenType::Minus: return BuildBinary(ShaderAst::BinaryType::Subtract, std::move(lhs), std::move(rhs)); - case TokenType::Multiply: return BuildBinary(ShaderAst::BinaryType::Multiply, std::move(lhs), std::move(rhs)); - case TokenType::NotEqual: return BuildBinary(ShaderAst::BinaryType::CompNe, std::move(lhs), std::move(rhs)); - case TokenType::Plus: return BuildBinary(ShaderAst::BinaryType::Add, std::move(lhs), std::move(rhs)); - default: - throw ParserUnexpectedTokenError{ token.location, token.type }; - } - }(); - } - } - - ShaderAst::ExpressionPtr Parser::ParseConstSelectExpression() - { - const Token& constSelectToken = Expect(Advance(), TokenType::ConstSelect); - Expect(Advance(), TokenType::OpenParenthesis); - - ShaderAst::ExpressionPtr cond = ParseExpression(); - - Expect(Advance(), TokenType::Comma); - - ShaderAst::ExpressionPtr trueExpr = ParseExpression(); - - Expect(Advance(), TokenType::Comma); - - ShaderAst::ExpressionPtr falseExpr = ParseExpression(); - - const Token& closeToken = Expect(Advance(), TokenType::ClosingParenthesis); - - auto condExpr = ShaderBuilder::ConditionalExpression(std::move(cond), std::move(trueExpr), std::move(falseExpr)); - condExpr->sourceLocation = SourceLocation::BuildFromTo(constSelectToken.location, closeToken.location); - - return condExpr; - } - - ShaderAst::ExpressionPtr Parser::ParseExpression() - { - return ParseBinOpRhs(0, ParsePrimaryExpression()); - } - - std::vector Parser::ParseExpressionList(TokenType terminationToken, SourceLocation* terminationLocation) - { - std::vector parameters; - bool first = true; - while (Peek().type != terminationToken) - { - if (!first) - Expect(Advance(), TokenType::Comma); - - first = false; - parameters.push_back(ParseExpression()); - } - - const Token& endToken = Expect(Advance(), terminationToken); - if (terminationLocation) - *terminationLocation = endToken.location; - - return parameters; - } - - ShaderAst::ExpressionPtr Parser::ParseFloatingPointExpression() - { - const Token& floatingPointToken = Expect(Advance(), TokenType::FloatingPointValue); - auto constantExpr = ShaderBuilder::Constant(float(std::get(floatingPointToken.data))); //< FIXME - constantExpr->sourceLocation = floatingPointToken.location; - - return constantExpr; - } - - ShaderAst::ExpressionPtr Parser::ParseIdentifier() - { - const Token& identifierToken = Expect(Advance(), TokenType::Identifier); - const std::string& identifier = std::get(identifierToken.data); - - auto identifierExpr = ShaderBuilder::Identifier(identifier); - identifierExpr->sourceLocation = identifierToken.location; - - return identifierExpr; - } - - ShaderAst::ExpressionPtr Parser::ParseIntegerExpression() - { - const Token& integerToken = Expect(Advance(), TokenType::IntegerValue); - auto constantExpr = ShaderBuilder::Constant(SafeCast(std::get(integerToken.data))); //< FIXME - constantExpr->sourceLocation = integerToken.location; - - return constantExpr; - } - - ShaderAst::ExpressionPtr Parser::ParseParenthesisExpression() - { - const Token& openToken = Expect(Advance(), TokenType::OpenParenthesis); - ShaderAst::ExpressionPtr expression = ParseExpression(); - const Token& closeToken = Expect(Advance(), TokenType::ClosingParenthesis); - - expression->sourceLocation = SourceLocation::BuildFromTo(openToken.location, closeToken.location); - - return expression; - } - - ShaderAst::ExpressionPtr Parser::ParsePrimaryExpression() - { - const Token& token = Peek(); - - ShaderAst::ExpressionPtr primaryExpr; - switch (token.type) - { - case TokenType::BoolFalse: - Consume(); - primaryExpr = ShaderBuilder::Constant(false); - primaryExpr->sourceLocation = token.location; - break; - - case TokenType::BoolTrue: - Consume(); - primaryExpr = ShaderBuilder::Constant(true); - primaryExpr->sourceLocation = token.location; - break; - - case TokenType::ConstSelect: - primaryExpr = ParseConstSelectExpression(); - break; - - case TokenType::FloatingPointValue: - primaryExpr = ParseFloatingPointExpression(); - break; - - case TokenType::Identifier: - primaryExpr = ParseIdentifier(); - break; - - case TokenType::IntegerValue: - primaryExpr = ParseIntegerExpression(); - break; - - case TokenType::Minus: - { - Consume(); - ShaderAst::ExpressionPtr expr = ParseExpression(); - - auto minusExpr = ShaderBuilder::Unary(ShaderAst::UnaryType::Minus, std::move(expr)); - minusExpr->sourceLocation = SourceLocation::BuildFromTo(token.location, minusExpr->expression->sourceLocation); - - primaryExpr = std::move(minusExpr); - break; - } - - case TokenType::Plus: - { - Consume(); - ShaderAst::ExpressionPtr expr = ParseExpression(); - - auto plusExpr = ShaderBuilder::Unary(ShaderAst::UnaryType::Plus, std::move(expr)); - plusExpr->sourceLocation = SourceLocation::BuildFromTo(token.location, plusExpr->expression->sourceLocation); - - primaryExpr = std::move(plusExpr); - break; - } - - case TokenType::Not: - { - Consume(); - ShaderAst::ExpressionPtr expr = ParseExpression(); - - auto notExpr = ShaderBuilder::Unary(ShaderAst::UnaryType::LogicalNot, std::move(expr)); - notExpr->sourceLocation = SourceLocation::BuildFromTo(token.location, notExpr->expression->sourceLocation); - - primaryExpr = std::move(notExpr); - break; - } - - case TokenType::OpenParenthesis: - primaryExpr = ParseParenthesisExpression(); - break; - - case TokenType::StringValue: - primaryExpr = ParseStringExpression(); - break; - - default: - throw ParserUnexpectedTokenError{ token.location, token.type }; - } - - primaryExpr->sourceLocation.ExtendToLeft(token.location); - - return primaryExpr; - } - - ShaderAst::ExpressionPtr Parser::ParseStringExpression() - { - const Token& litteralToken = Expect(Advance(), TokenType::StringValue); - auto constantExpr = ShaderBuilder::Constant(std::get(litteralToken.data)); - constantExpr->sourceLocation = litteralToken.location; - - return constantExpr; - } - - const std::string& Parser::ParseIdentifierAsName(SourceLocation* sourceLocation) - { - const Token& identifierToken = Expect(Advance(), TokenType::Identifier); - if (sourceLocation) - *sourceLocation = identifierToken.location; - - return std::get(identifierToken.data); - } - - std::string Parser::ParseModuleName() - { - std::string moduleName = ParseIdentifierAsName(nullptr); - while (Peek().type == TokenType::Dot) - { - Consume(); - moduleName += '.'; - moduleName += ParseIdentifierAsName(nullptr); - } - - return moduleName; - } - - ShaderAst::ExpressionPtr Parser::ParseType() - { - // Handle () as no type - const Token& openToken = Peek(); - if (openToken.type == TokenType::OpenParenthesis) - { - Consume(); - const Token& closeToken = Expect(Advance(), TokenType::ClosingParenthesis); - - auto constantExpr = ShaderBuilder::Constant(ShaderAst::NoValue{}); - constantExpr->sourceLocation = closeToken.location; - - return constantExpr; - } - - return ParseExpression(); - } - - template - void Parser::HandleUniqueAttribute(ShaderAst::ExpressionValue& targetAttribute, Parser::Attribute&& attribute) - { - if (targetAttribute.HasValue()) - throw ParserAttributeMultipleUniqueError{ attribute.sourceLocation, attribute.type }; - - if (!attribute.args) - throw ParserAttributeMissingParameterError{ attribute.sourceLocation, attribute.type }; - - targetAttribute = std::move(attribute.args); - } - - template - void Parser::HandleUniqueAttribute(ShaderAst::ExpressionValue& targetAttribute, Parser::Attribute&& attribute, T defaultValue) - { - if (targetAttribute.HasValue()) - throw ParserAttributeMultipleUniqueError{ attribute.sourceLocation, attribute.type }; - - if (attribute.args) - targetAttribute = std::move(attribute.args); - else - targetAttribute = std::move(defaultValue); - } - - template - void Parser::HandleUniqueStringAttribute(ShaderAst::ExpressionValue& targetAttribute, Parser::Attribute&& attribute, const M& map, std::optional defaultValue) - { - if (targetAttribute.HasValue()) - throw ParserAttributeMultipleUniqueError{ attribute.sourceLocation, attribute.type }; - - //FIXME: This should be handled with global values at sanitization stage - if (attribute.args) - { - if (attribute.args->GetType() != ShaderAst::NodeType::IdentifierExpression) - throw ParserAttributeParameterIdentifierError{ attribute.args->sourceLocation, attribute.type }; - - std::string_view exprStr = static_cast(*attribute.args).identifier; - - auto it = map.find(exprStr); - if (it == map.end()) - throw ParserAttributeInvalidParameterError{ attribute.args->sourceLocation, exprStr, attribute.type }; - - targetAttribute = it->second; - } - else - { - if (!defaultValue) - throw ParserAttributeMissingParameterError{ attribute.sourceLocation, attribute.type }; - - targetAttribute = defaultValue.value(); - } - } - - int Parser::GetTokenPrecedence(TokenType token) - { - switch (token) - { - case TokenType::Divide: return 80; - case TokenType::Dot: return 150; - case TokenType::Equal: return 50; - case TokenType::LessThan: return 40; - case TokenType::LessThanEqual: return 40; - case TokenType::LogicalAnd: return 20; - case TokenType::LogicalOr: return 10; - case TokenType::GreaterThan: return 40; - case TokenType::GreaterThanEqual: return 40; - case TokenType::Multiply: return 80; - case TokenType::Minus: return 60; - case TokenType::NotEqual: return 50; - case TokenType::Plus: return 60; - case TokenType::OpenSquareBracket: return 100; - case TokenType::OpenParenthesis: return 100; - default: return -1; - } - } - - ShaderAst::ModulePtr ParseFromFile(const std::filesystem::path& sourcePath) - { - std::optional> source = File::ReadWhole(sourcePath); - if (!source.has_value()) - return {}; - - return Parse(std::string_view(reinterpret_cast(source->data()), source->size()), sourcePath.generic_u8string()); - } -} diff --git a/src/Nazara/Shader/ShaderModuleResolver.cpp b/src/Nazara/Shader/ShaderModuleResolver.cpp deleted file mode 100644 index 55c902e1f..000000000 --- a/src/Nazara/Shader/ShaderModuleResolver.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - ShaderModuleResolver::~ShaderModuleResolver() = default; -} diff --git a/src/Nazara/Shader/ShaderWriter.cpp b/src/Nazara/Shader/ShaderWriter.cpp deleted file mode 100644 index 520a51d2f..000000000 --- a/src/Nazara/Shader/ShaderWriter.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - ShaderWriter::~ShaderWriter() = default; -} diff --git a/src/Nazara/Shader/SpirvAstVisitor.cpp b/src/Nazara/Shader/SpirvAstVisitor.cpp deleted file mode 100644 index 8a02b45d6..000000000 --- a/src/Nazara/Shader/SpirvAstVisitor.cpp +++ /dev/null @@ -1,1189 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - UInt32 SpirvAstVisitor::AllocateResultId() - { - return m_writer.AllocateResultId(); - } - - UInt32 SpirvAstVisitor::EvaluateExpression(ShaderAst::ExpressionPtr& expr) - { - expr->Visit(*this); - - assert(m_resultIds.size() == 1); - return PopResultId(); - } - - auto SpirvAstVisitor::GetVariable(std::size_t varIndex) const -> const Variable& - { - return Retrieve(m_variables, varIndex); - } - - void SpirvAstVisitor::Visit(ShaderAst::AccessIndexExpression& node) - { - SpirvExpressionLoad accessMemberVisitor(m_writer, *this, *m_currentBlock); - PushResultId(accessMemberVisitor.Evaluate(node)); - } - - void SpirvAstVisitor::Visit(ShaderAst::AssignExpression& node) - { - if (node.op != ShaderAst::AssignType::Simple) - throw std::runtime_error("unexpected assign expression (should have been removed by sanitization)"); - - UInt32 resultId = EvaluateExpression(node.right); - - SpirvExpressionStore storeVisitor(m_writer, *this, *m_currentBlock); - storeVisitor.Store(node.left, resultId); - - PushResultId(resultId); - } - - void SpirvAstVisitor::Visit(ShaderAst::BinaryExpression& node) - { - auto RetrieveBaseType = [](const ShaderAst::ExpressionType& exprType) - { - if (IsPrimitiveType(exprType)) - return std::get(exprType); - else if (IsVectorType(exprType)) - return std::get(exprType).type; - else if (IsMatrixType(exprType)) - return std::get(exprType).type; - else - throw std::runtime_error("unexpected type"); - }; - - const ShaderAst::ExpressionType& resultType = *GetExpressionType(node); - const ShaderAst::ExpressionType& leftType = *GetExpressionType(*node.left); - const ShaderAst::ExpressionType& rightType = *GetExpressionType(*node.right); - - ShaderAst::PrimitiveType leftTypeBase = RetrieveBaseType(leftType); - //ShaderAst::PrimitiveType rightTypeBase = RetrieveBaseType(rightType); - - - UInt32 leftOperand = EvaluateExpression(node.left); - UInt32 rightOperand = EvaluateExpression(node.right); - UInt32 resultId = m_writer.AllocateResultId(); - - bool swapOperands = false; - - SpirvOp op = [&] - { - switch (node.op) - { - case ShaderAst::BinaryType::Add: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFAdd; - - case ShaderAst::PrimitiveType::Int32: - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpIAdd; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::Subtract: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFSub; - - case ShaderAst::PrimitiveType::Int32: - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpISub; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::Divide: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFDiv; - - case ShaderAst::PrimitiveType::Int32: - return SpirvOp::OpSDiv; - - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpUDiv; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::Multiply: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - { - if (IsPrimitiveType(leftType)) - { - // Handle float * matrix|vector as matrix|vector * float - if (IsMatrixType(rightType)) - { - swapOperands = true; - return SpirvOp::OpMatrixTimesScalar; - } - else if (IsVectorType(rightType)) - { - swapOperands = true; - return SpirvOp::OpVectorTimesScalar; - } - } - else if (IsPrimitiveType(rightType)) - { - if (IsMatrixType(leftType)) - return SpirvOp::OpMatrixTimesScalar; - else if (IsVectorType(leftType)) - return SpirvOp::OpVectorTimesScalar; - } - else if (IsMatrixType(leftType)) - { - if (IsMatrixType(rightType)) - return SpirvOp::OpMatrixTimesMatrix; - else if (IsVectorType(rightType)) - return SpirvOp::OpMatrixTimesVector; - } - else if (IsMatrixType(rightType)) - { - assert(IsVectorType(leftType)); - return SpirvOp::OpVectorTimesMatrix; - } - - return SpirvOp::OpFMul; - } - - case ShaderAst::PrimitiveType::Int32: - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpIMul; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::CompEq: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Boolean: - return SpirvOp::OpLogicalEqual; - - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFOrdEqual; - - case ShaderAst::PrimitiveType::Int32: - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpIEqual; - - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::CompGe: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFOrdGreaterThan; - - case ShaderAst::PrimitiveType::Int32: - return SpirvOp::OpSGreaterThan; - - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpUGreaterThan; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::CompGt: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFOrdGreaterThanEqual; - - case ShaderAst::PrimitiveType::Int32: - return SpirvOp::OpSGreaterThanEqual; - - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpUGreaterThanEqual; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::CompLe: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFOrdLessThanEqual; - - case ShaderAst::PrimitiveType::Int32: - return SpirvOp::OpSLessThanEqual; - - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpULessThanEqual; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::CompLt: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFOrdLessThan; - - case ShaderAst::PrimitiveType::Int32: - return SpirvOp::OpSLessThan; - - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpULessThan; - - case ShaderAst::PrimitiveType::Boolean: - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::CompNe: - { - switch (leftTypeBase) - { - case ShaderAst::PrimitiveType::Boolean: - return SpirvOp::OpLogicalNotEqual; - - case ShaderAst::PrimitiveType::Float32: - return SpirvOp::OpFOrdNotEqual; - - case ShaderAst::PrimitiveType::Int32: - case ShaderAst::PrimitiveType::UInt32: - return SpirvOp::OpINotEqual; - - case ShaderAst::PrimitiveType::String: - break; - } - - break; - } - - case ShaderAst::BinaryType::LogicalAnd: - return SpirvOp::OpLogicalAnd; - - case ShaderAst::BinaryType::LogicalOr: - return SpirvOp::OpLogicalOr; - } - - assert(false); - throw std::runtime_error("unexpected binary operation"); - }(); - - if (swapOperands) - std::swap(leftOperand, rightOperand); - - if (node.op == ShaderAst::BinaryType::Divide) - { - //TODO: Handle other cases - if (IsVectorType(leftType) && IsPrimitiveType(rightType)) - { - const ShaderAst::VectorType& leftVec = std::get(leftType); - - UInt32 vecType = m_writer.GetTypeId(leftType); - - UInt32 rightAsVec = m_writer.AllocateResultId(); - m_currentBlock->AppendVariadic(SpirvOp::OpCompositeConstruct, [&](auto&& append) - { - append(vecType); - append(rightAsVec); - - for (std::size_t i = 0; i < leftVec.componentCount; ++i) - append(rightOperand); - }); - - rightOperand = rightAsVec; - } - else if (leftType != rightType) - throw std::runtime_error("unexpected division operands"); - } - - m_currentBlock->Append(op, m_writer.GetTypeId(resultType), resultId, leftOperand, rightOperand); - PushResultId(resultId); - } - - void SpirvAstVisitor::Visit(ShaderAst::BranchStatement& node) - { - assert(node.condStatements.size() == 1); //< sanitization splits multiple branches - auto& condStatement = node.condStatements.front(); - - auto mergeBlock = std::make_unique(m_writer); - auto contentBlock = std::make_unique(m_writer); - auto elseBlock = std::make_unique(m_writer); - - UInt32 conditionId = EvaluateExpression(condStatement.condition); - m_currentBlock->Append(SpirvOp::OpSelectionMerge, mergeBlock->GetLabelId(), SpirvSelectionControl::None); - // FIXME: Can we use merge block directly in OpBranchConditional if no else statement? - m_currentBlock->Append(SpirvOp::OpBranchConditional, conditionId, contentBlock->GetLabelId(), elseBlock->GetLabelId()); - - m_functionBlocks.emplace_back(std::move(contentBlock)); - m_currentBlock = m_functionBlocks.back().get(); - - condStatement.statement->Visit(*this); - - if (!m_currentBlock->IsTerminated()) - m_currentBlock->Append(SpirvOp::OpBranch, mergeBlock->GetLabelId()); - - m_functionBlocks.emplace_back(std::move(elseBlock)); - m_currentBlock = m_functionBlocks.back().get(); - - if (node.elseStatement) - node.elseStatement->Visit(*this); - - if (!m_currentBlock->IsTerminated()) - m_currentBlock->Append(SpirvOp::OpBranch, mergeBlock->GetLabelId()); - - m_functionBlocks.emplace_back(std::move(mergeBlock)); - m_currentBlock = m_functionBlocks.back().get(); - } - - void SpirvAstVisitor::Visit(ShaderAst::CallFunctionExpression& node) - { - std::size_t functionIndex = std::get(*GetExpressionType(*node.targetFunction)).funcIndex; - - UInt32 funcId = 0; - for (const auto& [funcIndex, func] : m_funcData) - { - if (funcIndex == functionIndex) - { - funcId = func.funcId; - break; - } - } - assert(funcId != 0); - - const FuncData& funcData = Retrieve(m_funcData, m_funcIndex); - const auto& funcCall = funcData.funcCalls[m_funcCallIndex++]; - - StackArray parameterIds = NazaraStackArrayNoInit(UInt32, node.parameters.size()); - for (std::size_t i = 0; i < node.parameters.size(); ++i) - { - UInt32 resultId = EvaluateExpression(node.parameters[i]); - UInt32 varId = funcData.variables[funcCall.firstVarIndex + i].varId; - m_currentBlock->Append(SpirvOp::OpStore, varId, resultId); - - parameterIds[i] = varId; - } - - UInt32 resultId = AllocateResultId(); - m_currentBlock->AppendVariadic(SpirvOp::OpFunctionCall, [&](auto&& appender) - { - appender(m_writer.GetTypeId(*ShaderAst::GetExpressionType(node))); - appender(resultId); - appender(funcId); - - for (std::size_t i = 0; i < node.parameters.size(); ++i) - appender(parameterIds[i]); - }); - - PushResultId(resultId); - } - - void SpirvAstVisitor::Visit(ShaderAst::CastExpression& node) - { - const ShaderAst::ExpressionType& targetExprType = node.targetType.GetResultingValue(); - if (IsPrimitiveType(targetExprType)) - { - ShaderAst::PrimitiveType targetType = std::get(targetExprType); - - assert(node.expressions[0] && !node.expressions[1]); - ShaderAst::ExpressionPtr& expression = node.expressions[0]; - - assert(expression->cachedExpressionType.has_value()); - const ShaderAst::ExpressionType& exprType = expression->cachedExpressionType.value(); - assert(IsPrimitiveType(exprType)); - ShaderAst::PrimitiveType fromType = std::get(exprType); - - UInt32 fromId = EvaluateExpression(expression); - if (targetType == fromType) - return PushResultId(fromId); - - std::optional castOp; - switch (targetType) - { - case ShaderAst::PrimitiveType::Boolean: - throw std::runtime_error("unsupported cast to boolean"); - - case ShaderAst::PrimitiveType::Float32: - { - switch (fromType) - { - case ShaderAst::PrimitiveType::Boolean: - throw std::runtime_error("unsupported cast from boolean"); - - case ShaderAst::PrimitiveType::Float32: - break; //< Already handled - - case ShaderAst::PrimitiveType::Int32: - castOp = SpirvOp::OpConvertSToF; - break; - - case ShaderAst::PrimitiveType::UInt32: - castOp = SpirvOp::OpConvertUToF; - break; - - case ShaderAst::PrimitiveType::String: - throw std::runtime_error("unexpected string type"); - } - break; - } - - case ShaderAst::PrimitiveType::Int32: - { - switch (fromType) - { - case ShaderAst::PrimitiveType::Boolean: - throw std::runtime_error("unsupported cast from boolean"); - - case ShaderAst::PrimitiveType::Float32: - castOp = SpirvOp::OpConvertFToS; - break; - - case ShaderAst::PrimitiveType::Int32: - break; //< Already handled - - case ShaderAst::PrimitiveType::UInt32: - throw std::runtime_error("unsupported cast from int32"); - - case ShaderAst::PrimitiveType::String: - throw std::runtime_error("unexpected string type"); - } - break; - } - - case ShaderAst::PrimitiveType::UInt32: - { - switch (fromType) - { - case ShaderAst::PrimitiveType::Boolean: - throw std::runtime_error("unsupported cast from boolean"); - - case ShaderAst::PrimitiveType::Float32: - castOp = SpirvOp::OpConvertFToU; - break; - - case ShaderAst::PrimitiveType::Int32: - castOp = SpirvOp::OpBitcast; - break; - - case ShaderAst::PrimitiveType::UInt32: - break; //< Already handled - - case ShaderAst::PrimitiveType::String: - throw std::runtime_error("unexpected string type"); - } - break; - } - - case ShaderAst::PrimitiveType::String: - throw std::runtime_error("unexpected string type"); - } - - assert(castOp); - - UInt32 resultId = m_writer.AllocateResultId(); - m_currentBlock->Append(*castOp, m_writer.GetTypeId(targetType), resultId, fromId); - - PushResultId(resultId); - } - else - { - assert(IsVectorType(targetExprType)); - StackVector exprResults = NazaraStackVector(UInt32, node.expressions.size()); - - for (auto& exprPtr : node.expressions) - { - if (!exprPtr) - break; - - exprResults.push_back(EvaluateExpression(exprPtr)); - } - - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->AppendVariadic(SpirvOp::OpCompositeConstruct, [&](const auto& appender) - { - appender(m_writer.GetTypeId(targetExprType)); - appender(resultId); - - for (UInt32 exprResultId : exprResults) - appender(exprResultId); - }); - - PushResultId(resultId); - } - } - - void SpirvAstVisitor::Visit(ShaderAst::ConstantValueExpression& node) - { - std::visit([&] (const auto& value) - { - PushResultId(m_writer.GetConstantId(value)); - }, node.value); - } - - void SpirvAstVisitor::Visit(ShaderAst::DeclareExternalStatement& node) - { - for (auto&& extVar : node.externalVars) - { - assert(extVar.varIndex); - RegisterExternalVariable(*extVar.varIndex, extVar.type.GetResultingValue()); - } - } - - void SpirvAstVisitor::Visit(ShaderAst::DeclareFunctionStatement& node) - { - assert(node.funcIndex); - m_funcIndex = *node.funcIndex; - m_funcCallIndex = 0; - - auto& func = m_funcData[m_funcIndex]; - - m_instructions.Append(SpirvOp::OpFunction, func.returnTypeId, func.funcId, 0, func.funcTypeId); - - if (!func.parameters.empty()) - { - assert(node.parameters.size() == func.parameters.size()); - for (std::size_t i = 0; i < func.parameters.size(); ++i) - { - UInt32 paramResultId = m_writer.AllocateResultId(); - m_instructions.Append(SpirvOp::OpFunctionParameter, func.parameters[i].pointerTypeId, paramResultId); - - RegisterVariable(*node.parameters[i].varIndex, func.parameters[i].typeId, paramResultId, SpirvStorageClass::Function); - } - } - - auto contentBlock = std::make_unique(m_writer); - m_currentBlock = contentBlock.get(); - - m_functionBlocks.clear(); - m_functionBlocks.emplace_back(std::move(contentBlock)); - - CallOnExit resetCurrentBlock([&] { m_currentBlock = nullptr; }); - - for (auto& var : func.variables) - { - var.varId = m_writer.AllocateResultId(); - m_currentBlock->Append(SpirvOp::OpVariable, var.typeId, var.varId, SpirvStorageClass::Function); - } - - if (func.entryPointData) - { - auto& entryPointData = *func.entryPointData; - if (entryPointData.inputStruct) - { - auto& inputStruct = *entryPointData.inputStruct; - - UInt32 paramId = m_writer.AllocateResultId(); - m_currentBlock->Append(SpirvOp::OpVariable, inputStruct.pointerId, paramId, SpirvStorageClass::Function); - - for (const auto& input : entryPointData.inputs) - { - UInt32 resultId = m_writer.AllocateResultId(); - m_currentBlock->Append(SpirvOp::OpAccessChain, input.memberPointerId, resultId, paramId, input.memberIndexConstantId); - m_currentBlock->Append(SpirvOp::OpCopyMemory, resultId, input.varId); - } - - RegisterVariable(*node.parameters.front().varIndex, inputStruct.typeId, paramId, SpirvStorageClass::Function); - } - } - - HandleStatementList(node.statements); - - // Add implicit return - if (!m_functionBlocks.back()->IsTerminated()) - m_functionBlocks.back()->Append(SpirvOp::OpReturn); - - for (std::unique_ptr& block : m_functionBlocks) - m_instructions.AppendSection(*block); - - m_instructions.Append(SpirvOp::OpFunctionEnd); - } - - void SpirvAstVisitor::Visit(ShaderAst::DeclareOptionStatement& /*node*/) - { - /* nothing to do */ - } - - void SpirvAstVisitor::Visit(ShaderAst::DeclareStructStatement& node) - { - assert(node.structIndex); - RegisterStruct(*node.structIndex, &node.description); - } - - void SpirvAstVisitor::Visit(ShaderAst::DeclareVariableStatement& node) - { - const auto& func = m_funcData[m_funcIndex]; - - UInt32 typeId = m_writer.GetTypeId(node.varType.GetResultingValue()); - - assert(node.varIndex); - auto varIt = func.varIndexToVarId.find(*node.varIndex); - UInt32 varId = func.variables[varIt->second].varId; - - RegisterVariable(*node.varIndex, typeId, varId, SpirvStorageClass::Function); - - if (node.initialExpression) - { - UInt32 value = EvaluateExpression(node.initialExpression); - m_currentBlock->Append(SpirvOp::OpStore, varId, value); - } - } - - void SpirvAstVisitor::Visit(ShaderAst::DiscardStatement& /*node*/) - { - m_currentBlock->Append(SpirvOp::OpKill); - } - - void SpirvAstVisitor::Visit(ShaderAst::ExpressionStatement& node) - { - node.expression->Visit(*this); - - PopResultId(); - } - - void SpirvAstVisitor::Visit(ShaderAst::IntrinsicExpression& node) - { - switch (node.intrinsic) - { - case ShaderAst::IntrinsicType::CrossProduct: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* parameterType = GetExpressionType(*node.parameters[0]); - assert(parameterType); - assert(IsVectorType(*parameterType)); - - UInt32 typeId = m_writer.GetTypeId(*parameterType); - - UInt32 firstParam = EvaluateExpression(node.parameters[0]); - UInt32 secondParam = EvaluateExpression(node.parameters[1]); - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, GLSLstd450Cross, firstParam, secondParam); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::DotProduct: - { - const ShaderAst::ExpressionType* vecExprType = GetExpressionType(*node.parameters[0]); - assert(vecExprType); - assert(IsVectorType(*vecExprType)); - - const ShaderAst::VectorType& vecType = std::get(*vecExprType); - - UInt32 typeId = m_writer.GetTypeId(vecType.type); - - UInt32 vec1 = EvaluateExpression(node.parameters[0]); - UInt32 vec2 = EvaluateExpression(node.parameters[1]); - - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpDot, typeId, resultId, vec1, vec2); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::Exp: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* parameterType = GetExpressionType(*node.parameters[0]); - assert(parameterType); - assert(IsPrimitiveType(*parameterType) || IsVectorType(*parameterType)); - UInt32 typeId = m_writer.GetTypeId(*parameterType); - - UInt32 param = EvaluateExpression(node.parameters[0]); - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, GLSLstd450Exp, param); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::Length: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* vecExprType = GetExpressionType(*node.parameters[0]); - assert(vecExprType); - assert(IsVectorType(*vecExprType)); - - const ShaderAst::VectorType& vecType = std::get(*vecExprType); - UInt32 typeId = m_writer.GetTypeId(vecType.type); - - UInt32 vec = EvaluateExpression(node.parameters[0]); - - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, GLSLstd450Length, vec); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::Max: - case ShaderAst::IntrinsicType::Min: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* parameterType = GetExpressionType(*node.parameters[0]); - assert(parameterType); - assert(IsPrimitiveType(*parameterType) || IsVectorType(*parameterType)); - UInt32 typeId = m_writer.GetTypeId(*parameterType); - - ShaderAst::PrimitiveType basicType; - if (IsPrimitiveType(*parameterType)) - basicType = std::get(*parameterType); - else if (IsVectorType(*parameterType)) - basicType = std::get(*parameterType).type; - else - throw std::runtime_error("unexpected expression type"); - - GLSLstd450 op; - switch (basicType) - { - case ShaderAst::PrimitiveType::Boolean: - throw std::runtime_error("unexpected boolean for max/min intrinsic"); - - case ShaderAst::PrimitiveType::Float32: - op = (node.intrinsic == ShaderAst::IntrinsicType::Max) ? GLSLstd450FMax : GLSLstd450FMin; - break; - - case ShaderAst::PrimitiveType::Int32: - op = (node.intrinsic == ShaderAst::IntrinsicType::Max) ? GLSLstd450SMax : GLSLstd450SMin; - break; - - case ShaderAst::PrimitiveType::UInt32: - op = (node.intrinsic == ShaderAst::IntrinsicType::Max) ? GLSLstd450UMax : GLSLstd450UMin; - break; - - case ShaderAst::PrimitiveType::String: - throw std::runtime_error("unexpected string type"); - } - - UInt32 firstParam = EvaluateExpression(node.parameters[0]); - UInt32 secondParam = EvaluateExpression(node.parameters[1]); - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, op, firstParam, secondParam); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::Normalize: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* vecExprType = GetExpressionType(*node.parameters[0]); - assert(vecExprType); - assert(IsVectorType(*vecExprType)); - - const ShaderAst::VectorType& vecType = std::get(*vecExprType); - UInt32 typeId = m_writer.GetTypeId(vecType); - - UInt32 vec = EvaluateExpression(node.parameters[0]); - - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, GLSLstd450Normalize, vec); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::Pow: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* parameterType = GetExpressionType(*node.parameters[0]); - assert(parameterType); - assert(IsPrimitiveType(*parameterType) || IsVectorType(*parameterType)); - UInt32 typeId = m_writer.GetTypeId(*parameterType); - - UInt32 firstParam = EvaluateExpression(node.parameters[0]); - UInt32 secondParam = EvaluateExpression(node.parameters[1]); - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, GLSLstd450Pow, firstParam, secondParam); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::Reflect: - { - UInt32 glslInstructionSet = m_writer.GetExtendedInstructionSet("GLSL.std.450"); - - const ShaderAst::ExpressionType* parameterType = GetExpressionType(*node.parameters[0]); - assert(parameterType); - assert(IsVectorType(*parameterType)); - UInt32 typeId = m_writer.GetTypeId(*parameterType); - - UInt32 firstParam = EvaluateExpression(node.parameters[0]); - UInt32 secondParam = EvaluateExpression(node.parameters[1]); - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpExtInst, typeId, resultId, glslInstructionSet, GLSLstd450Reflect, firstParam, secondParam); - PushResultId(resultId); - break; - } - - case ShaderAst::IntrinsicType::SampleTexture: - { - UInt32 typeId = m_writer.GetTypeId(ShaderAst::VectorType{4, ShaderAst::PrimitiveType::Float32}); - - UInt32 samplerId = EvaluateExpression(node.parameters[0]); - UInt32 coordinatesId = EvaluateExpression(node.parameters[1]); - UInt32 resultId = m_writer.AllocateResultId(); - - m_currentBlock->Append(SpirvOp::OpImageSampleImplicitLod, typeId, resultId, samplerId, coordinatesId); - PushResultId(resultId); - break; - } - - default: - throw std::runtime_error("not yet implemented"); - } - } - - void SpirvAstVisitor::Visit(ShaderAst::NoOpStatement& /*node*/) - { - // nothing to do - } - - void SpirvAstVisitor::Visit(ShaderAst::MultiStatement& node) - { - HandleStatementList(node.statements); - } - - void SpirvAstVisitor::Visit(ShaderAst::ReturnStatement& node) - { - if (node.returnExpr) - { - // Handle entry point return - const auto& func = m_funcData[m_funcIndex]; - if (func.entryPointData) - { - auto& entryPointData = *func.entryPointData; - if (entryPointData.outputStructTypeId) - { - UInt32 paramId = EvaluateExpression(node.returnExpr); - for (const auto& output : entryPointData.outputs) - { - UInt32 resultId = m_writer.AllocateResultId(); - m_currentBlock->Append(SpirvOp::OpCompositeExtract, output.typeId, resultId, paramId, output.memberIndex); - m_currentBlock->Append(SpirvOp::OpStore, output.varId, resultId); - } - } - - m_currentBlock->Append(SpirvOp::OpReturn); - } - else - m_currentBlock->Append(SpirvOp::OpReturnValue, EvaluateExpression(node.returnExpr)); - } - else - m_currentBlock->Append(SpirvOp::OpReturn); - } - - void SpirvAstVisitor::Visit(ShaderAst::ScopedStatement& node) - { - node.statement->Visit(*this); - } - - void SpirvAstVisitor::Visit(ShaderAst::SwizzleExpression& node) - { - const ShaderAst::ExpressionType* swizzledExpressionType = GetExpressionType(*node.expression); - assert(swizzledExpressionType); - - UInt32 exprResultId = EvaluateExpression(node.expression); - - const ShaderAst::ExpressionType* targetExprType = GetExpressionType(node); - assert(targetExprType); - - if (node.componentCount > 1) - { - assert(IsVectorType(*targetExprType)); - - const ShaderAst::VectorType& targetType = std::get(*targetExprType); - - UInt32 resultId = m_writer.AllocateResultId(); - if (IsVectorType(*swizzledExpressionType)) - { - // Swizzling a vector is implemented via OpVectorShuffle using the same vector twice as operands - m_currentBlock->AppendVariadic(SpirvOp::OpVectorShuffle, [&](const auto& appender) - { - appender(m_writer.GetTypeId(targetType)); - appender(resultId); - appender(exprResultId); - appender(exprResultId); - - for (std::size_t i = 0; i < node.componentCount; ++i) - appender(node.components[i]); - }); - } - else - { - assert(IsPrimitiveType(*swizzledExpressionType)); - - // Swizzling a primitive to a vector (a.xxx) can be implemented using OpCompositeConstruct - m_currentBlock->AppendVariadic(SpirvOp::OpCompositeConstruct, [&](const auto& appender) - { - appender(m_writer.GetTypeId(targetType)); - appender(resultId); - - for (std::size_t i = 0; i < node.componentCount; ++i) - appender(exprResultId); - }); - } - - PushResultId(resultId); - } - else if (IsVectorType(*swizzledExpressionType)) - { - assert(IsPrimitiveType(*targetExprType)); - ShaderAst::PrimitiveType targetType = std::get(*targetExprType); - - // Extract a single component from the vector - assert(node.componentCount == 1); - - UInt32 resultId = m_writer.AllocateResultId(); - m_currentBlock->Append(SpirvOp::OpCompositeExtract, m_writer.GetTypeId(targetType), resultId, exprResultId, node.components[0]); - - PushResultId(resultId); - } - else - { - // Swizzling a primitive to itself (a.x for example), don't do anything - assert(IsPrimitiveType(*swizzledExpressionType)); - assert(IsPrimitiveType(*targetExprType)); - assert(node.componentCount == 1); - assert(node.components[0] == 0); - - PushResultId(exprResultId); - } - } - - void SpirvAstVisitor::Visit(ShaderAst::UnaryExpression& node) - { - const ShaderAst::ExpressionType* resultType = GetExpressionType(node); - assert(resultType); - - const ShaderAst::ExpressionType* exprType = GetExpressionType(*node.expression); - assert(exprType); - - UInt32 operand = EvaluateExpression(node.expression); - - UInt32 resultId = [&] - { - switch (node.op) - { - case ShaderAst::UnaryType::LogicalNot: - { - assert(IsPrimitiveType(*exprType)); - assert(std::get(*resultType) == ShaderAst::PrimitiveType::Boolean); - - UInt32 resultId = m_writer.AllocateResultId(); - m_currentBlock->Append(SpirvOp::OpLogicalNot, m_writer.GetTypeId(*resultType), resultId, operand); - - return resultId; - } - - case ShaderAst::UnaryType::Minus: - { - ShaderAst::PrimitiveType basicType; - if (IsPrimitiveType(*exprType)) - basicType = std::get(*exprType); - else if (IsVectorType(*exprType)) - basicType = std::get(*exprType).type; - else - throw std::runtime_error("unexpected expression type"); - - UInt32 resultId = m_writer.AllocateResultId(); - - switch (basicType) - { - case ShaderAst::PrimitiveType::Float32: - m_currentBlock->Append(SpirvOp::OpFNegate, m_writer.GetTypeId(*resultType), resultId, operand); - return resultId; - - case ShaderAst::PrimitiveType::Int32: - case ShaderAst::PrimitiveType::UInt32: - m_currentBlock->Append(SpirvOp::OpSNegate, m_writer.GetTypeId(*resultType), resultId, operand); - return resultId; - - default: - break; - } - break; - } - - case ShaderAst::UnaryType::Plus: - PushResultId(operand); //< No-op - break; - } - - throw std::runtime_error("unexpected unary operation"); - }(); - - PushResultId(resultId); - } - - void SpirvAstVisitor::Visit(ShaderAst::VariableValueExpression& node) - { - SpirvExpressionLoad loadVisitor(m_writer, *this, *m_currentBlock); - PushResultId(loadVisitor.Evaluate(node)); - } - - void SpirvAstVisitor::Visit(ShaderAst::WhileStatement& node) - { - assert(node.condition); - assert(node.body); - - auto headerBlock = std::make_unique(m_writer); - auto bodyBlock = std::make_unique(m_writer); - auto mergeBlock = std::make_unique(m_writer); - - m_currentBlock->Append(SpirvOp::OpBranch, headerBlock->GetLabelId()); - m_currentBlock = headerBlock.get(); - - UInt32 expressionId = EvaluateExpression(node.condition); - - SpirvLoopControl loopControl; - if (node.unroll.HasValue()) - { - switch (node.unroll.GetResultingValue()) - { - case ShaderAst::LoopUnroll::Always: - // it shouldn't be possible to have this attribute as the loop gets unrolled in the sanitizer - throw std::runtime_error("unexpected unroll attribute"); - - case ShaderAst::LoopUnroll::Hint: - loopControl = SpirvLoopControl::Unroll; - break; - - case ShaderAst::LoopUnroll::Never: - loopControl = SpirvLoopControl::DontUnroll; - break; - } - } - else - loopControl = SpirvLoopControl::None; - - m_currentBlock->Append(SpirvOp::OpLoopMerge, mergeBlock->GetLabelId(), bodyBlock->GetLabelId(), loopControl); - m_currentBlock->Append(SpirvOp::OpBranchConditional, expressionId, bodyBlock->GetLabelId(), mergeBlock->GetLabelId()); - - UInt32 headerLabelId = headerBlock->GetLabelId(); - - m_currentBlock = bodyBlock.get(); - m_functionBlocks.emplace_back(std::move(headerBlock)); - m_functionBlocks.emplace_back(std::move(bodyBlock)); - - node.body->Visit(*this); - - // Jump back to header block to test condition - m_currentBlock->Append(SpirvOp::OpBranch, headerLabelId); - - m_functionBlocks.emplace_back(std::move(mergeBlock)); - m_currentBlock = m_functionBlocks.back().get(); - } - - void SpirvAstVisitor::HandleStatementList(const std::vector& statements) - { - for (auto& statement : statements) - { - // Handle termination statements - switch (statement->GetType()) - { - case ShaderAst::NodeType::DiscardStatement: - case ShaderAst::NodeType::ReturnStatement: - statement->Visit(*this); - return; //< stop processing statements after this one - - default: - statement->Visit(*this); - break; - } - } - } - - void SpirvAstVisitor::PushResultId(UInt32 value) - { - m_resultIds.push_back(value); - } - - UInt32 SpirvAstVisitor::PopResultId() - { - if (m_resultIds.empty()) - throw std::runtime_error("invalid operation"); - - UInt32 resultId = m_resultIds.back(); - m_resultIds.pop_back(); - - return resultId; - } -} diff --git a/src/Nazara/Shader/SpirvConstantCache.cpp b/src/Nazara/Shader/SpirvConstantCache.cpp deleted file mode 100644 index e0c50155f..000000000 --- a/src/Nazara/Shader/SpirvConstantCache.cpp +++ /dev/null @@ -1,1183 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - namespace - { - StructFieldType SpirvTypeToStructFieldType(const SpirvConstantCache::AnyType& type) - { - if (std::holds_alternative(type)) - return StructFieldType::Bool1; - else if (std::holds_alternative(type)) - { - const auto& floatType = std::get(type); - assert(floatType.width == 32 || floatType.width == 64); - return (floatType.width == 32) ? StructFieldType::Float1 : StructFieldType::Double1; - } - else if (std::holds_alternative(type)) - { - const auto& intType = std::get(type); - assert(intType.width == 32); - return (intType.signedness) ? StructFieldType::Int1 : StructFieldType::UInt1; - } - - throw std::runtime_error("unexpected type"); - } - } - - struct SpirvConstantCache::Eq - { - bool Compare(const ConstantBool& lhs, const ConstantBool& rhs) const - { - return lhs.value == rhs.value; - } - - bool Compare(const ConstantComposite& lhs, const ConstantComposite& rhs) const - { - return Compare(lhs.type, rhs.type) && Compare(lhs.values, rhs.values); - } - - bool Compare(const ConstantScalar& lhs, const ConstantScalar& rhs) const - { - return lhs.value == rhs.value; - } - - bool Compare(const Array& lhs, const Array& rhs) const - { - return Compare(lhs.length, rhs.length) && Compare(lhs.elementType, rhs.elementType) && lhs.stride == rhs.stride; - } - - bool Compare(const Bool& /*lhs*/, const Bool& /*rhs*/) const - { - return true; - } - - bool Compare(const Float& lhs, const Float& rhs) const - { - return lhs.width == rhs.width; - } - - bool Compare(const Function& lhs, const Function& rhs) const - { - return Compare(lhs.parameters, rhs.parameters) && Compare(lhs.returnType, rhs.returnType); - } - - bool Compare(const Image& lhs, const Image& rhs) const - { - return lhs.arrayed == rhs.arrayed - && lhs.dim == rhs.dim - && lhs.format == rhs.format - && lhs.multisampled == rhs.multisampled - && lhs.qualifier == rhs.qualifier - && Compare(lhs.sampledType, rhs.sampledType) - && lhs.depth == rhs.depth - && lhs.sampled == rhs.sampled; - } - - bool Compare(const Integer& lhs, const Integer& rhs) const - { - return lhs.width == rhs.width && lhs.signedness == rhs.signedness; - } - - bool Compare(const Matrix& lhs, const Matrix& rhs) const - { - return lhs.columnCount == rhs.columnCount && Compare(lhs.columnType, rhs.columnType); - } - - bool Compare(const Pointer& lhs, const Pointer& rhs) const - { - return lhs.storageClass == rhs.storageClass && Compare(lhs.type, rhs.type); - } - - bool Compare(const SampledImage& lhs, const SampledImage& rhs) const - { - return Compare(lhs.image, rhs.image); - } - - bool Compare(const Structure& lhs, const Structure& rhs) const - { - if (lhs.name != rhs.name) - return false; - - if (lhs.decorations != rhs.decorations) - return false; - - if (!Compare(lhs.members, rhs.members)) - return false; - - return true; - } - - bool Compare(const Structure::Member& lhs, const Structure::Member& rhs) const - { - if (!Compare(lhs.type, rhs.type)) - return false; - - if (lhs.name != rhs.name) - return false; - - return true; - } - - bool Compare(const Variable& lhs, const Variable& rhs) const - { - if (lhs.debugName != rhs.debugName) - return false; - - if (lhs.funcId != rhs.funcId) - return false; - - if (!Compare(lhs.initializer, rhs.initializer)) - return false; - - if (lhs.storageClass != rhs.storageClass) - return false; - - if (!Compare(lhs.type, rhs.type)) - return false; - - return true; - } - - bool Compare(const Vector& lhs, const Vector& rhs) const - { - return Compare(lhs.componentType, rhs.componentType) && lhs.componentCount == rhs.componentCount; - } - - bool Compare(const Void& /*lhs*/, const Void& /*rhs*/) const - { - return true; - } - - - bool Compare(const Constant& lhs, const Constant& rhs) const - { - return Compare(lhs.constant, rhs.constant); - } - - bool Compare(const Type& lhs, const Type& rhs) const - { - return Compare(lhs.type, rhs.type); - } - - - template - bool Compare(const std::optional& lhs, const std::optional& rhs) const - { - if (lhs.has_value() != rhs.has_value()) - return false; - - if (!lhs.has_value()) - return true; - - return Compare(*lhs, *rhs); - } - - template - bool Compare(const std::shared_ptr& lhs, const std::shared_ptr& rhs) const - { - if (bool(lhs) != bool(rhs)) - return false; - - if (!lhs) - return true; - - return Compare(*lhs, *rhs); - } - - template - bool Compare(const std::variant& lhs, const std::variant& rhs) const - { - if (lhs.index() != rhs.index()) - return false; - - return std::visit([&](auto&& arg) - { - using U = std::decay_t; - return Compare(arg, std::get(rhs)); - }, lhs); - } - - template - bool Compare(const std::vector& lhs, const std::vector& rhs) const - { - if (lhs.size() != rhs.size()) - return false; - - for (std::size_t i = 0; i < lhs.size(); ++i) - { - if (!Compare(lhs[i], rhs[i])) - return false; - } - - return true; - } - - template - bool Compare(const std::unique_ptr& lhs, const std::unique_ptr& rhs) const - { - if (bool(lhs) != bool(rhs)) - return false; - - if (!lhs) - return true; - - return Compare(*lhs, *rhs); - } - - template - bool operator()(const T& lhs, const T& rhs) const - { - return Compare(lhs, rhs); - } - }; - - struct SpirvConstantCache::DepRegisterer - { - DepRegisterer(SpirvConstantCache& c) : - cache(c) - { - } - - void Register(const Array& array) - { - assert(array.elementType); - cache.Register(*array.elementType); - assert(array.length); - cache.Register(*array.length); - } - - void Register(const Bool&) {} - void Register(const Float&) {} - void Register(const Integer&) {} - void Register(const Void&) {} - - void Register(const Image& image) - { - cache.Register(*image.sampledType); - } - - void Register(const Function& func) - { - cache.Register(*func.returnType); - Register(func.parameters); - } - - void Register(const Matrix& vec) - { - assert(vec.columnType); - cache.Register(*vec.columnType); - } - - void Register(const Pointer& ptr) - { - assert(ptr.type); - cache.Register(*ptr.type); - } - - void Register(const SampledImage& sampledImage) - { - assert(sampledImage.image); - cache.Register(*sampledImage.image); - } - - void Register(const Structure& s) - { - Register(s.members); - cache.BuildFieldOffsets(s); - } - - void Register(const SpirvConstantCache::Structure::Member& m) - { - cache.Register(*m.type); - } - - void Register(const Variable& variable) - { - assert(variable.type); - cache.Register(*variable.type); - } - - void Register(const Vector& vec) - { - assert(vec.componentType); - cache.Register(*vec.componentType); - } - - void Register(const ConstantBool&) - { - cache.Register({ Bool{} }); - } - - void Register(const ConstantScalar& scalar) - { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - cache.Register({ Float{ 64 } }); - else if constexpr (std::is_same_v) - cache.Register({ Float{ 32 } }); - else if constexpr (std::is_same_v) - cache.Register({ Integer{ 32, true } }); - else if constexpr (std::is_same_v) - cache.Register({ Integer{ 64, true } }); - else if constexpr (std::is_same_v) - cache.Register({ Integer{ 32, false } }); - else if constexpr (std::is_same_v) - cache.Register({ Integer{ 64, false } }); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - - }, scalar.value); - } - - void Register(const ConstantComposite& composite) - { - assert(composite.type); - cache.Register(*composite.type); - - for (auto&& value : composite.values) - { - assert(value); - cache.Register(*value); - } - } - - - void Register(const Constant& c) - { - return Register(c.constant); - } - - void Register(const Type& t) - { - return Register(t.type); - } - - - template - void Register(const std::shared_ptr& ptr) - { - assert(ptr); - return Register(*ptr); - } - - template - void Register(const std::optional& opt) - { - if (opt) - Register(*opt); - } - - template - void Register(const std::variant& v) - { - return std::visit([&](auto&& arg) - { - return Register(arg); - }, v); - } - - void Register(const std::vector& lhs) - { - for (std::size_t i = 0; i < lhs.size(); ++i) - cache.Register(*lhs[i]); - } - - template - void Register(const std::vector& lhs) - { - for (std::size_t i = 0; i < lhs.size(); ++i) - Register(lhs[i]); - } - - template - void Register(const std::unique_ptr& lhs) - { - assert(lhs); - return Register(*lhs); - } - - SpirvConstantCache& cache; - }; - - //< FIXME PLZ - struct AnyHasher - { - template - std::size_t operator()(const U&) const - { - return 42; - } - }; - - struct SpirvConstantCache::Internal - { - struct StructOffsets - { - FieldOffsets fieldOffsets; - std::vector offsets; - }; - - Internal(UInt32& resultId) : - nextResultId(resultId) - { - } - - tsl::ordered_map, UInt32 /*id*/, AnyHasher, Eq> ids; - tsl::ordered_map variableIds; - StructCallback structCallback; - UInt32& nextResultId; - bool isInBlockStruct = false; - }; - - SpirvConstantCache::SpirvConstantCache(UInt32& resultId) - { - m_internal = std::make_unique(resultId); - } - - SpirvConstantCache::SpirvConstantCache(SpirvConstantCache&& cache) noexcept = default; - - SpirvConstantCache::~SpirvConstantCache() = default; - - auto SpirvConstantCache::BuildConstant(const ShaderAst::ConstantValue& value) const -> ConstantPtr - { - return std::make_shared(std::visit([&](auto&& arg) -> SpirvConstantCache::AnyConstant - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - throw std::runtime_error("invalid type (value expected)"); - else if constexpr (std::is_same_v) - throw std::runtime_error("unexpected string litteral"); - else if constexpr (std::is_same_v) - return ConstantBool{ arg }; - else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) - return ConstantScalar{ arg }; - else if constexpr (std::is_same_v || std::is_same_v) - { - return ConstantComposite{ - BuildType(ShaderAst::VectorType{ 2, (std::is_same_v) ? ShaderAst::PrimitiveType::Float32 : ShaderAst::PrimitiveType::Int32 }), - { - BuildConstant(arg.x), - BuildConstant(arg.y) - } - }; - } - else if constexpr (std::is_same_v || std::is_same_v) - { - return ConstantComposite{ - BuildType(ShaderAst::VectorType{ 3, (std::is_same_v) ? ShaderAst::PrimitiveType::Float32 : ShaderAst::PrimitiveType::Int32 }), - { - BuildConstant(arg.x), - BuildConstant(arg.y), - BuildConstant(arg.z) - } - }; - } - else if constexpr (std::is_same_v || std::is_same_v) - { - return ConstantComposite{ - BuildType(ShaderAst::VectorType{ 4, (std::is_same_v) ? ShaderAst::PrimitiveType::Float32 : ShaderAst::PrimitiveType::Int32 }), - { - BuildConstant(arg.x), - BuildConstant(arg.y), - BuildConstant(arg.z), - BuildConstant(arg.w) - } - }; - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, value)); - } - - FieldOffsets SpirvConstantCache::BuildFieldOffsets(const Structure& structData) const - { - FieldOffsets structOffsets(StructLayout::Std140); - - for (const Structure::Member& member : structData.members) - { - member.offset = SafeCast(std::visit([&](auto&& arg) -> std::size_t - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - { - assert(std::holds_alternative(arg.length->constant)); - const auto& scalar = std::get(arg.length->constant); - assert(std::holds_alternative(scalar.value)); - std::size_t length = std::get(scalar.value); - - return RegisterArrayField(structOffsets, arg.elementType->type, length); - } - else if constexpr (std::is_same_v) - return structOffsets.AddField(StructFieldType::Bool1); - else if constexpr (std::is_same_v) - { - switch (arg.width) - { - case 32: return structOffsets.AddField(StructFieldType::Float1); - case 64: return structOffsets.AddField(StructFieldType::Double1); - default: throw std::runtime_error("unexpected float width " + std::to_string(arg.width)); - } - } - else if constexpr (std::is_same_v) - return structOffsets.AddField((arg.signedness) ? StructFieldType::Int1 : StructFieldType::UInt1); - else if constexpr (std::is_same_v) - { - assert(std::holds_alternative(arg.columnType->type)); - Vector& columnVec = std::get(arg.columnType->type); - - if (!std::holds_alternative(columnVec.componentType->type)) - throw std::runtime_error("unexpected vector type"); - - Float& vecType = std::get(columnVec.componentType->type); - - StructFieldType columnType; - switch (vecType.width) - { - case 32: columnType = StructFieldType::Float1; break; - case 64: columnType = StructFieldType::Double1; break; - default: throw std::runtime_error("unexpected float width " + std::to_string(vecType.width)); - } - - return structOffsets.AddMatrix(columnType, arg.columnCount, columnVec.componentCount, true); - } - else if constexpr (std::is_same_v) - throw std::runtime_error("unhandled pointer in struct"); - else if constexpr (std::is_same_v) - return structOffsets.AddStruct(BuildFieldOffsets(arg)); - else if constexpr (std::is_same_v) - { - if (std::holds_alternative(arg.componentType->type)) - return structOffsets.AddField(static_cast(UnderlyingCast(StructFieldType::Bool1) + arg.componentCount - 1)); - else if (std::holds_alternative(arg.componentType->type)) - { - Float& floatData = std::get(arg.componentType->type); - switch (floatData.width) - { - case 32: return structOffsets.AddField(static_cast(UnderlyingCast(StructFieldType::Float1) + arg.componentCount - 1)); - case 64: return structOffsets.AddField(static_cast(UnderlyingCast(StructFieldType::Double1) + arg.componentCount - 1)); - default: throw std::runtime_error("unexpected float width " + std::to_string(floatData.width)); - } - } - else if (std::holds_alternative(arg.componentType->type)) - { - Integer& intData = std::get(arg.componentType->type); - if (intData.width != 32) - throw std::runtime_error("unexpected integer width " + std::to_string(intData.width)); - - if (intData.signedness) - return structOffsets.AddField(static_cast(UnderlyingCast(StructFieldType::Int1) + arg.componentCount - 1)); - else - return structOffsets.AddField(static_cast(UnderlyingCast(StructFieldType::UInt1) + arg.componentCount - 1)); - } - else - throw std::runtime_error("unexpected type for vector"); - } - else if constexpr (std::is_same_v) - throw std::runtime_error("unexpected function as struct member"); - else if constexpr (std::is_same_v) - throw std::runtime_error("unexpected identifier"); - else if constexpr (std::is_same_v || std::is_same_v) - throw std::runtime_error("unexpected opaque type as struct member"); - else if constexpr (std::is_same_v) - throw std::runtime_error("unexpected void as struct member"); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, member.type->type)); - } - - return structOffsets; - } - - auto SpirvConstantCache::BuildFunctionType(const ShaderAst::ExpressionType& retType, const std::vector& parameters) const -> TypePtr - { - std::vector parameterTypes; - parameterTypes.reserve(parameters.size()); - - for (const auto& parameterType : parameters) - parameterTypes.push_back(BuildPointerType(parameterType, SpirvStorageClass::Function)); - - return std::make_shared(Function{ - BuildType(retType), - std::move(parameterTypes) - }); - } - - auto SpirvConstantCache::BuildPointerType(const ShaderAst::ExpressionType& type, SpirvStorageClass storageClass) const -> TypePtr - { - bool wasInblockStruct = m_internal->isInBlockStruct; - if (storageClass == SpirvStorageClass::Uniform) - m_internal->isInBlockStruct = true; - - auto typePtr = std::make_shared(Pointer{ - BuildType(type), - storageClass - }); - - m_internal->isInBlockStruct = wasInblockStruct; - - return typePtr; - } - - auto SpirvConstantCache::BuildPointerType(const TypePtr& type, SpirvStorageClass storageClass) const -> TypePtr - { - bool wasInblockStruct = m_internal->isInBlockStruct; - if (storageClass == SpirvStorageClass::Uniform) - m_internal->isInBlockStruct = true; - - auto typePtr = std::make_shared(Pointer{ - type, - storageClass - }); - - m_internal->isInBlockStruct = wasInblockStruct; - - return typePtr; - } - - auto SpirvConstantCache::BuildPointerType(const ShaderAst::PrimitiveType& type, SpirvStorageClass storageClass) const -> TypePtr - { - bool wasInblockStruct = m_internal->isInBlockStruct; - if (storageClass == SpirvStorageClass::Uniform) - m_internal->isInBlockStruct = true; - - auto typePtr = std::make_shared(Pointer{ - BuildType(type), - storageClass - }); - - m_internal->isInBlockStruct = wasInblockStruct; - - return typePtr; - } - - auto SpirvConstantCache::BuildType(const ShaderAst::AliasType& /*type*/) const -> TypePtr - { - // No AliasType is expected (as they should have been resolved by now) - throw std::runtime_error("unexpected alias"); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::ArrayType& type) const -> TypePtr - { - const auto& containedType = type.containedType->type; - - TypePtr builtContainedType = BuildType(containedType); - - // ArrayStride - std::optional arrayStride; - if (m_internal->isInBlockStruct) - { - FieldOffsets fieldOffset(StructLayout::Std140); - RegisterArrayField(fieldOffset, builtContainedType->type, 1); - - arrayStride = SafeCast(fieldOffset.GetAlignedSize()); - } - - return std::make_shared(Array{ - builtContainedType, - BuildConstant(type.length), - arrayStride - }); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::ExpressionType& type) const -> TypePtr - { - return std::visit([&](auto&& arg) -> TypePtr - { - return BuildType(arg); - }, type); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::PrimitiveType& type) const -> TypePtr - { - return std::make_shared([&]() -> AnyType - { - switch (type) - { - case ShaderAst::PrimitiveType::Boolean: - return Bool{}; - - case ShaderAst::PrimitiveType::Float32: - return Float{ 32 }; - - case ShaderAst::PrimitiveType::Int32: - return Integer{ 32, true }; - - case ShaderAst::PrimitiveType::UInt32: - return Integer{ 32, false }; - - case ShaderAst::PrimitiveType::String: - break; - } - - throw std::runtime_error("unexpected type"); - }()); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::MatrixType& type) const -> TypePtr - { - return std::make_shared( - Matrix{ - BuildType(ShaderAst::VectorType { - UInt32(type.rowCount), type.type - }), - UInt32(type.columnCount) - }); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::NoType& /*type*/) const -> TypePtr - { - return std::make_shared(Void{}); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::SamplerType& type) const -> TypePtr - { - Image imageType; - imageType.sampled = true; - imageType.sampledType = BuildType(type.sampledType); - - switch (type.dim) - { - case ImageType::Cubemap: - imageType.dim = SpirvDim::Cube; - break; - - case ImageType::E1D_Array: - imageType.arrayed = true; - [[fallthrough]]; - case ImageType::E1D: - imageType.dim = SpirvDim::Dim1D; - break; - - case ImageType::E2D_Array: - imageType.arrayed = true; - [[fallthrough]]; - case ImageType::E2D: - imageType.dim = SpirvDim::Dim2D; - break; - - case ImageType::E3D: - imageType.dim = SpirvDim::Dim3D; - break; - } - - return std::make_shared(SampledImage{ std::make_shared(imageType) }); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::StructType& type) const -> TypePtr - { - assert(m_internal->structCallback); - return BuildType(m_internal->structCallback(type.structIndex)); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::StructDescription& structDesc, std::vector decorations) const -> TypePtr - { - Structure sType; - sType.name = structDesc.name; - sType.decorations = std::move(decorations); - - bool wasInBlock = m_internal->isInBlockStruct; - if (!wasInBlock) - m_internal->isInBlockStruct = std::find(sType.decorations.begin(), sType.decorations.end(), SpirvDecoration::Block) != sType.decorations.end(); - - for (const auto& member : structDesc.members) - { - if (member.cond.HasValue() && !member.cond.GetResultingValue()) - continue; - - auto& sMembers = sType.members.emplace_back(); - sMembers.name = member.name; - sMembers.type = BuildType(member.type.GetResultingValue()); - } - - m_internal->isInBlockStruct = wasInBlock; - - return std::make_shared(std::move(sType)); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::VectorType& type) const -> TypePtr - { - return std::make_shared(Vector{ BuildType(type.type), UInt32(type.componentCount) }); - } - - auto SpirvConstantCache::BuildType(const ShaderAst::UniformType& type) const -> TypePtr - { - return BuildType(type.containedType); - } - - UInt32 SpirvConstantCache::GetId(const Constant& c) - { - auto it = m_internal->ids.find(c.constant); - if (it == m_internal->ids.end()) - throw std::runtime_error("constant is not registered"); - - return it->second; - } - - UInt32 SpirvConstantCache::GetId(const Type& t) - { - auto it = m_internal->ids.find(t.type); - if (it == m_internal->ids.end()) - throw std::runtime_error("type is not registered"); - - return it->second; - } - - UInt32 SpirvConstantCache::GetId(const Variable& v) - { - auto it = m_internal->variableIds.find(v); - if (it == m_internal->variableIds.end()) - throw std::runtime_error("variable is not registered"); - - return it->second; - } - - UInt32 SpirvConstantCache::Register(Constant c) - { - AnyConstant& constant = c.constant; - - DepRegisterer registerer(*this); - registerer.Register(constant); - - std::size_t h = m_internal->ids.hash_function()(constant); - auto it = m_internal->ids.find(constant, h); - if (it == m_internal->ids.end()) - { - UInt32 resultId = m_internal->nextResultId++; - it = m_internal->ids.emplace(std::move(constant), resultId).first; - } - - return it.value(); - } - - UInt32 SpirvConstantCache::Register(Type t) - { - AnyType& type = t.type; - - DepRegisterer registerer(*this); - registerer.Register(type); - - std::size_t h = m_internal->ids.hash_function()(type); - auto it = m_internal->ids.find(type, h); - if (it == m_internal->ids.end()) - { - UInt32 resultId = m_internal->nextResultId++; - it = m_internal->ids.emplace(std::move(type), resultId).first; - } - - return it.value(); - } - - UInt32 SpirvConstantCache::Register(Variable v) - { - DepRegisterer registerer(*this); - registerer.Register(v); - - std::size_t h = m_internal->variableIds.hash_function()(v); - auto it = m_internal->variableIds.find(v, h); - if (it == m_internal->variableIds.end()) - { - UInt32 resultId = m_internal->nextResultId++; - it = m_internal->variableIds.emplace(std::move(v), resultId).first; - } - - return it.value(); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Array& type, std::size_t arrayLength) const - { - FieldOffsets dummyStruct(fieldOffsets.GetLayout()); - RegisterArrayField(dummyStruct, type.elementType->type, std::get(std::get(type.length->constant).value)); - - return fieldOffsets.AddStructArray(dummyStruct, arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Bool& type, std::size_t arrayLength) const - { - return fieldOffsets.AddFieldArray(SpirvTypeToStructFieldType(type), arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Float& type, std::size_t arrayLength) const - { - return fieldOffsets.AddFieldArray(SpirvTypeToStructFieldType(type), arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& /*fieldOffsets*/, const Function& /*type*/, std::size_t /*arrayLength*/) const - { - throw std::runtime_error("unexpected Function"); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& /*fieldOffsets*/, const Image& /*type*/, std::size_t /*arrayLength*/) const - { - throw std::runtime_error("unexpected Image"); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Integer& type, std::size_t arrayLength) const - { - return fieldOffsets.AddFieldArray(SpirvTypeToStructFieldType(type), arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Matrix& type, std::size_t arrayLength) const - { - if (!std::holds_alternative(type.columnType->type)) - throw std::runtime_error("unexpected column type"); - - const Vector& vecType = std::get(type.columnType->type); - return fieldOffsets.AddMatrixArray(SpirvTypeToStructFieldType(vecType.componentType->type), type.columnCount, vecType.componentCount, true, arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& /*fieldOffsets*/, const Pointer& /*type*/, std::size_t /*arrayLength*/) const - { - throw std::runtime_error("unexpected Pointer (not implemented)"); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& /*fieldOffsets*/, const SampledImage& /*type*/, std::size_t /*arrayLength*/) const - { - throw std::runtime_error("unexpected SampledImage"); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Structure& type, std::size_t arrayLength) const - { - auto innerFieldOffset = BuildFieldOffsets(type); - return fieldOffsets.AddStructArray(innerFieldOffset, arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Type& type, std::size_t arrayLength) const - { - return std::visit([&](auto&& arg) -> std::size_t - { - return RegisterArrayField(fieldOffsets, arg, arrayLength); - }, type.type); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& fieldOffsets, const Vector& type, std::size_t arrayLength) const - { - assert(type.componentCount > 0 && type.componentCount <= 4); - return fieldOffsets.AddFieldArray(static_cast(UnderlyingCast(SpirvTypeToStructFieldType(type.componentType->type)) + type.componentCount), arrayLength); - } - - std::size_t SpirvConstantCache::RegisterArrayField(FieldOffsets& /*fieldOffsets*/, const Void& /*type*/, std::size_t /*arrayLength*/) const - { - throw std::runtime_error("unexpected Void"); - } - - void SpirvConstantCache::SetStructCallback(StructCallback callback) - { - m_internal->structCallback = std::move(callback); - } - - void SpirvConstantCache::Write(SpirvSection& annotations, SpirvSection& constants, SpirvSection& debugInfos) - { - for (auto&& [object, id] : m_internal->ids) - { - UInt32 resultId = id; - - std::visit(Overloaded - { - [&](const AnyConstant& constant) { Write(constant, resultId, constants); }, - [&](const AnyType& type) { Write(type, resultId, annotations, constants, debugInfos); }, - }, object); - } - - for (auto&& [variable, id] : m_internal->variableIds) - { - const auto& var = variable; - UInt32 resultId = id; - - if (!variable.debugName.empty()) - debugInfos.Append(SpirvOp::OpName, resultId, variable.debugName); - - constants.AppendVariadic(SpirvOp::OpVariable, [&](const auto& appender) - { - appender(GetId(*var.type)); - appender(resultId); - appender(var.storageClass); - - if (var.initializer) - appender(GetId((*var.initializer)->constant)); - }); - } - } - - SpirvConstantCache& SpirvConstantCache::operator=(SpirvConstantCache&& cache) noexcept = default; - - void SpirvConstantCache::Write(const AnyConstant& constant, UInt32 resultId, SpirvSection& constants) - { - std::visit([&](auto&& arg) - { - using ConstantType = std::decay_t; - - if constexpr (std::is_same_v) - constants.Append((arg.value) ? SpirvOp::OpConstantTrue : SpirvOp::OpConstantFalse, GetId({ Bool{} }), resultId); - else if constexpr (std::is_same_v) - { - constants.AppendVariadic(SpirvOp::OpConstantComposite, [&](const auto& appender) - { - appender(GetId(arg.type->type)); - appender(resultId); - - for (const auto& value : arg.values) - appender(GetId(value->constant)); - }); - } - else if constexpr (std::is_same_v) - { - std::visit([&](auto&& value) - { - using ValueType = std::decay_t; - - UInt32 typeId; - if constexpr (std::is_same_v) - typeId = GetId({ Float{ 64 } }); - else if constexpr (std::is_same_v) - typeId = GetId({ Float{ 32 } }); - else if constexpr (std::is_same_v) - typeId = GetId({ Integer{ 32, true } }); - else if constexpr (std::is_same_v) - typeId = GetId({ Integer{ 64, true } }); - else if constexpr (std::is_same_v) - typeId = GetId({ Integer{ 32, false } }); - else if constexpr (std::is_same_v) - typeId = GetId({ Integer{ 64, false } }); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - - constants.Append(SpirvOp::OpConstant, typeId, resultId, SpirvSection::Raw{ &value, sizeof(value) }); - - }, arg.value); - } - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, constant); - } - - void SpirvConstantCache::Write(const AnyType& type, UInt32 resultId, SpirvSection& annotations, SpirvSection& constants, SpirvSection& debugInfos) - { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - { - constants.Append(SpirvOp::OpTypeArray, resultId, GetId(*arg.elementType), GetId(*arg.length)); - if (arg.stride) - annotations.Append(SpirvOp::OpDecorate, resultId, SpirvDecoration::ArrayStride, *arg.stride); - } - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeBool, resultId); - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeFloat, resultId, arg.width); - else if constexpr (std::is_same_v) - { - constants.AppendVariadic(SpirvOp::OpTypeFunction, [&](const auto& appender) - { - appender(resultId); - appender(GetId(*arg.returnType)); - - for (const auto& param : arg.parameters) - appender(GetId(*param)); - }); - } - else if constexpr (std::is_same_v) - throw std::runtime_error("unexpected identifier"); - else if constexpr (std::is_same_v) - { - UInt32 depth; - if (arg.depth.has_value()) - depth = (*arg.depth) ? 1 : 0; - else - depth = 2; - - UInt32 sampled; - if (arg.sampled.has_value()) - sampled = (*arg.sampled) ? 1 : 2; //< Yes/No - else - sampled = 0; //< Dunno - - constants.AppendVariadic(SpirvOp::OpTypeImage, [&](const auto& appender) - { - appender(resultId); - appender(GetId(*arg.sampledType)); - appender(arg.dim); - appender(depth); - appender(arg.arrayed); - appender(arg.multisampled); - appender(sampled); - appender(arg.format); - - if (arg.qualifier) - appender(*arg.qualifier); - }); - } - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeInt, resultId, arg.width, arg.signedness); - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeMatrix, resultId, GetId(*arg.columnType), arg.columnCount); - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypePointer, resultId, arg.storageClass, GetId(*arg.type)); - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeSampledImage, resultId, GetId(*arg.image)); - else if constexpr (std::is_same_v) - WriteStruct(arg, resultId, annotations, constants, debugInfos); - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeVector, resultId, GetId(*arg.componentType), arg.componentCount); - else if constexpr (std::is_same_v) - constants.Append(SpirvOp::OpTypeVoid, resultId); - else - static_assert(AlwaysFalse::value, "non-exhaustive visitor"); - }, type); - } - - void SpirvConstantCache::WriteStruct(const Structure& structData, UInt32 resultId, SpirvSection& annotations, SpirvSection& constants, SpirvSection& debugInfos) - { - constants.AppendVariadic(SpirvOp::OpTypeStruct, [&](const auto& appender) - { - appender(resultId); - - for (const auto& member : structData.members) - appender(GetId(*member.type)); - }); - - debugInfos.Append(SpirvOp::OpName, resultId, structData.name); - - for (SpirvDecoration decoration : structData.decorations) - annotations.Append(SpirvOp::OpDecorate, resultId, decoration); - - for (std::size_t memberIndex = 0; memberIndex < structData.members.size(); ++memberIndex) - { - const auto& member = structData.members[memberIndex]; - debugInfos.Append(SpirvOp::OpMemberName, resultId, memberIndex, member.name); - - UInt32 offset = member.offset.value(); - - std::visit([&](auto&& arg) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - { - annotations.Append(SpirvOp::OpMemberDecorate, resultId, memberIndex, SpirvDecoration::ColMajor); - annotations.Append(SpirvOp::OpMemberDecorate, resultId, memberIndex, SpirvDecoration::MatrixStride, 16); - } - }, member.type->type); - - annotations.Append(SpirvOp::OpMemberDecorate, resultId, memberIndex, SpirvDecoration::Offset, offset); - } - } -} diff --git a/src/Nazara/Shader/SpirvData.cpp b/src/Nazara/Shader/SpirvData.cpp deleted file mode 100644 index 58147c899..000000000 --- a/src/Nazara/Shader/SpirvData.cpp +++ /dev/null @@ -1,15662 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// this file was automatically generated and should not be edited - -#include -#include -#include -#include -#include - -namespace Nz -{ - static constexpr std::array s_operands = { - { - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralString, - R"('Continued Source')" - }, - { - SpirvOperandKind::SourceLanguage, - R"(SourceLanguage)" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Version')" - }, - { - SpirvOperandKind::IdRef, - R"('File')" - }, - { - SpirvOperandKind::LiteralString, - R"('Source')" - }, - { - SpirvOperandKind::LiteralString, - R"('Extension')" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::LiteralString, - R"('Name')" - }, - { - SpirvOperandKind::IdRef, - R"('Type')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Member')" - }, - { - SpirvOperandKind::LiteralString, - R"('Name')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralString, - R"('String')" - }, - { - SpirvOperandKind::IdRef, - R"('File')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Line')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Column')" - }, - { - SpirvOperandKind::LiteralString, - R"('Name')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralString, - R"('Name')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Set')" - }, - { - SpirvOperandKind::LiteralExtInstInteger, - R"('Instruction')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1', + -'Operand 2', + -...)" - }, - { - SpirvOperandKind::AddressingModel, - R"(AddressingModel)" - }, - { - SpirvOperandKind::MemoryModel, - R"(MemoryModel)" - }, - { - SpirvOperandKind::ExecutionModel, - R"(ExecutionModel)" - }, - { - SpirvOperandKind::IdRef, - R"('Entry Point')" - }, - { - SpirvOperandKind::LiteralString, - R"('Name')" - }, - { - SpirvOperandKind::IdRef, - R"('Interface')" - }, - { - SpirvOperandKind::IdRef, - R"('Entry Point')" - }, - { - SpirvOperandKind::ExecutionMode, - R"('Mode')" - }, - { - SpirvOperandKind::Capability, - R"('Capability')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Width')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Signedness')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Width')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Component Type')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Component Count')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Column Type')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Column Count')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Type')" - }, - { - SpirvOperandKind::Dim, - R"(Dim)" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Depth')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Arrayed')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('MS')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Sampled')" - }, - { - SpirvOperandKind::ImageFormat, - R"(ImageFormat)" - }, - { - SpirvOperandKind::AccessQualifier, - R"(AccessQualifier)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image Type')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Element Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Length')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Element Type')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Member 0 type', + -'member 1 type', + -...)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralString, - R"(The name of the opaque type.)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::StorageClass, - R"(StorageClass)" - }, - { - SpirvOperandKind::IdRef, - R"('Type')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Return Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Parameter 0 Type', + -'Parameter 1 Type', + -...)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::AccessQualifier, - R"('Qualifier')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer Type')" - }, - { - SpirvOperandKind::StorageClass, - R"(StorageClass)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralContextDependentNumber, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Constituents')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::SamplerAddressingMode, - R"(SamplerAddressingMode)" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Param')" - }, - { - SpirvOperandKind::SamplerFilterMode, - R"(SamplerFilterMode)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralContextDependentNumber, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Constituents')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralSpecConstantOpInteger, - R"('Opcode')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::FunctionControl, - R"(FunctionControl)" - }, - { - SpirvOperandKind::IdRef, - R"('Function Type')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Function')" - }, - { - SpirvOperandKind::IdRef, - R"('Argument 0', + -'Argument 1', + -...)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::StorageClass, - R"(StorageClass)" - }, - { - SpirvOperandKind::IdRef, - R"('Initializer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Sample')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Object')" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::IdRef, - R"('Source')" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::IdRef, - R"('Source')" - }, - { - SpirvOperandKind::IdRef, - R"('Size')" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Indexes')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Indexes')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Element')" - }, - { - SpirvOperandKind::IdRef, - R"('Indexes')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Structure')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Array member')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Element')" - }, - { - SpirvOperandKind::IdRef, - R"('Indexes')" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::Decoration, - R"(Decoration)" - }, - { - SpirvOperandKind::IdRef, - R"('Structure Type')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Member')" - }, - { - SpirvOperandKind::Decoration, - R"(Decoration)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Decoration Group')" - }, - { - SpirvOperandKind::IdRef, - R"('Targets')" - }, - { - SpirvOperandKind::IdRef, - R"('Decoration Group')" - }, - { - SpirvOperandKind::PairIdRefLiteralInteger, - R"('Targets')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdRef, - R"('Component')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Components')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Constituents')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Composite')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Indexes')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Object')" - }, - { - SpirvOperandKind::IdRef, - R"('Composite')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Indexes')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Matrix')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Sampler')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Component')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Texel')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Level of Detail')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Float Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Float Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Signed Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Unsigned Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Unsigned Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Signed Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Float Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Signed Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Unsigned Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Integer Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::StorageClass, - R"('Storage')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdRef, - R"('Scalar')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Matrix')" - }, - { - SpirvOperandKind::IdRef, - R"('Scalar')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdRef, - R"('Matrix')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Matrix')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('LeftMatrix')" - }, - { - SpirvOperandKind::IdRef, - R"('RightMatrix')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdRef, - R"('y')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdRef, - R"('y')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('x')" - }, - { - SpirvOperandKind::IdRef, - R"('y')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Condition')" - }, - { - SpirvOperandKind::IdRef, - R"('Object 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Object 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Shift')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Shift')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Shift')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Insert')" - }, - { - SpirvOperandKind::IdRef, - R"('Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Count')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Count')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdRef, - R"('Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Count')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Base')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('P')" - }, - { - SpirvOperandKind::IdRef, - R"('Stream')" - }, - { - SpirvOperandKind::IdRef, - R"('Stream')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Equal')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Unequal')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Comparator')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Equal')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Unequal')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Comparator')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::PairIdRefIdRef, - R"('Variable, Parent, ...')" - }, - { - SpirvOperandKind::IdRef, - R"('Merge Block')" - }, - { - SpirvOperandKind::IdRef, - R"('Continue Target')" - }, - { - SpirvOperandKind::LoopControl, - R"(LoopControl)" - }, - { - SpirvOperandKind::IdRef, - R"('Merge Block')" - }, - { - SpirvOperandKind::SelectionControl, - R"(SelectionControl)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Target Label')" - }, - { - SpirvOperandKind::IdRef, - R"('Condition')" - }, - { - SpirvOperandKind::IdRef, - R"('True Label')" - }, - { - SpirvOperandKind::IdRef, - R"('False Label')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Branch weights')" - }, - { - SpirvOperandKind::IdRef, - R"('Selector')" - }, - { - SpirvOperandKind::IdRef, - R"('Default')" - }, - { - SpirvOperandKind::PairLiteralIntegerIdRef, - R"('Target')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Size')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Destination')" - }, - { - SpirvOperandKind::IdRef, - R"('Source')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Elements')" - }, - { - SpirvOperandKind::IdRef, - R"('Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Event')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Events')" - }, - { - SpirvOperandKind::IdRef, - R"('Events List')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('LocalId')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Packets')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Packets')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Packets')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Packets')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe')" - }, - { - SpirvOperandKind::IdRef, - R"('Reserve Id')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Queue')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Events')" - }, - { - SpirvOperandKind::IdRef, - R"('Wait Events')" - }, - { - SpirvOperandKind::IdRef, - R"('Ret Event')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Queue')" - }, - { - SpirvOperandKind::IdRef, - R"('Flags')" - }, - { - SpirvOperandKind::IdRef, - R"('ND Range')" - }, - { - SpirvOperandKind::IdRef, - R"('Num Events')" - }, - { - SpirvOperandKind::IdRef, - R"('Wait Events')" - }, - { - SpirvOperandKind::IdRef, - R"('Ret Event')" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdRef, - R"('Local Size')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('ND Range')" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('ND Range')" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdRef, - R"('Event')" - }, - { - SpirvOperandKind::IdRef, - R"('Event')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Event')" - }, - { - SpirvOperandKind::IdRef, - R"('Event')" - }, - { - SpirvOperandKind::IdRef, - R"('Status')" - }, - { - SpirvOperandKind::IdRef, - R"('Event')" - }, - { - SpirvOperandKind::IdRef, - R"('Profiling Info')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('GlobalWorkSize')" - }, - { - SpirvOperandKind::IdRef, - R"('LocalWorkSize')" - }, - { - SpirvOperandKind::IdRef, - R"('GlobalWorkOffset')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Component')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('D~ref~')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Resident Code')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Packet Size')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Capacity')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pipe Storage')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Subgroup Count')" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Invoke')" - }, - { - SpirvOperandKind::IdRef, - R"('Param')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Param Align')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Subgroup Count')" - }, - { - SpirvOperandKind::IdRef, - R"('Named Barrier')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::LiteralString, - R"('Process')" - }, - { - SpirvOperandKind::IdRef, - R"('Entry Point')" - }, - { - SpirvOperandKind::ExecutionMode, - R"('Mode')" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::Decoration, - R"(Decoration)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Id')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Id')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Mask')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Delta')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Delta')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Predicate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Delta')" - }, - { - SpirvOperandKind::IdRef, - R"('ClusterSize')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Accel')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Flags')" - }, - { - SpirvOperandKind::IdRef, - R"('Cull Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Miss Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Origin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Direction')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmax')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Callable Data')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Accel')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::PackedVectorFormat, - R"('Packed Vector Format')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::PackedVectorFormat, - R"('Packed Vector Format')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::PackedVectorFormat, - R"('Packed Vector Format')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::IdRef, - R"('Accumulator')" - }, - { - SpirvOperandKind::PackedVectorFormat, - R"('Packed Vector Format')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::IdRef, - R"('Accumulator')" - }, - { - SpirvOperandKind::PackedVectorFormat, - R"('Packed Vector Format')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Vector 2')" - }, - { - SpirvOperandKind::IdRef, - R"('Accumulator')" - }, - { - SpirvOperandKind::PackedVectorFormat, - R"('Packed Vector Format')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Accel')" - }, - { - SpirvOperandKind::IdRef, - R"('RayFlags')" - }, - { - SpirvOperandKind::IdRef, - R"('CullMask')" - }, - { - SpirvOperandKind::IdRef, - R"('RayOrigin')" - }, - { - SpirvOperandKind::IdRef, - R"('RayTMin')" - }, - { - SpirvOperandKind::IdRef, - R"('RayDirection')" - }, - { - SpirvOperandKind::IdRef, - R"('RayTMax')" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('HitT')" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Fragment Index')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Scope')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Sampled Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Granularity')" - }, - { - SpirvOperandKind::IdRef, - R"('Coarse')" - }, - { - SpirvOperandKind::ImageOperands, - R"(ImageOperands)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Index Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Indices')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Hit')" - }, - { - SpirvOperandKind::IdRef, - R"('HitKind')" - }, - { - SpirvOperandKind::IdRef, - R"('Accel')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Flags')" - }, - { - SpirvOperandKind::IdRef, - R"('Cull Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Miss Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Origin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Direction')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmax')" - }, - { - SpirvOperandKind::IdRef, - R"('PayloadId')" - }, - { - SpirvOperandKind::IdRef, - R"('Accel')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Flags')" - }, - { - SpirvOperandKind::IdRef, - R"('Cull Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Miss Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Origin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Direction')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmax')" - }, - { - SpirvOperandKind::IdRef, - R"('Time')" - }, - { - SpirvOperandKind::IdRef, - R"('PayloadId')" - }, - { - SpirvOperandKind::IdRef, - R"('Accel')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Flags')" - }, - { - SpirvOperandKind::IdRef, - R"('Cull Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Miss Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Origin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmin')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Direction')" - }, - { - SpirvOperandKind::IdRef, - R"('Ray Tmax')" - }, - { - SpirvOperandKind::IdRef, - R"('Time')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('SBT Index')" - }, - { - SpirvOperandKind::IdRef, - R"('Callable DataId')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Component Type')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdRef, - R"('Rows')" - }, - { - SpirvOperandKind::IdRef, - R"('Columns')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Column Major')" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdRef, - R"('Object')" - }, - { - SpirvOperandKind::IdRef, - R"('Stride')" - }, - { - SpirvOperandKind::IdRef, - R"('Column Major')" - }, - { - SpirvOperandKind::MemoryAccess, - R"(MemoryAccess)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::IdRef, - R"('C')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Type')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Bit Width')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Data')" - }, - { - SpirvOperandKind::IdRef, - R"('InvocationId')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Current')" - }, - { - SpirvOperandKind::IdRef, - R"('Next')" - }, - { - SpirvOperandKind::IdRef, - R"('Delta')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Previous')" - }, - { - SpirvOperandKind::IdRef, - R"('Current')" - }, - { - SpirvOperandKind::IdRef, - R"('Delta')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Data')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Ptr')" - }, - { - SpirvOperandKind::IdRef, - R"('Ptr')" - }, - { - SpirvOperandKind::IdRef, - R"('Data')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Data')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Width')" - }, - { - SpirvOperandKind::IdRef, - R"('Height')" - }, - { - SpirvOperandKind::IdRef, - R"('Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Coordinate')" - }, - { - SpirvOperandKind::IdRef, - R"('Width')" - }, - { - SpirvOperandKind::IdRef, - R"('Height')" - }, - { - SpirvOperandKind::IdRef, - R"('Data')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Function')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Operand 1')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::LiteralString, - R"('Asm target')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Asm type')" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::LiteralString, - R"('Asm instructions')" - }, - { - SpirvOperandKind::LiteralString, - R"('Constraints')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Asm')" - }, - { - SpirvOperandKind::IdRef, - R"('Argument 0')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('Condition')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdRef, - R"('ExpectedValue')" - }, - { - SpirvOperandKind::IdRef, - R"('Target')" - }, - { - SpirvOperandKind::Decoration, - R"(Decoration)" - }, - { - SpirvOperandKind::IdRef, - R"('Struct Type')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Member')" - }, - { - SpirvOperandKind::Decoration, - R"(Decoration)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Sampler')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image Type')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Slice Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Qp')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Reference Base Penalty')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Slice Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Qp')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Shape Penalty')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Slice Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Qp')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Direction Cost')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Slice Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Qp')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Slice Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Qp')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Cost Center Delta')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Cost Table')" - }, - { - SpirvOperandKind::IdRef, - R"('Cost Precision')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Slice Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Qp')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Source Field Polarity')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Reference Field Polarity')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Forward Reference Field Polarity')" - }, - { - SpirvOperandKind::IdRef, - R"('Backward Reference Field Polarity')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Ids')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Parameter Field Polarities')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Coord')" - }, - { - SpirvOperandKind::IdRef, - R"('Partition Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('SAD Adjustment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Search Window Config')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('id> Search Window Config')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Search Window Config')" - }, - { - SpirvOperandKind::IdRef, - R"('Dual Ref')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Offset')" - }, - { - SpirvOperandKind::IdRef, - R"('Src Coord')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Window Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Image Size')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Max Motion Vector Count')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Threshold')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Sad Weights')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Streamin Components')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Streamin Components')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Streamin Components')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Streamin Components')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shape')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shape')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shape')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shape')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shape')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shape')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Image Select')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Coord')" - }, - { - SpirvOperandKind::IdRef, - R"('Motion Vectors')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shapes')" - }, - { - SpirvOperandKind::IdRef, - R"('Minor Shapes')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdRef, - R"('Pixel Resolution')" - }, - { - SpirvOperandKind::IdRef, - R"('Sad Adjustment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Coord')" - }, - { - SpirvOperandKind::IdRef, - R"('Motion Vectors')" - }, - { - SpirvOperandKind::IdRef, - R"('Major Shapes')" - }, - { - SpirvOperandKind::IdRef, - R"('Minor Shapes')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdRef, - R"('Pixel Resolution')" - }, - { - SpirvOperandKind::IdRef, - R"('Bidirectional Weight')" - }, - { - SpirvOperandKind::IdRef, - R"('Sad Adjustment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Ids')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Ids')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Field Polarities')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Coord')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Skip Block Partition Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Skip Motion Vector Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('Motion Vectors')" - }, - { - SpirvOperandKind::IdRef, - R"('Bidirectional Weight')" - }, - { - SpirvOperandKind::IdRef, - R"('Sad Adjustment')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Luma Intra Partition Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('Intra Neighbour Availabilty')" - }, - { - SpirvOperandKind::IdRef, - R"('Left Edge Luma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Left Corner Luma Pixel')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Edge Luma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Right Edge Luma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Sad Adjustment')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Luma Intra Partition Mask')" - }, - { - SpirvOperandKind::IdRef, - R"('Intra Neighbour Availabilty')" - }, - { - SpirvOperandKind::IdRef, - R"('Left Edge Luma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Left Corner Luma Pixel')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Edge Luma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Right Edge Luma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Left Edge Chroma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Left Corner Chroma Pixel')" - }, - { - SpirvOperandKind::IdRef, - R"('Upper Edge Chroma Pixels')" - }, - { - SpirvOperandKind::IdRef, - R"('Sad Adjustment')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Skip Block Partition Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Direction')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Shape Penalty')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Luma Mode Penalty')" - }, - { - SpirvOperandKind::IdRef, - R"('Luma Packed Neighbor Modes')" - }, - { - SpirvOperandKind::IdRef, - R"('Luma Packed Non Dc Penalty')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Chroma Mode Base Penalty')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Sad Coefficients')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Block Based Skip Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Fwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Bwd Ref Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Ids')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Src Image')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Ids')" - }, - { - SpirvOperandKind::IdRef, - R"('Packed Reference Field Polarities')" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Payload')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Lenght')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Ptr')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('FromSign')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('FromSign')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M2')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('A')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('M1')" - }, - { - SpirvOperandKind::IdRef, - R"('B')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Mout')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('EnableSubnormals')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingMode')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('RoundingAccuracy')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Loop Control Parameters')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Name')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Alias Domain')" - }, - { - SpirvOperandKind::IdRef, - R"('Name')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('AliasScope1, AliasScope2, ...')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Input Type')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('S')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('I')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('rI')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('Q')" - }, - { - SpirvOperandKind::LiteralInteger, - R"('O')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Size')" - }, - { - SpirvOperandKind::IdRef, - R"('Packet Alignment')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Result')" - }, - { - SpirvOperandKind::IdRef, - R"('Input')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('RayQuery')" - }, - { - SpirvOperandKind::IdRef, - R"('Intersection')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdRef, - R"('Pointer')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdRef, - R"('Value')" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::AccessQualifier, - R"('AccessQualifier')" - }, - { - SpirvOperandKind::IdRef, - R"('Member 0 type', + -'member 1 type', + -...)" - }, - { - SpirvOperandKind::IdRef, - R"('Constituents')" - }, - { - SpirvOperandKind::IdRef, - R"('Constituents')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::IdScope, - R"('Memory')" - }, - { - SpirvOperandKind::IdMemorySemantics, - R"('Semantics')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - { - SpirvOperandKind::IdResultType, - R"(IdResultType)" - }, - { - SpirvOperandKind::IdResult, - R"(IdResult)" - }, - { - SpirvOperandKind::IdScope, - R"('Execution')" - }, - { - SpirvOperandKind::GroupOperation, - R"('Operation')" - }, - { - SpirvOperandKind::IdRef, - R"('X')" - }, - } - }; - - static std::array s_instructions = { - { - { - SpirvOp::OpNop, - R"(OpNop)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpUndef, - R"(OpUndef)", - &s_operands[0], - &s_operands[1], - 2, - }, - { - SpirvOp::OpSourceContinued, - R"(OpSourceContinued)", - &s_operands[2], - nullptr, - 1, - }, - { - SpirvOp::OpSource, - R"(OpSource)", - &s_operands[3], - nullptr, - 4, - }, - { - SpirvOp::OpSourceExtension, - R"(OpSourceExtension)", - &s_operands[7], - nullptr, - 1, - }, - { - SpirvOp::OpName, - R"(OpName)", - &s_operands[8], - nullptr, - 2, - }, - { - SpirvOp::OpMemberName, - R"(OpMemberName)", - &s_operands[10], - nullptr, - 3, - }, - { - SpirvOp::OpString, - R"(OpString)", - &s_operands[13], - &s_operands[13], - 2, - }, - { - SpirvOp::OpLine, - R"(OpLine)", - &s_operands[15], - nullptr, - 3, - }, - { - SpirvOp::OpExtension, - R"(OpExtension)", - &s_operands[18], - nullptr, - 1, - }, - { - SpirvOp::OpExtInstImport, - R"(OpExtInstImport)", - &s_operands[19], - &s_operands[19], - 2, - }, - { - SpirvOp::OpExtInst, - R"(OpExtInst)", - &s_operands[21], - &s_operands[22], - 5, - }, - { - SpirvOp::OpMemoryModel, - R"(OpMemoryModel)", - &s_operands[26], - nullptr, - 2, - }, - { - SpirvOp::OpEntryPoint, - R"(OpEntryPoint)", - &s_operands[28], - nullptr, - 4, - }, - { - SpirvOp::OpExecutionMode, - R"(OpExecutionMode)", - &s_operands[32], - nullptr, - 2, - }, - { - SpirvOp::OpCapability, - R"(OpCapability)", - &s_operands[34], - nullptr, - 1, - }, - { - SpirvOp::OpTypeVoid, - R"(OpTypeVoid)", - &s_operands[35], - &s_operands[35], - 1, - }, - { - SpirvOp::OpTypeBool, - R"(OpTypeBool)", - &s_operands[36], - &s_operands[36], - 1, - }, - { - SpirvOp::OpTypeInt, - R"(OpTypeInt)", - &s_operands[37], - &s_operands[37], - 3, - }, - { - SpirvOp::OpTypeFloat, - R"(OpTypeFloat)", - &s_operands[40], - &s_operands[40], - 2, - }, - { - SpirvOp::OpTypeVector, - R"(OpTypeVector)", - &s_operands[42], - &s_operands[42], - 3, - }, - { - SpirvOp::OpTypeMatrix, - R"(OpTypeMatrix)", - &s_operands[45], - &s_operands[45], - 3, - }, - { - SpirvOp::OpTypeImage, - R"(OpTypeImage)", - &s_operands[48], - &s_operands[48], - 9, - }, - { - SpirvOp::OpTypeSampler, - R"(OpTypeSampler)", - &s_operands[57], - &s_operands[57], - 1, - }, - { - SpirvOp::OpTypeSampledImage, - R"(OpTypeSampledImage)", - &s_operands[58], - &s_operands[58], - 2, - }, - { - SpirvOp::OpTypeArray, - R"(OpTypeArray)", - &s_operands[60], - &s_operands[60], - 3, - }, - { - SpirvOp::OpTypeRuntimeArray, - R"(OpTypeRuntimeArray)", - &s_operands[63], - &s_operands[63], - 2, - }, - { - SpirvOp::OpTypeStruct, - R"(OpTypeStruct)", - &s_operands[65], - &s_operands[65], - 2, - }, - { - SpirvOp::OpTypeOpaque, - R"(OpTypeOpaque)", - &s_operands[67], - &s_operands[67], - 2, - }, - { - SpirvOp::OpTypePointer, - R"(OpTypePointer)", - &s_operands[69], - &s_operands[69], - 3, - }, - { - SpirvOp::OpTypeFunction, - R"(OpTypeFunction)", - &s_operands[72], - &s_operands[72], - 3, - }, - { - SpirvOp::OpTypeEvent, - R"(OpTypeEvent)", - &s_operands[75], - &s_operands[75], - 1, - }, - { - SpirvOp::OpTypeDeviceEvent, - R"(OpTypeDeviceEvent)", - &s_operands[76], - &s_operands[76], - 1, - }, - { - SpirvOp::OpTypeReserveId, - R"(OpTypeReserveId)", - &s_operands[77], - &s_operands[77], - 1, - }, - { - SpirvOp::OpTypeQueue, - R"(OpTypeQueue)", - &s_operands[78], - &s_operands[78], - 1, - }, - { - SpirvOp::OpTypePipe, - R"(OpTypePipe)", - &s_operands[79], - &s_operands[79], - 2, - }, - { - SpirvOp::OpTypeForwardPointer, - R"(OpTypeForwardPointer)", - &s_operands[81], - nullptr, - 2, - }, - { - SpirvOp::OpConstantTrue, - R"(OpConstantTrue)", - &s_operands[83], - &s_operands[84], - 2, - }, - { - SpirvOp::OpConstantFalse, - R"(OpConstantFalse)", - &s_operands[85], - &s_operands[86], - 2, - }, - { - SpirvOp::OpConstant, - R"(OpConstant)", - &s_operands[87], - &s_operands[88], - 3, - }, - { - SpirvOp::OpConstantComposite, - R"(OpConstantComposite)", - &s_operands[90], - &s_operands[91], - 3, - }, - { - SpirvOp::OpConstantSampler, - R"(OpConstantSampler)", - &s_operands[93], - &s_operands[94], - 5, - }, - { - SpirvOp::OpConstantNull, - R"(OpConstantNull)", - &s_operands[98], - &s_operands[99], - 2, - }, - { - SpirvOp::OpSpecConstantTrue, - R"(OpSpecConstantTrue)", - &s_operands[100], - &s_operands[101], - 2, - }, - { - SpirvOp::OpSpecConstantFalse, - R"(OpSpecConstantFalse)", - &s_operands[102], - &s_operands[103], - 2, - }, - { - SpirvOp::OpSpecConstant, - R"(OpSpecConstant)", - &s_operands[104], - &s_operands[105], - 3, - }, - { - SpirvOp::OpSpecConstantComposite, - R"(OpSpecConstantComposite)", - &s_operands[107], - &s_operands[108], - 3, - }, - { - SpirvOp::OpSpecConstantOp, - R"(OpSpecConstantOp)", - &s_operands[110], - &s_operands[111], - 3, - }, - { - SpirvOp::OpFunction, - R"(OpFunction)", - &s_operands[113], - &s_operands[114], - 4, - }, - { - SpirvOp::OpFunctionParameter, - R"(OpFunctionParameter)", - &s_operands[117], - &s_operands[118], - 2, - }, - { - SpirvOp::OpFunctionEnd, - R"(OpFunctionEnd)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpFunctionCall, - R"(OpFunctionCall)", - &s_operands[119], - &s_operands[120], - 4, - }, - { - SpirvOp::OpVariable, - R"(OpVariable)", - &s_operands[123], - &s_operands[124], - 4, - }, - { - SpirvOp::OpImageTexelPointer, - R"(OpImageTexelPointer)", - &s_operands[127], - &s_operands[128], - 5, - }, - { - SpirvOp::OpLoad, - R"(OpLoad)", - &s_operands[132], - &s_operands[133], - 4, - }, - { - SpirvOp::OpStore, - R"(OpStore)", - &s_operands[136], - nullptr, - 3, - }, - { - SpirvOp::OpCopyMemory, - R"(OpCopyMemory)", - &s_operands[139], - nullptr, - 4, - }, - { - SpirvOp::OpCopyMemorySized, - R"(OpCopyMemorySized)", - &s_operands[143], - nullptr, - 5, - }, - { - SpirvOp::OpAccessChain, - R"(OpAccessChain)", - &s_operands[148], - &s_operands[149], - 4, - }, - { - SpirvOp::OpInBoundsAccessChain, - R"(OpInBoundsAccessChain)", - &s_operands[152], - &s_operands[153], - 4, - }, - { - SpirvOp::OpPtrAccessChain, - R"(OpPtrAccessChain)", - &s_operands[156], - &s_operands[157], - 5, - }, - { - SpirvOp::OpArrayLength, - R"(OpArrayLength)", - &s_operands[161], - &s_operands[162], - 4, - }, - { - SpirvOp::OpGenericPtrMemSemantics, - R"(OpGenericPtrMemSemantics)", - &s_operands[165], - &s_operands[166], - 3, - }, - { - SpirvOp::OpInBoundsPtrAccessChain, - R"(OpInBoundsPtrAccessChain)", - &s_operands[168], - &s_operands[169], - 5, - }, - { - SpirvOp::OpDecorate, - R"(OpDecorate)", - &s_operands[173], - nullptr, - 2, - }, - { - SpirvOp::OpMemberDecorate, - R"(OpMemberDecorate)", - &s_operands[175], - nullptr, - 3, - }, - { - SpirvOp::OpDecorationGroup, - R"(OpDecorationGroup)", - &s_operands[178], - &s_operands[178], - 1, - }, - { - SpirvOp::OpGroupDecorate, - R"(OpGroupDecorate)", - &s_operands[179], - nullptr, - 2, - }, - { - SpirvOp::OpGroupMemberDecorate, - R"(OpGroupMemberDecorate)", - &s_operands[181], - nullptr, - 2, - }, - { - SpirvOp::OpVectorExtractDynamic, - R"(OpVectorExtractDynamic)", - &s_operands[183], - &s_operands[184], - 4, - }, - { - SpirvOp::OpVectorInsertDynamic, - R"(OpVectorInsertDynamic)", - &s_operands[187], - &s_operands[188], - 5, - }, - { - SpirvOp::OpVectorShuffle, - R"(OpVectorShuffle)", - &s_operands[192], - &s_operands[193], - 5, - }, - { - SpirvOp::OpCompositeConstruct, - R"(OpCompositeConstruct)", - &s_operands[197], - &s_operands[198], - 3, - }, - { - SpirvOp::OpCompositeExtract, - R"(OpCompositeExtract)", - &s_operands[200], - &s_operands[201], - 4, - }, - { - SpirvOp::OpCompositeInsert, - R"(OpCompositeInsert)", - &s_operands[204], - &s_operands[205], - 5, - }, - { - SpirvOp::OpCopyObject, - R"(OpCopyObject)", - &s_operands[209], - &s_operands[210], - 3, - }, - { - SpirvOp::OpTranspose, - R"(OpTranspose)", - &s_operands[212], - &s_operands[213], - 3, - }, - { - SpirvOp::OpSampledImage, - R"(OpSampledImage)", - &s_operands[215], - &s_operands[216], - 4, - }, - { - SpirvOp::OpImageSampleImplicitLod, - R"(OpImageSampleImplicitLod)", - &s_operands[219], - &s_operands[220], - 5, - }, - { - SpirvOp::OpImageSampleExplicitLod, - R"(OpImageSampleExplicitLod)", - &s_operands[224], - &s_operands[225], - 5, - }, - { - SpirvOp::OpImageSampleDrefImplicitLod, - R"(OpImageSampleDrefImplicitLod)", - &s_operands[229], - &s_operands[230], - 6, - }, - { - SpirvOp::OpImageSampleDrefExplicitLod, - R"(OpImageSampleDrefExplicitLod)", - &s_operands[235], - &s_operands[236], - 6, - }, - { - SpirvOp::OpImageSampleProjImplicitLod, - R"(OpImageSampleProjImplicitLod)", - &s_operands[241], - &s_operands[242], - 5, - }, - { - SpirvOp::OpImageSampleProjExplicitLod, - R"(OpImageSampleProjExplicitLod)", - &s_operands[246], - &s_operands[247], - 5, - }, - { - SpirvOp::OpImageSampleProjDrefImplicitLod, - R"(OpImageSampleProjDrefImplicitLod)", - &s_operands[251], - &s_operands[252], - 6, - }, - { - SpirvOp::OpImageSampleProjDrefExplicitLod, - R"(OpImageSampleProjDrefExplicitLod)", - &s_operands[257], - &s_operands[258], - 6, - }, - { - SpirvOp::OpImageFetch, - R"(OpImageFetch)", - &s_operands[263], - &s_operands[264], - 5, - }, - { - SpirvOp::OpImageGather, - R"(OpImageGather)", - &s_operands[268], - &s_operands[269], - 6, - }, - { - SpirvOp::OpImageDrefGather, - R"(OpImageDrefGather)", - &s_operands[274], - &s_operands[275], - 6, - }, - { - SpirvOp::OpImageRead, - R"(OpImageRead)", - &s_operands[280], - &s_operands[281], - 5, - }, - { - SpirvOp::OpImageWrite, - R"(OpImageWrite)", - &s_operands[285], - nullptr, - 4, - }, - { - SpirvOp::OpImage, - R"(OpImage)", - &s_operands[289], - &s_operands[290], - 3, - }, - { - SpirvOp::OpImageQueryFormat, - R"(OpImageQueryFormat)", - &s_operands[292], - &s_operands[293], - 3, - }, - { - SpirvOp::OpImageQueryOrder, - R"(OpImageQueryOrder)", - &s_operands[295], - &s_operands[296], - 3, - }, - { - SpirvOp::OpImageQuerySizeLod, - R"(OpImageQuerySizeLod)", - &s_operands[298], - &s_operands[299], - 4, - }, - { - SpirvOp::OpImageQuerySize, - R"(OpImageQuerySize)", - &s_operands[302], - &s_operands[303], - 3, - }, - { - SpirvOp::OpImageQueryLod, - R"(OpImageQueryLod)", - &s_operands[305], - &s_operands[306], - 4, - }, - { - SpirvOp::OpImageQueryLevels, - R"(OpImageQueryLevels)", - &s_operands[309], - &s_operands[310], - 3, - }, - { - SpirvOp::OpImageQuerySamples, - R"(OpImageQuerySamples)", - &s_operands[312], - &s_operands[313], - 3, - }, - { - SpirvOp::OpConvertFToU, - R"(OpConvertFToU)", - &s_operands[315], - &s_operands[316], - 3, - }, - { - SpirvOp::OpConvertFToS, - R"(OpConvertFToS)", - &s_operands[318], - &s_operands[319], - 3, - }, - { - SpirvOp::OpConvertSToF, - R"(OpConvertSToF)", - &s_operands[321], - &s_operands[322], - 3, - }, - { - SpirvOp::OpConvertUToF, - R"(OpConvertUToF)", - &s_operands[324], - &s_operands[325], - 3, - }, - { - SpirvOp::OpUConvert, - R"(OpUConvert)", - &s_operands[327], - &s_operands[328], - 3, - }, - { - SpirvOp::OpSConvert, - R"(OpSConvert)", - &s_operands[330], - &s_operands[331], - 3, - }, - { - SpirvOp::OpFConvert, - R"(OpFConvert)", - &s_operands[333], - &s_operands[334], - 3, - }, - { - SpirvOp::OpQuantizeToF16, - R"(OpQuantizeToF16)", - &s_operands[336], - &s_operands[337], - 3, - }, - { - SpirvOp::OpConvertPtrToU, - R"(OpConvertPtrToU)", - &s_operands[339], - &s_operands[340], - 3, - }, - { - SpirvOp::OpSatConvertSToU, - R"(OpSatConvertSToU)", - &s_operands[342], - &s_operands[343], - 3, - }, - { - SpirvOp::OpSatConvertUToS, - R"(OpSatConvertUToS)", - &s_operands[345], - &s_operands[346], - 3, - }, - { - SpirvOp::OpConvertUToPtr, - R"(OpConvertUToPtr)", - &s_operands[348], - &s_operands[349], - 3, - }, - { - SpirvOp::OpPtrCastToGeneric, - R"(OpPtrCastToGeneric)", - &s_operands[351], - &s_operands[352], - 3, - }, - { - SpirvOp::OpGenericCastToPtr, - R"(OpGenericCastToPtr)", - &s_operands[354], - &s_operands[355], - 3, - }, - { - SpirvOp::OpGenericCastToPtrExplicit, - R"(OpGenericCastToPtrExplicit)", - &s_operands[357], - &s_operands[358], - 4, - }, - { - SpirvOp::OpBitcast, - R"(OpBitcast)", - &s_operands[361], - &s_operands[362], - 3, - }, - { - SpirvOp::OpSNegate, - R"(OpSNegate)", - &s_operands[364], - &s_operands[365], - 3, - }, - { - SpirvOp::OpFNegate, - R"(OpFNegate)", - &s_operands[367], - &s_operands[368], - 3, - }, - { - SpirvOp::OpIAdd, - R"(OpIAdd)", - &s_operands[370], - &s_operands[371], - 4, - }, - { - SpirvOp::OpFAdd, - R"(OpFAdd)", - &s_operands[374], - &s_operands[375], - 4, - }, - { - SpirvOp::OpISub, - R"(OpISub)", - &s_operands[378], - &s_operands[379], - 4, - }, - { - SpirvOp::OpFSub, - R"(OpFSub)", - &s_operands[382], - &s_operands[383], - 4, - }, - { - SpirvOp::OpIMul, - R"(OpIMul)", - &s_operands[386], - &s_operands[387], - 4, - }, - { - SpirvOp::OpFMul, - R"(OpFMul)", - &s_operands[390], - &s_operands[391], - 4, - }, - { - SpirvOp::OpUDiv, - R"(OpUDiv)", - &s_operands[394], - &s_operands[395], - 4, - }, - { - SpirvOp::OpSDiv, - R"(OpSDiv)", - &s_operands[398], - &s_operands[399], - 4, - }, - { - SpirvOp::OpFDiv, - R"(OpFDiv)", - &s_operands[402], - &s_operands[403], - 4, - }, - { - SpirvOp::OpUMod, - R"(OpUMod)", - &s_operands[406], - &s_operands[407], - 4, - }, - { - SpirvOp::OpSRem, - R"(OpSRem)", - &s_operands[410], - &s_operands[411], - 4, - }, - { - SpirvOp::OpSMod, - R"(OpSMod)", - &s_operands[414], - &s_operands[415], - 4, - }, - { - SpirvOp::OpFRem, - R"(OpFRem)", - &s_operands[418], - &s_operands[419], - 4, - }, - { - SpirvOp::OpFMod, - R"(OpFMod)", - &s_operands[422], - &s_operands[423], - 4, - }, - { - SpirvOp::OpVectorTimesScalar, - R"(OpVectorTimesScalar)", - &s_operands[426], - &s_operands[427], - 4, - }, - { - SpirvOp::OpMatrixTimesScalar, - R"(OpMatrixTimesScalar)", - &s_operands[430], - &s_operands[431], - 4, - }, - { - SpirvOp::OpVectorTimesMatrix, - R"(OpVectorTimesMatrix)", - &s_operands[434], - &s_operands[435], - 4, - }, - { - SpirvOp::OpMatrixTimesVector, - R"(OpMatrixTimesVector)", - &s_operands[438], - &s_operands[439], - 4, - }, - { - SpirvOp::OpMatrixTimesMatrix, - R"(OpMatrixTimesMatrix)", - &s_operands[442], - &s_operands[443], - 4, - }, - { - SpirvOp::OpOuterProduct, - R"(OpOuterProduct)", - &s_operands[446], - &s_operands[447], - 4, - }, - { - SpirvOp::OpDot, - R"(OpDot)", - &s_operands[450], - &s_operands[451], - 4, - }, - { - SpirvOp::OpIAddCarry, - R"(OpIAddCarry)", - &s_operands[454], - &s_operands[455], - 4, - }, - { - SpirvOp::OpISubBorrow, - R"(OpISubBorrow)", - &s_operands[458], - &s_operands[459], - 4, - }, - { - SpirvOp::OpUMulExtended, - R"(OpUMulExtended)", - &s_operands[462], - &s_operands[463], - 4, - }, - { - SpirvOp::OpSMulExtended, - R"(OpSMulExtended)", - &s_operands[466], - &s_operands[467], - 4, - }, - { - SpirvOp::OpAny, - R"(OpAny)", - &s_operands[470], - &s_operands[471], - 3, - }, - { - SpirvOp::OpAll, - R"(OpAll)", - &s_operands[473], - &s_operands[474], - 3, - }, - { - SpirvOp::OpIsNan, - R"(OpIsNan)", - &s_operands[476], - &s_operands[477], - 3, - }, - { - SpirvOp::OpIsInf, - R"(OpIsInf)", - &s_operands[479], - &s_operands[480], - 3, - }, - { - SpirvOp::OpIsFinite, - R"(OpIsFinite)", - &s_operands[482], - &s_operands[483], - 3, - }, - { - SpirvOp::OpIsNormal, - R"(OpIsNormal)", - &s_operands[485], - &s_operands[486], - 3, - }, - { - SpirvOp::OpSignBitSet, - R"(OpSignBitSet)", - &s_operands[488], - &s_operands[489], - 3, - }, - { - SpirvOp::OpLessOrGreater, - R"(OpLessOrGreater)", - &s_operands[491], - &s_operands[492], - 4, - }, - { - SpirvOp::OpOrdered, - R"(OpOrdered)", - &s_operands[495], - &s_operands[496], - 4, - }, - { - SpirvOp::OpUnordered, - R"(OpUnordered)", - &s_operands[499], - &s_operands[500], - 4, - }, - { - SpirvOp::OpLogicalEqual, - R"(OpLogicalEqual)", - &s_operands[503], - &s_operands[504], - 4, - }, - { - SpirvOp::OpLogicalNotEqual, - R"(OpLogicalNotEqual)", - &s_operands[507], - &s_operands[508], - 4, - }, - { - SpirvOp::OpLogicalOr, - R"(OpLogicalOr)", - &s_operands[511], - &s_operands[512], - 4, - }, - { - SpirvOp::OpLogicalAnd, - R"(OpLogicalAnd)", - &s_operands[515], - &s_operands[516], - 4, - }, - { - SpirvOp::OpLogicalNot, - R"(OpLogicalNot)", - &s_operands[519], - &s_operands[520], - 3, - }, - { - SpirvOp::OpSelect, - R"(OpSelect)", - &s_operands[522], - &s_operands[523], - 5, - }, - { - SpirvOp::OpIEqual, - R"(OpIEqual)", - &s_operands[527], - &s_operands[528], - 4, - }, - { - SpirvOp::OpINotEqual, - R"(OpINotEqual)", - &s_operands[531], - &s_operands[532], - 4, - }, - { - SpirvOp::OpUGreaterThan, - R"(OpUGreaterThan)", - &s_operands[535], - &s_operands[536], - 4, - }, - { - SpirvOp::OpSGreaterThan, - R"(OpSGreaterThan)", - &s_operands[539], - &s_operands[540], - 4, - }, - { - SpirvOp::OpUGreaterThanEqual, - R"(OpUGreaterThanEqual)", - &s_operands[543], - &s_operands[544], - 4, - }, - { - SpirvOp::OpSGreaterThanEqual, - R"(OpSGreaterThanEqual)", - &s_operands[547], - &s_operands[548], - 4, - }, - { - SpirvOp::OpULessThan, - R"(OpULessThan)", - &s_operands[551], - &s_operands[552], - 4, - }, - { - SpirvOp::OpSLessThan, - R"(OpSLessThan)", - &s_operands[555], - &s_operands[556], - 4, - }, - { - SpirvOp::OpULessThanEqual, - R"(OpULessThanEqual)", - &s_operands[559], - &s_operands[560], - 4, - }, - { - SpirvOp::OpSLessThanEqual, - R"(OpSLessThanEqual)", - &s_operands[563], - &s_operands[564], - 4, - }, - { - SpirvOp::OpFOrdEqual, - R"(OpFOrdEqual)", - &s_operands[567], - &s_operands[568], - 4, - }, - { - SpirvOp::OpFUnordEqual, - R"(OpFUnordEqual)", - &s_operands[571], - &s_operands[572], - 4, - }, - { - SpirvOp::OpFOrdNotEqual, - R"(OpFOrdNotEqual)", - &s_operands[575], - &s_operands[576], - 4, - }, - { - SpirvOp::OpFUnordNotEqual, - R"(OpFUnordNotEqual)", - &s_operands[579], - &s_operands[580], - 4, - }, - { - SpirvOp::OpFOrdLessThan, - R"(OpFOrdLessThan)", - &s_operands[583], - &s_operands[584], - 4, - }, - { - SpirvOp::OpFUnordLessThan, - R"(OpFUnordLessThan)", - &s_operands[587], - &s_operands[588], - 4, - }, - { - SpirvOp::OpFOrdGreaterThan, - R"(OpFOrdGreaterThan)", - &s_operands[591], - &s_operands[592], - 4, - }, - { - SpirvOp::OpFUnordGreaterThan, - R"(OpFUnordGreaterThan)", - &s_operands[595], - &s_operands[596], - 4, - }, - { - SpirvOp::OpFOrdLessThanEqual, - R"(OpFOrdLessThanEqual)", - &s_operands[599], - &s_operands[600], - 4, - }, - { - SpirvOp::OpFUnordLessThanEqual, - R"(OpFUnordLessThanEqual)", - &s_operands[603], - &s_operands[604], - 4, - }, - { - SpirvOp::OpFOrdGreaterThanEqual, - R"(OpFOrdGreaterThanEqual)", - &s_operands[607], - &s_operands[608], - 4, - }, - { - SpirvOp::OpFUnordGreaterThanEqual, - R"(OpFUnordGreaterThanEqual)", - &s_operands[611], - &s_operands[612], - 4, - }, - { - SpirvOp::OpShiftRightLogical, - R"(OpShiftRightLogical)", - &s_operands[615], - &s_operands[616], - 4, - }, - { - SpirvOp::OpShiftRightArithmetic, - R"(OpShiftRightArithmetic)", - &s_operands[619], - &s_operands[620], - 4, - }, - { - SpirvOp::OpShiftLeftLogical, - R"(OpShiftLeftLogical)", - &s_operands[623], - &s_operands[624], - 4, - }, - { - SpirvOp::OpBitwiseOr, - R"(OpBitwiseOr)", - &s_operands[627], - &s_operands[628], - 4, - }, - { - SpirvOp::OpBitwiseXor, - R"(OpBitwiseXor)", - &s_operands[631], - &s_operands[632], - 4, - }, - { - SpirvOp::OpBitwiseAnd, - R"(OpBitwiseAnd)", - &s_operands[635], - &s_operands[636], - 4, - }, - { - SpirvOp::OpNot, - R"(OpNot)", - &s_operands[639], - &s_operands[640], - 3, - }, - { - SpirvOp::OpBitFieldInsert, - R"(OpBitFieldInsert)", - &s_operands[642], - &s_operands[643], - 6, - }, - { - SpirvOp::OpBitFieldSExtract, - R"(OpBitFieldSExtract)", - &s_operands[648], - &s_operands[649], - 5, - }, - { - SpirvOp::OpBitFieldUExtract, - R"(OpBitFieldUExtract)", - &s_operands[653], - &s_operands[654], - 5, - }, - { - SpirvOp::OpBitReverse, - R"(OpBitReverse)", - &s_operands[658], - &s_operands[659], - 3, - }, - { - SpirvOp::OpBitCount, - R"(OpBitCount)", - &s_operands[661], - &s_operands[662], - 3, - }, - { - SpirvOp::OpDPdx, - R"(OpDPdx)", - &s_operands[664], - &s_operands[665], - 3, - }, - { - SpirvOp::OpDPdy, - R"(OpDPdy)", - &s_operands[667], - &s_operands[668], - 3, - }, - { - SpirvOp::OpFwidth, - R"(OpFwidth)", - &s_operands[670], - &s_operands[671], - 3, - }, - { - SpirvOp::OpDPdxFine, - R"(OpDPdxFine)", - &s_operands[673], - &s_operands[674], - 3, - }, - { - SpirvOp::OpDPdyFine, - R"(OpDPdyFine)", - &s_operands[676], - &s_operands[677], - 3, - }, - { - SpirvOp::OpFwidthFine, - R"(OpFwidthFine)", - &s_operands[679], - &s_operands[680], - 3, - }, - { - SpirvOp::OpDPdxCoarse, - R"(OpDPdxCoarse)", - &s_operands[682], - &s_operands[683], - 3, - }, - { - SpirvOp::OpDPdyCoarse, - R"(OpDPdyCoarse)", - &s_operands[685], - &s_operands[686], - 3, - }, - { - SpirvOp::OpFwidthCoarse, - R"(OpFwidthCoarse)", - &s_operands[688], - &s_operands[689], - 3, - }, - { - SpirvOp::OpEmitVertex, - R"(OpEmitVertex)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpEndPrimitive, - R"(OpEndPrimitive)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpEmitStreamVertex, - R"(OpEmitStreamVertex)", - &s_operands[691], - nullptr, - 1, - }, - { - SpirvOp::OpEndStreamPrimitive, - R"(OpEndStreamPrimitive)", - &s_operands[692], - nullptr, - 1, - }, - { - SpirvOp::OpControlBarrier, - R"(OpControlBarrier)", - &s_operands[693], - nullptr, - 3, - }, - { - SpirvOp::OpMemoryBarrier, - R"(OpMemoryBarrier)", - &s_operands[696], - nullptr, - 2, - }, - { - SpirvOp::OpAtomicLoad, - R"(OpAtomicLoad)", - &s_operands[698], - &s_operands[699], - 5, - }, - { - SpirvOp::OpAtomicStore, - R"(OpAtomicStore)", - &s_operands[703], - nullptr, - 4, - }, - { - SpirvOp::OpAtomicExchange, - R"(OpAtomicExchange)", - &s_operands[707], - &s_operands[708], - 6, - }, - { - SpirvOp::OpAtomicCompareExchange, - R"(OpAtomicCompareExchange)", - &s_operands[713], - &s_operands[714], - 8, - }, - { - SpirvOp::OpAtomicCompareExchangeWeak, - R"(OpAtomicCompareExchangeWeak)", - &s_operands[721], - &s_operands[722], - 8, - }, - { - SpirvOp::OpAtomicIIncrement, - R"(OpAtomicIIncrement)", - &s_operands[729], - &s_operands[730], - 5, - }, - { - SpirvOp::OpAtomicIDecrement, - R"(OpAtomicIDecrement)", - &s_operands[734], - &s_operands[735], - 5, - }, - { - SpirvOp::OpAtomicIAdd, - R"(OpAtomicIAdd)", - &s_operands[739], - &s_operands[740], - 6, - }, - { - SpirvOp::OpAtomicISub, - R"(OpAtomicISub)", - &s_operands[745], - &s_operands[746], - 6, - }, - { - SpirvOp::OpAtomicSMin, - R"(OpAtomicSMin)", - &s_operands[751], - &s_operands[752], - 6, - }, - { - SpirvOp::OpAtomicUMin, - R"(OpAtomicUMin)", - &s_operands[757], - &s_operands[758], - 6, - }, - { - SpirvOp::OpAtomicSMax, - R"(OpAtomicSMax)", - &s_operands[763], - &s_operands[764], - 6, - }, - { - SpirvOp::OpAtomicUMax, - R"(OpAtomicUMax)", - &s_operands[769], - &s_operands[770], - 6, - }, - { - SpirvOp::OpAtomicAnd, - R"(OpAtomicAnd)", - &s_operands[775], - &s_operands[776], - 6, - }, - { - SpirvOp::OpAtomicOr, - R"(OpAtomicOr)", - &s_operands[781], - &s_operands[782], - 6, - }, - { - SpirvOp::OpAtomicXor, - R"(OpAtomicXor)", - &s_operands[787], - &s_operands[788], - 6, - }, - { - SpirvOp::OpPhi, - R"(OpPhi)", - &s_operands[793], - &s_operands[794], - 3, - }, - { - SpirvOp::OpLoopMerge, - R"(OpLoopMerge)", - &s_operands[796], - nullptr, - 3, - }, - { - SpirvOp::OpSelectionMerge, - R"(OpSelectionMerge)", - &s_operands[799], - nullptr, - 2, - }, - { - SpirvOp::OpLabel, - R"(OpLabel)", - &s_operands[801], - &s_operands[801], - 1, - }, - { - SpirvOp::OpBranch, - R"(OpBranch)", - &s_operands[802], - nullptr, - 1, - }, - { - SpirvOp::OpBranchConditional, - R"(OpBranchConditional)", - &s_operands[803], - nullptr, - 4, - }, - { - SpirvOp::OpSwitch, - R"(OpSwitch)", - &s_operands[807], - nullptr, - 3, - }, - { - SpirvOp::OpKill, - R"(OpKill)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpReturn, - R"(OpReturn)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpReturnValue, - R"(OpReturnValue)", - &s_operands[810], - nullptr, - 1, - }, - { - SpirvOp::OpUnreachable, - R"(OpUnreachable)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpLifetimeStart, - R"(OpLifetimeStart)", - &s_operands[811], - nullptr, - 2, - }, - { - SpirvOp::OpLifetimeStop, - R"(OpLifetimeStop)", - &s_operands[813], - nullptr, - 2, - }, - { - SpirvOp::OpGroupAsyncCopy, - R"(OpGroupAsyncCopy)", - &s_operands[815], - &s_operands[816], - 8, - }, - { - SpirvOp::OpGroupWaitEvents, - R"(OpGroupWaitEvents)", - &s_operands[823], - nullptr, - 3, - }, - { - SpirvOp::OpGroupAll, - R"(OpGroupAll)", - &s_operands[826], - &s_operands[827], - 4, - }, - { - SpirvOp::OpGroupAny, - R"(OpGroupAny)", - &s_operands[830], - &s_operands[831], - 4, - }, - { - SpirvOp::OpGroupBroadcast, - R"(OpGroupBroadcast)", - &s_operands[834], - &s_operands[835], - 5, - }, - { - SpirvOp::OpGroupIAdd, - R"(OpGroupIAdd)", - &s_operands[839], - &s_operands[840], - 5, - }, - { - SpirvOp::OpGroupFAdd, - R"(OpGroupFAdd)", - &s_operands[844], - &s_operands[845], - 5, - }, - { - SpirvOp::OpGroupFMin, - R"(OpGroupFMin)", - &s_operands[849], - &s_operands[850], - 5, - }, - { - SpirvOp::OpGroupUMin, - R"(OpGroupUMin)", - &s_operands[854], - &s_operands[855], - 5, - }, - { - SpirvOp::OpGroupSMin, - R"(OpGroupSMin)", - &s_operands[859], - &s_operands[860], - 5, - }, - { - SpirvOp::OpGroupFMax, - R"(OpGroupFMax)", - &s_operands[864], - &s_operands[865], - 5, - }, - { - SpirvOp::OpGroupUMax, - R"(OpGroupUMax)", - &s_operands[869], - &s_operands[870], - 5, - }, - { - SpirvOp::OpGroupSMax, - R"(OpGroupSMax)", - &s_operands[874], - &s_operands[875], - 5, - }, - { - SpirvOp::OpReadPipe, - R"(OpReadPipe)", - &s_operands[879], - &s_operands[880], - 6, - }, - { - SpirvOp::OpWritePipe, - R"(OpWritePipe)", - &s_operands[885], - &s_operands[886], - 6, - }, - { - SpirvOp::OpReservedReadPipe, - R"(OpReservedReadPipe)", - &s_operands[891], - &s_operands[892], - 8, - }, - { - SpirvOp::OpReservedWritePipe, - R"(OpReservedWritePipe)", - &s_operands[899], - &s_operands[900], - 8, - }, - { - SpirvOp::OpReserveReadPipePackets, - R"(OpReserveReadPipePackets)", - &s_operands[907], - &s_operands[908], - 6, - }, - { - SpirvOp::OpReserveWritePipePackets, - R"(OpReserveWritePipePackets)", - &s_operands[913], - &s_operands[914], - 6, - }, - { - SpirvOp::OpCommitReadPipe, - R"(OpCommitReadPipe)", - &s_operands[919], - nullptr, - 4, - }, - { - SpirvOp::OpCommitWritePipe, - R"(OpCommitWritePipe)", - &s_operands[923], - nullptr, - 4, - }, - { - SpirvOp::OpIsValidReserveId, - R"(OpIsValidReserveId)", - &s_operands[927], - &s_operands[928], - 3, - }, - { - SpirvOp::OpGetNumPipePackets, - R"(OpGetNumPipePackets)", - &s_operands[930], - &s_operands[931], - 5, - }, - { - SpirvOp::OpGetMaxPipePackets, - R"(OpGetMaxPipePackets)", - &s_operands[935], - &s_operands[936], - 5, - }, - { - SpirvOp::OpGroupReserveReadPipePackets, - R"(OpGroupReserveReadPipePackets)", - &s_operands[940], - &s_operands[941], - 7, - }, - { - SpirvOp::OpGroupReserveWritePipePackets, - R"(OpGroupReserveWritePipePackets)", - &s_operands[947], - &s_operands[948], - 7, - }, - { - SpirvOp::OpGroupCommitReadPipe, - R"(OpGroupCommitReadPipe)", - &s_operands[954], - nullptr, - 5, - }, - { - SpirvOp::OpGroupCommitWritePipe, - R"(OpGroupCommitWritePipe)", - &s_operands[959], - nullptr, - 5, - }, - { - SpirvOp::OpEnqueueMarker, - R"(OpEnqueueMarker)", - &s_operands[964], - &s_operands[965], - 6, - }, - { - SpirvOp::OpEnqueueKernel, - R"(OpEnqueueKernel)", - &s_operands[970], - &s_operands[971], - 13, - }, - { - SpirvOp::OpGetKernelNDrangeSubGroupCount, - R"(OpGetKernelNDrangeSubGroupCount)", - &s_operands[983], - &s_operands[984], - 7, - }, - { - SpirvOp::OpGetKernelNDrangeMaxSubGroupSize, - R"(OpGetKernelNDrangeMaxSubGroupSize)", - &s_operands[990], - &s_operands[991], - 7, - }, - { - SpirvOp::OpGetKernelWorkGroupSize, - R"(OpGetKernelWorkGroupSize)", - &s_operands[997], - &s_operands[998], - 6, - }, - { - SpirvOp::OpGetKernelPreferredWorkGroupSizeMultiple, - R"(OpGetKernelPreferredWorkGroupSizeMultiple)", - &s_operands[1003], - &s_operands[1004], - 6, - }, - { - SpirvOp::OpRetainEvent, - R"(OpRetainEvent)", - &s_operands[1009], - nullptr, - 1, - }, - { - SpirvOp::OpReleaseEvent, - R"(OpReleaseEvent)", - &s_operands[1010], - nullptr, - 1, - }, - { - SpirvOp::OpCreateUserEvent, - R"(OpCreateUserEvent)", - &s_operands[1011], - &s_operands[1012], - 2, - }, - { - SpirvOp::OpIsValidEvent, - R"(OpIsValidEvent)", - &s_operands[1013], - &s_operands[1014], - 3, - }, - { - SpirvOp::OpSetUserEventStatus, - R"(OpSetUserEventStatus)", - &s_operands[1016], - nullptr, - 2, - }, - { - SpirvOp::OpCaptureEventProfilingInfo, - R"(OpCaptureEventProfilingInfo)", - &s_operands[1018], - nullptr, - 3, - }, - { - SpirvOp::OpGetDefaultQueue, - R"(OpGetDefaultQueue)", - &s_operands[1021], - &s_operands[1022], - 2, - }, - { - SpirvOp::OpBuildNDRange, - R"(OpBuildNDRange)", - &s_operands[1023], - &s_operands[1024], - 5, - }, - { - SpirvOp::OpImageSparseSampleImplicitLod, - R"(OpImageSparseSampleImplicitLod)", - &s_operands[1028], - &s_operands[1029], - 5, - }, - { - SpirvOp::OpImageSparseSampleExplicitLod, - R"(OpImageSparseSampleExplicitLod)", - &s_operands[1033], - &s_operands[1034], - 5, - }, - { - SpirvOp::OpImageSparseSampleDrefImplicitLod, - R"(OpImageSparseSampleDrefImplicitLod)", - &s_operands[1038], - &s_operands[1039], - 6, - }, - { - SpirvOp::OpImageSparseSampleDrefExplicitLod, - R"(OpImageSparseSampleDrefExplicitLod)", - &s_operands[1044], - &s_operands[1045], - 6, - }, - { - SpirvOp::OpImageSparseSampleProjImplicitLod, - R"(OpImageSparseSampleProjImplicitLod)", - &s_operands[1050], - &s_operands[1051], - 5, - }, - { - SpirvOp::OpImageSparseSampleProjExplicitLod, - R"(OpImageSparseSampleProjExplicitLod)", - &s_operands[1055], - &s_operands[1056], - 5, - }, - { - SpirvOp::OpImageSparseSampleProjDrefImplicitLod, - R"(OpImageSparseSampleProjDrefImplicitLod)", - &s_operands[1060], - &s_operands[1061], - 6, - }, - { - SpirvOp::OpImageSparseSampleProjDrefExplicitLod, - R"(OpImageSparseSampleProjDrefExplicitLod)", - &s_operands[1066], - &s_operands[1067], - 6, - }, - { - SpirvOp::OpImageSparseFetch, - R"(OpImageSparseFetch)", - &s_operands[1072], - &s_operands[1073], - 5, - }, - { - SpirvOp::OpImageSparseGather, - R"(OpImageSparseGather)", - &s_operands[1077], - &s_operands[1078], - 6, - }, - { - SpirvOp::OpImageSparseDrefGather, - R"(OpImageSparseDrefGather)", - &s_operands[1083], - &s_operands[1084], - 6, - }, - { - SpirvOp::OpImageSparseTexelsResident, - R"(OpImageSparseTexelsResident)", - &s_operands[1089], - &s_operands[1090], - 3, - }, - { - SpirvOp::OpNoLine, - R"(OpNoLine)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpAtomicFlagTestAndSet, - R"(OpAtomicFlagTestAndSet)", - &s_operands[1092], - &s_operands[1093], - 5, - }, - { - SpirvOp::OpAtomicFlagClear, - R"(OpAtomicFlagClear)", - &s_operands[1097], - nullptr, - 3, - }, - { - SpirvOp::OpImageSparseRead, - R"(OpImageSparseRead)", - &s_operands[1100], - &s_operands[1101], - 5, - }, - { - SpirvOp::OpSizeOf, - R"(OpSizeOf)", - &s_operands[1105], - &s_operands[1106], - 3, - }, - { - SpirvOp::OpTypePipeStorage, - R"(OpTypePipeStorage)", - &s_operands[1108], - &s_operands[1108], - 1, - }, - { - SpirvOp::OpConstantPipeStorage, - R"(OpConstantPipeStorage)", - &s_operands[1109], - &s_operands[1110], - 5, - }, - { - SpirvOp::OpCreatePipeFromPipeStorage, - R"(OpCreatePipeFromPipeStorage)", - &s_operands[1114], - &s_operands[1115], - 3, - }, - { - SpirvOp::OpGetKernelLocalSizeForSubgroupCount, - R"(OpGetKernelLocalSizeForSubgroupCount)", - &s_operands[1117], - &s_operands[1118], - 7, - }, - { - SpirvOp::OpGetKernelMaxNumSubgroups, - R"(OpGetKernelMaxNumSubgroups)", - &s_operands[1124], - &s_operands[1125], - 6, - }, - { - SpirvOp::OpTypeNamedBarrier, - R"(OpTypeNamedBarrier)", - &s_operands[1130], - &s_operands[1130], - 1, - }, - { - SpirvOp::OpNamedBarrierInitialize, - R"(OpNamedBarrierInitialize)", - &s_operands[1131], - &s_operands[1132], - 3, - }, - { - SpirvOp::OpMemoryNamedBarrier, - R"(OpMemoryNamedBarrier)", - &s_operands[1134], - nullptr, - 3, - }, - { - SpirvOp::OpModuleProcessed, - R"(OpModuleProcessed)", - &s_operands[1137], - nullptr, - 1, - }, - { - SpirvOp::OpExecutionModeId, - R"(OpExecutionModeId)", - &s_operands[1138], - nullptr, - 2, - }, - { - SpirvOp::OpDecorateId, - R"(OpDecorateId)", - &s_operands[1140], - nullptr, - 2, - }, - { - SpirvOp::OpGroupNonUniformElect, - R"(OpGroupNonUniformElect)", - &s_operands[1142], - &s_operands[1143], - 3, - }, - { - SpirvOp::OpGroupNonUniformAll, - R"(OpGroupNonUniformAll)", - &s_operands[1145], - &s_operands[1146], - 4, - }, - { - SpirvOp::OpGroupNonUniformAny, - R"(OpGroupNonUniformAny)", - &s_operands[1149], - &s_operands[1150], - 4, - }, - { - SpirvOp::OpGroupNonUniformAllEqual, - R"(OpGroupNonUniformAllEqual)", - &s_operands[1153], - &s_operands[1154], - 4, - }, - { - SpirvOp::OpGroupNonUniformBroadcast, - R"(OpGroupNonUniformBroadcast)", - &s_operands[1157], - &s_operands[1158], - 5, - }, - { - SpirvOp::OpGroupNonUniformBroadcastFirst, - R"(OpGroupNonUniformBroadcastFirst)", - &s_operands[1162], - &s_operands[1163], - 4, - }, - { - SpirvOp::OpGroupNonUniformBallot, - R"(OpGroupNonUniformBallot)", - &s_operands[1166], - &s_operands[1167], - 4, - }, - { - SpirvOp::OpGroupNonUniformInverseBallot, - R"(OpGroupNonUniformInverseBallot)", - &s_operands[1170], - &s_operands[1171], - 4, - }, - { - SpirvOp::OpGroupNonUniformBallotBitExtract, - R"(OpGroupNonUniformBallotBitExtract)", - &s_operands[1174], - &s_operands[1175], - 5, - }, - { - SpirvOp::OpGroupNonUniformBallotBitCount, - R"(OpGroupNonUniformBallotBitCount)", - &s_operands[1179], - &s_operands[1180], - 5, - }, - { - SpirvOp::OpGroupNonUniformBallotFindLSB, - R"(OpGroupNonUniformBallotFindLSB)", - &s_operands[1184], - &s_operands[1185], - 4, - }, - { - SpirvOp::OpGroupNonUniformBallotFindMSB, - R"(OpGroupNonUniformBallotFindMSB)", - &s_operands[1188], - &s_operands[1189], - 4, - }, - { - SpirvOp::OpGroupNonUniformShuffle, - R"(OpGroupNonUniformShuffle)", - &s_operands[1192], - &s_operands[1193], - 5, - }, - { - SpirvOp::OpGroupNonUniformShuffleXor, - R"(OpGroupNonUniformShuffleXor)", - &s_operands[1197], - &s_operands[1198], - 5, - }, - { - SpirvOp::OpGroupNonUniformShuffleUp, - R"(OpGroupNonUniformShuffleUp)", - &s_operands[1202], - &s_operands[1203], - 5, - }, - { - SpirvOp::OpGroupNonUniformShuffleDown, - R"(OpGroupNonUniformShuffleDown)", - &s_operands[1207], - &s_operands[1208], - 5, - }, - { - SpirvOp::OpGroupNonUniformIAdd, - R"(OpGroupNonUniformIAdd)", - &s_operands[1212], - &s_operands[1213], - 6, - }, - { - SpirvOp::OpGroupNonUniformFAdd, - R"(OpGroupNonUniformFAdd)", - &s_operands[1218], - &s_operands[1219], - 6, - }, - { - SpirvOp::OpGroupNonUniformIMul, - R"(OpGroupNonUniformIMul)", - &s_operands[1224], - &s_operands[1225], - 6, - }, - { - SpirvOp::OpGroupNonUniformFMul, - R"(OpGroupNonUniformFMul)", - &s_operands[1230], - &s_operands[1231], - 6, - }, - { - SpirvOp::OpGroupNonUniformSMin, - R"(OpGroupNonUniformSMin)", - &s_operands[1236], - &s_operands[1237], - 6, - }, - { - SpirvOp::OpGroupNonUniformUMin, - R"(OpGroupNonUniformUMin)", - &s_operands[1242], - &s_operands[1243], - 6, - }, - { - SpirvOp::OpGroupNonUniformFMin, - R"(OpGroupNonUniformFMin)", - &s_operands[1248], - &s_operands[1249], - 6, - }, - { - SpirvOp::OpGroupNonUniformSMax, - R"(OpGroupNonUniformSMax)", - &s_operands[1254], - &s_operands[1255], - 6, - }, - { - SpirvOp::OpGroupNonUniformUMax, - R"(OpGroupNonUniformUMax)", - &s_operands[1260], - &s_operands[1261], - 6, - }, - { - SpirvOp::OpGroupNonUniformFMax, - R"(OpGroupNonUniformFMax)", - &s_operands[1266], - &s_operands[1267], - 6, - }, - { - SpirvOp::OpGroupNonUniformBitwiseAnd, - R"(OpGroupNonUniformBitwiseAnd)", - &s_operands[1272], - &s_operands[1273], - 6, - }, - { - SpirvOp::OpGroupNonUniformBitwiseOr, - R"(OpGroupNonUniformBitwiseOr)", - &s_operands[1278], - &s_operands[1279], - 6, - }, - { - SpirvOp::OpGroupNonUniformBitwiseXor, - R"(OpGroupNonUniformBitwiseXor)", - &s_operands[1284], - &s_operands[1285], - 6, - }, - { - SpirvOp::OpGroupNonUniformLogicalAnd, - R"(OpGroupNonUniformLogicalAnd)", - &s_operands[1290], - &s_operands[1291], - 6, - }, - { - SpirvOp::OpGroupNonUniformLogicalOr, - R"(OpGroupNonUniformLogicalOr)", - &s_operands[1296], - &s_operands[1297], - 6, - }, - { - SpirvOp::OpGroupNonUniformLogicalXor, - R"(OpGroupNonUniformLogicalXor)", - &s_operands[1302], - &s_operands[1303], - 6, - }, - { - SpirvOp::OpGroupNonUniformQuadBroadcast, - R"(OpGroupNonUniformQuadBroadcast)", - &s_operands[1308], - &s_operands[1309], - 5, - }, - { - SpirvOp::OpGroupNonUniformQuadSwap, - R"(OpGroupNonUniformQuadSwap)", - &s_operands[1313], - &s_operands[1314], - 5, - }, - { - SpirvOp::OpCopyLogical, - R"(OpCopyLogical)", - &s_operands[1318], - &s_operands[1319], - 3, - }, - { - SpirvOp::OpPtrEqual, - R"(OpPtrEqual)", - &s_operands[1321], - &s_operands[1322], - 4, - }, - { - SpirvOp::OpPtrNotEqual, - R"(OpPtrNotEqual)", - &s_operands[1325], - &s_operands[1326], - 4, - }, - { - SpirvOp::OpPtrDiff, - R"(OpPtrDiff)", - &s_operands[1329], - &s_operands[1330], - 4, - }, - { - SpirvOp::OpTerminateInvocation, - R"(OpTerminateInvocation)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpSubgroupBallotKHR, - R"(OpSubgroupBallotKHR)", - &s_operands[1333], - &s_operands[1334], - 3, - }, - { - SpirvOp::OpSubgroupFirstInvocationKHR, - R"(OpSubgroupFirstInvocationKHR)", - &s_operands[1336], - &s_operands[1337], - 3, - }, - { - SpirvOp::OpSubgroupAllKHR, - R"(OpSubgroupAllKHR)", - &s_operands[1339], - &s_operands[1340], - 3, - }, - { - SpirvOp::OpSubgroupAnyKHR, - R"(OpSubgroupAnyKHR)", - &s_operands[1342], - &s_operands[1343], - 3, - }, - { - SpirvOp::OpSubgroupAllEqualKHR, - R"(OpSubgroupAllEqualKHR)", - &s_operands[1345], - &s_operands[1346], - 3, - }, - { - SpirvOp::OpGroupNonUniformRotateKHR, - R"(OpGroupNonUniformRotateKHR)", - &s_operands[1348], - &s_operands[1349], - 6, - }, - { - SpirvOp::OpSubgroupReadInvocationKHR, - R"(OpSubgroupReadInvocationKHR)", - &s_operands[1354], - &s_operands[1355], - 4, - }, - { - SpirvOp::OpTraceRayKHR, - R"(OpTraceRayKHR)", - &s_operands[1358], - nullptr, - 11, - }, - { - SpirvOp::OpExecuteCallableKHR, - R"(OpExecuteCallableKHR)", - &s_operands[1369], - nullptr, - 2, - }, - { - SpirvOp::OpConvertUToAccelerationStructureKHR, - R"(OpConvertUToAccelerationStructureKHR)", - &s_operands[1371], - &s_operands[1372], - 3, - }, - { - SpirvOp::OpIgnoreIntersectionKHR, - R"(OpIgnoreIntersectionKHR)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpTerminateRayKHR, - R"(OpTerminateRayKHR)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpSDotKHR, - R"(OpSDotKHR)", - &s_operands[1374], - &s_operands[1375], - 5, - }, - { - SpirvOp::OpUDotKHR, - R"(OpUDotKHR)", - &s_operands[1379], - &s_operands[1380], - 5, - }, - { - SpirvOp::OpSUDotKHR, - R"(OpSUDotKHR)", - &s_operands[1384], - &s_operands[1385], - 5, - }, - { - SpirvOp::OpSDotAccSatKHR, - R"(OpSDotAccSatKHR)", - &s_operands[1389], - &s_operands[1390], - 6, - }, - { - SpirvOp::OpUDotAccSatKHR, - R"(OpUDotAccSatKHR)", - &s_operands[1395], - &s_operands[1396], - 6, - }, - { - SpirvOp::OpSUDotAccSatKHR, - R"(OpSUDotAccSatKHR)", - &s_operands[1401], - &s_operands[1402], - 6, - }, - { - SpirvOp::OpTypeRayQueryKHR, - R"(OpTypeRayQueryKHR)", - &s_operands[1407], - &s_operands[1407], - 1, - }, - { - SpirvOp::OpRayQueryInitializeKHR, - R"(OpRayQueryInitializeKHR)", - &s_operands[1408], - nullptr, - 8, - }, - { - SpirvOp::OpRayQueryTerminateKHR, - R"(OpRayQueryTerminateKHR)", - &s_operands[1416], - nullptr, - 1, - }, - { - SpirvOp::OpRayQueryGenerateIntersectionKHR, - R"(OpRayQueryGenerateIntersectionKHR)", - &s_operands[1417], - nullptr, - 2, - }, - { - SpirvOp::OpRayQueryConfirmIntersectionKHR, - R"(OpRayQueryConfirmIntersectionKHR)", - &s_operands[1419], - nullptr, - 1, - }, - { - SpirvOp::OpRayQueryProceedKHR, - R"(OpRayQueryProceedKHR)", - &s_operands[1420], - &s_operands[1421], - 3, - }, - { - SpirvOp::OpRayQueryGetIntersectionTypeKHR, - R"(OpRayQueryGetIntersectionTypeKHR)", - &s_operands[1423], - &s_operands[1424], - 4, - }, - { - SpirvOp::OpGroupIAddNonUniformAMD, - R"(OpGroupIAddNonUniformAMD)", - &s_operands[1427], - &s_operands[1428], - 5, - }, - { - SpirvOp::OpGroupFAddNonUniformAMD, - R"(OpGroupFAddNonUniformAMD)", - &s_operands[1432], - &s_operands[1433], - 5, - }, - { - SpirvOp::OpGroupFMinNonUniformAMD, - R"(OpGroupFMinNonUniformAMD)", - &s_operands[1437], - &s_operands[1438], - 5, - }, - { - SpirvOp::OpGroupUMinNonUniformAMD, - R"(OpGroupUMinNonUniformAMD)", - &s_operands[1442], - &s_operands[1443], - 5, - }, - { - SpirvOp::OpGroupSMinNonUniformAMD, - R"(OpGroupSMinNonUniformAMD)", - &s_operands[1447], - &s_operands[1448], - 5, - }, - { - SpirvOp::OpGroupFMaxNonUniformAMD, - R"(OpGroupFMaxNonUniformAMD)", - &s_operands[1452], - &s_operands[1453], - 5, - }, - { - SpirvOp::OpGroupUMaxNonUniformAMD, - R"(OpGroupUMaxNonUniformAMD)", - &s_operands[1457], - &s_operands[1458], - 5, - }, - { - SpirvOp::OpGroupSMaxNonUniformAMD, - R"(OpGroupSMaxNonUniformAMD)", - &s_operands[1462], - &s_operands[1463], - 5, - }, - { - SpirvOp::OpFragmentMaskFetchAMD, - R"(OpFragmentMaskFetchAMD)", - &s_operands[1467], - &s_operands[1468], - 4, - }, - { - SpirvOp::OpFragmentFetchAMD, - R"(OpFragmentFetchAMD)", - &s_operands[1471], - &s_operands[1472], - 5, - }, - { - SpirvOp::OpReadClockKHR, - R"(OpReadClockKHR)", - &s_operands[1476], - &s_operands[1477], - 3, - }, - { - SpirvOp::OpImageSampleFootprintNV, - R"(OpImageSampleFootprintNV)", - &s_operands[1479], - &s_operands[1480], - 7, - }, - { - SpirvOp::OpGroupNonUniformPartitionNV, - R"(OpGroupNonUniformPartitionNV)", - &s_operands[1486], - &s_operands[1487], - 3, - }, - { - SpirvOp::OpWritePackedPrimitiveIndices4x8NV, - R"(OpWritePackedPrimitiveIndices4x8NV)", - &s_operands[1489], - nullptr, - 2, - }, - { - SpirvOp::OpReportIntersectionKHR, - R"(OpReportIntersectionKHR)", - &s_operands[1491], - &s_operands[1492], - 4, - }, - { - SpirvOp::OpIgnoreIntersectionNV, - R"(OpIgnoreIntersectionNV)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpTerminateRayNV, - R"(OpTerminateRayNV)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpTraceNV, - R"(OpTraceNV)", - &s_operands[1495], - nullptr, - 11, - }, - { - SpirvOp::OpTraceMotionNV, - R"(OpTraceMotionNV)", - &s_operands[1506], - nullptr, - 12, - }, - { - SpirvOp::OpTraceRayMotionNV, - R"(OpTraceRayMotionNV)", - &s_operands[1518], - nullptr, - 12, - }, - { - SpirvOp::OpTypeAccelerationStructureKHR, - R"(OpTypeAccelerationStructureKHR)", - &s_operands[1530], - &s_operands[1530], - 1, - }, - { - SpirvOp::OpExecuteCallableNV, - R"(OpExecuteCallableNV)", - &s_operands[1531], - nullptr, - 2, - }, - { - SpirvOp::OpTypeCooperativeMatrixNV, - R"(OpTypeCooperativeMatrixNV)", - &s_operands[1533], - &s_operands[1533], - 5, - }, - { - SpirvOp::OpCooperativeMatrixLoadNV, - R"(OpCooperativeMatrixLoadNV)", - &s_operands[1538], - &s_operands[1539], - 6, - }, - { - SpirvOp::OpCooperativeMatrixStoreNV, - R"(OpCooperativeMatrixStoreNV)", - &s_operands[1544], - nullptr, - 5, - }, - { - SpirvOp::OpCooperativeMatrixMulAddNV, - R"(OpCooperativeMatrixMulAddNV)", - &s_operands[1549], - &s_operands[1550], - 5, - }, - { - SpirvOp::OpCooperativeMatrixLengthNV, - R"(OpCooperativeMatrixLengthNV)", - &s_operands[1554], - &s_operands[1555], - 3, - }, - { - SpirvOp::OpBeginInvocationInterlockEXT, - R"(OpBeginInvocationInterlockEXT)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpEndInvocationInterlockEXT, - R"(OpEndInvocationInterlockEXT)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpDemoteToHelperInvocationEXT, - R"(OpDemoteToHelperInvocationEXT)", - nullptr, - nullptr, - 0, - }, - { - SpirvOp::OpIsHelperInvocationEXT, - R"(OpIsHelperInvocationEXT)", - &s_operands[1557], - &s_operands[1558], - 2, - }, - { - SpirvOp::OpConvertUToImageNV, - R"(OpConvertUToImageNV)", - &s_operands[1559], - &s_operands[1560], - 3, - }, - { - SpirvOp::OpConvertUToSamplerNV, - R"(OpConvertUToSamplerNV)", - &s_operands[1562], - &s_operands[1563], - 3, - }, - { - SpirvOp::OpConvertImageToUNV, - R"(OpConvertImageToUNV)", - &s_operands[1565], - &s_operands[1566], - 3, - }, - { - SpirvOp::OpConvertSamplerToUNV, - R"(OpConvertSamplerToUNV)", - &s_operands[1568], - &s_operands[1569], - 3, - }, - { - SpirvOp::OpConvertUToSampledImageNV, - R"(OpConvertUToSampledImageNV)", - &s_operands[1571], - &s_operands[1572], - 3, - }, - { - SpirvOp::OpConvertSampledImageToUNV, - R"(OpConvertSampledImageToUNV)", - &s_operands[1574], - &s_operands[1575], - 3, - }, - { - SpirvOp::OpSamplerImageAddressingModeNV, - R"(OpSamplerImageAddressingModeNV)", - &s_operands[1577], - nullptr, - 1, - }, - { - SpirvOp::OpSubgroupShuffleINTEL, - R"(OpSubgroupShuffleINTEL)", - &s_operands[1578], - &s_operands[1579], - 4, - }, - { - SpirvOp::OpSubgroupShuffleDownINTEL, - R"(OpSubgroupShuffleDownINTEL)", - &s_operands[1582], - &s_operands[1583], - 5, - }, - { - SpirvOp::OpSubgroupShuffleUpINTEL, - R"(OpSubgroupShuffleUpINTEL)", - &s_operands[1587], - &s_operands[1588], - 5, - }, - { - SpirvOp::OpSubgroupShuffleXorINTEL, - R"(OpSubgroupShuffleXorINTEL)", - &s_operands[1592], - &s_operands[1593], - 4, - }, - { - SpirvOp::OpSubgroupBlockReadINTEL, - R"(OpSubgroupBlockReadINTEL)", - &s_operands[1596], - &s_operands[1597], - 3, - }, - { - SpirvOp::OpSubgroupBlockWriteINTEL, - R"(OpSubgroupBlockWriteINTEL)", - &s_operands[1599], - nullptr, - 2, - }, - { - SpirvOp::OpSubgroupImageBlockReadINTEL, - R"(OpSubgroupImageBlockReadINTEL)", - &s_operands[1601], - &s_operands[1602], - 4, - }, - { - SpirvOp::OpSubgroupImageBlockWriteINTEL, - R"(OpSubgroupImageBlockWriteINTEL)", - &s_operands[1605], - nullptr, - 3, - }, - { - SpirvOp::OpSubgroupImageMediaBlockReadINTEL, - R"(OpSubgroupImageMediaBlockReadINTEL)", - &s_operands[1608], - &s_operands[1609], - 6, - }, - { - SpirvOp::OpSubgroupImageMediaBlockWriteINTEL, - R"(OpSubgroupImageMediaBlockWriteINTEL)", - &s_operands[1614], - nullptr, - 5, - }, - { - SpirvOp::OpUCountLeadingZerosINTEL, - R"(OpUCountLeadingZerosINTEL)", - &s_operands[1619], - &s_operands[1620], - 3, - }, - { - SpirvOp::OpUCountTrailingZerosINTEL, - R"(OpUCountTrailingZerosINTEL)", - &s_operands[1622], - &s_operands[1623], - 3, - }, - { - SpirvOp::OpAbsISubINTEL, - R"(OpAbsISubINTEL)", - &s_operands[1625], - &s_operands[1626], - 4, - }, - { - SpirvOp::OpAbsUSubINTEL, - R"(OpAbsUSubINTEL)", - &s_operands[1629], - &s_operands[1630], - 4, - }, - { - SpirvOp::OpIAddSatINTEL, - R"(OpIAddSatINTEL)", - &s_operands[1633], - &s_operands[1634], - 4, - }, - { - SpirvOp::OpUAddSatINTEL, - R"(OpUAddSatINTEL)", - &s_operands[1637], - &s_operands[1638], - 4, - }, - { - SpirvOp::OpIAverageINTEL, - R"(OpIAverageINTEL)", - &s_operands[1641], - &s_operands[1642], - 4, - }, - { - SpirvOp::OpUAverageINTEL, - R"(OpUAverageINTEL)", - &s_operands[1645], - &s_operands[1646], - 4, - }, - { - SpirvOp::OpIAverageRoundedINTEL, - R"(OpIAverageRoundedINTEL)", - &s_operands[1649], - &s_operands[1650], - 4, - }, - { - SpirvOp::OpUAverageRoundedINTEL, - R"(OpUAverageRoundedINTEL)", - &s_operands[1653], - &s_operands[1654], - 4, - }, - { - SpirvOp::OpISubSatINTEL, - R"(OpISubSatINTEL)", - &s_operands[1657], - &s_operands[1658], - 4, - }, - { - SpirvOp::OpUSubSatINTEL, - R"(OpUSubSatINTEL)", - &s_operands[1661], - &s_operands[1662], - 4, - }, - { - SpirvOp::OpIMul32x16INTEL, - R"(OpIMul32x16INTEL)", - &s_operands[1665], - &s_operands[1666], - 4, - }, - { - SpirvOp::OpUMul32x16INTEL, - R"(OpUMul32x16INTEL)", - &s_operands[1669], - &s_operands[1670], - 4, - }, - { - SpirvOp::OpConstantFunctionPointerINTEL, - R"(OpConstantFunctionPointerINTEL)", - &s_operands[1673], - &s_operands[1674], - 3, - }, - { - SpirvOp::OpFunctionPointerCallINTEL, - R"(OpFunctionPointerCallINTEL)", - &s_operands[1676], - &s_operands[1677], - 3, - }, - { - SpirvOp::OpAsmTargetINTEL, - R"(OpAsmTargetINTEL)", - &s_operands[1679], - &s_operands[1680], - 3, - }, - { - SpirvOp::OpAsmINTEL, - R"(OpAsmINTEL)", - &s_operands[1682], - &s_operands[1683], - 6, - }, - { - SpirvOp::OpAsmCallINTEL, - R"(OpAsmCallINTEL)", - &s_operands[1688], - &s_operands[1689], - 4, - }, - { - SpirvOp::OpAtomicFMinEXT, - R"(OpAtomicFMinEXT)", - &s_operands[1692], - &s_operands[1693], - 6, - }, - { - SpirvOp::OpAtomicFMaxEXT, - R"(OpAtomicFMaxEXT)", - &s_operands[1698], - &s_operands[1699], - 6, - }, - { - SpirvOp::OpAssumeTrueKHR, - R"(OpAssumeTrueKHR)", - &s_operands[1704], - nullptr, - 1, - }, - { - SpirvOp::OpExpectKHR, - R"(OpExpectKHR)", - &s_operands[1705], - &s_operands[1706], - 4, - }, - { - SpirvOp::OpDecorateStringGOOGLE, - R"(OpDecorateStringGOOGLE)", - &s_operands[1709], - nullptr, - 2, - }, - { - SpirvOp::OpMemberDecorateStringGOOGLE, - R"(OpMemberDecorateStringGOOGLE)", - &s_operands[1711], - nullptr, - 3, - }, - { - SpirvOp::OpVmeImageINTEL, - R"(OpVmeImageINTEL)", - &s_operands[1714], - &s_operands[1715], - 4, - }, - { - SpirvOp::OpTypeVmeImageINTEL, - R"(OpTypeVmeImageINTEL)", - &s_operands[1718], - &s_operands[1718], - 2, - }, - { - SpirvOp::OpTypeAvcImePayloadINTEL, - R"(OpTypeAvcImePayloadINTEL)", - &s_operands[1720], - &s_operands[1720], - 1, - }, - { - SpirvOp::OpTypeAvcRefPayloadINTEL, - R"(OpTypeAvcRefPayloadINTEL)", - &s_operands[1721], - &s_operands[1721], - 1, - }, - { - SpirvOp::OpTypeAvcSicPayloadINTEL, - R"(OpTypeAvcSicPayloadINTEL)", - &s_operands[1722], - &s_operands[1722], - 1, - }, - { - SpirvOp::OpTypeAvcMcePayloadINTEL, - R"(OpTypeAvcMcePayloadINTEL)", - &s_operands[1723], - &s_operands[1723], - 1, - }, - { - SpirvOp::OpTypeAvcMceResultINTEL, - R"(OpTypeAvcMceResultINTEL)", - &s_operands[1724], - &s_operands[1724], - 1, - }, - { - SpirvOp::OpTypeAvcImeResultINTEL, - R"(OpTypeAvcImeResultINTEL)", - &s_operands[1725], - &s_operands[1725], - 1, - }, - { - SpirvOp::OpTypeAvcImeResultSingleReferenceStreamoutINTEL, - R"(OpTypeAvcImeResultSingleReferenceStreamoutINTEL)", - &s_operands[1726], - &s_operands[1726], - 1, - }, - { - SpirvOp::OpTypeAvcImeResultDualReferenceStreamoutINTEL, - R"(OpTypeAvcImeResultDualReferenceStreamoutINTEL)", - &s_operands[1727], - &s_operands[1727], - 1, - }, - { - SpirvOp::OpTypeAvcImeSingleReferenceStreaminINTEL, - R"(OpTypeAvcImeSingleReferenceStreaminINTEL)", - &s_operands[1728], - &s_operands[1728], - 1, - }, - { - SpirvOp::OpTypeAvcImeDualReferenceStreaminINTEL, - R"(OpTypeAvcImeDualReferenceStreaminINTEL)", - &s_operands[1729], - &s_operands[1729], - 1, - }, - { - SpirvOp::OpTypeAvcRefResultINTEL, - R"(OpTypeAvcRefResultINTEL)", - &s_operands[1730], - &s_operands[1730], - 1, - }, - { - SpirvOp::OpTypeAvcSicResultINTEL, - R"(OpTypeAvcSicResultINTEL)", - &s_operands[1731], - &s_operands[1731], - 1, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL)", - &s_operands[1732], - &s_operands[1733], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL, - R"(OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL)", - &s_operands[1736], - &s_operands[1737], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL)", - &s_operands[1740], - &s_operands[1741], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceSetInterShapePenaltyINTEL, - R"(OpSubgroupAvcMceSetInterShapePenaltyINTEL)", - &s_operands[1744], - &s_operands[1745], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL)", - &s_operands[1748], - &s_operands[1749], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceSetInterDirectionPenaltyINTEL, - R"(OpSubgroupAvcMceSetInterDirectionPenaltyINTEL)", - &s_operands[1752], - &s_operands[1753], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL)", - &s_operands[1756], - &s_operands[1757], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL, - R"(OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL)", - &s_operands[1760], - &s_operands[1761], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL, - R"(OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL)", - &s_operands[1764], - &s_operands[1765], - 2, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL, - R"(OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL)", - &s_operands[1766], - &s_operands[1767], - 2, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL, - R"(OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL)", - &s_operands[1768], - &s_operands[1769], - 2, - }, - { - SpirvOp::OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL, - R"(OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL)", - &s_operands[1770], - &s_operands[1771], - 6, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL)", - &s_operands[1776], - &s_operands[1777], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL)", - &s_operands[1780], - &s_operands[1781], - 2, - }, - { - SpirvOp::OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL, - R"(OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL)", - &s_operands[1782], - &s_operands[1783], - 2, - }, - { - SpirvOp::OpSubgroupAvcMceSetAcOnlyHaarINTEL, - R"(OpSubgroupAvcMceSetAcOnlyHaarINTEL)", - &s_operands[1784], - &s_operands[1785], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL, - R"(OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL)", - &s_operands[1787], - &s_operands[1788], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL, - R"(OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL)", - &s_operands[1791], - &s_operands[1792], - 4, - }, - { - SpirvOp::OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL, - R"(OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL)", - &s_operands[1795], - &s_operands[1796], - 5, - }, - { - SpirvOp::OpSubgroupAvcMceConvertToImePayloadINTEL, - R"(OpSubgroupAvcMceConvertToImePayloadINTEL)", - &s_operands[1800], - &s_operands[1801], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceConvertToImeResultINTEL, - R"(OpSubgroupAvcMceConvertToImeResultINTEL)", - &s_operands[1803], - &s_operands[1804], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceConvertToRefPayloadINTEL, - R"(OpSubgroupAvcMceConvertToRefPayloadINTEL)", - &s_operands[1806], - &s_operands[1807], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceConvertToRefResultINTEL, - R"(OpSubgroupAvcMceConvertToRefResultINTEL)", - &s_operands[1809], - &s_operands[1810], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceConvertToSicPayloadINTEL, - R"(OpSubgroupAvcMceConvertToSicPayloadINTEL)", - &s_operands[1812], - &s_operands[1813], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceConvertToSicResultINTEL, - R"(OpSubgroupAvcMceConvertToSicResultINTEL)", - &s_operands[1815], - &s_operands[1816], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetMotionVectorsINTEL, - R"(OpSubgroupAvcMceGetMotionVectorsINTEL)", - &s_operands[1818], - &s_operands[1819], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterDistortionsINTEL, - R"(OpSubgroupAvcMceGetInterDistortionsINTEL)", - &s_operands[1821], - &s_operands[1822], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetBestInterDistortionsINTEL, - R"(OpSubgroupAvcMceGetBestInterDistortionsINTEL)", - &s_operands[1824], - &s_operands[1825], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterMajorShapeINTEL, - R"(OpSubgroupAvcMceGetInterMajorShapeINTEL)", - &s_operands[1827], - &s_operands[1828], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterMinorShapeINTEL, - R"(OpSubgroupAvcMceGetInterMinorShapeINTEL)", - &s_operands[1830], - &s_operands[1831], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterDirectionsINTEL, - R"(OpSubgroupAvcMceGetInterDirectionsINTEL)", - &s_operands[1833], - &s_operands[1834], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterMotionVectorCountINTEL, - R"(OpSubgroupAvcMceGetInterMotionVectorCountINTEL)", - &s_operands[1836], - &s_operands[1837], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterReferenceIdsINTEL, - R"(OpSubgroupAvcMceGetInterReferenceIdsINTEL)", - &s_operands[1839], - &s_operands[1840], - 3, - }, - { - SpirvOp::OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL, - R"(OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL)", - &s_operands[1842], - &s_operands[1843], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeInitializeINTEL, - R"(OpSubgroupAvcImeInitializeINTEL)", - &s_operands[1847], - &s_operands[1848], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeSetSingleReferenceINTEL, - R"(OpSubgroupAvcImeSetSingleReferenceINTEL)", - &s_operands[1852], - &s_operands[1853], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeSetDualReferenceINTEL, - R"(OpSubgroupAvcImeSetDualReferenceINTEL)", - &s_operands[1857], - &s_operands[1858], - 6, - }, - { - SpirvOp::OpSubgroupAvcImeRefWindowSizeINTEL, - R"(OpSubgroupAvcImeRefWindowSizeINTEL)", - &s_operands[1863], - &s_operands[1864], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeAdjustRefOffsetINTEL, - R"(OpSubgroupAvcImeAdjustRefOffsetINTEL)", - &s_operands[1867], - &s_operands[1868], - 6, - }, - { - SpirvOp::OpSubgroupAvcImeConvertToMcePayloadINTEL, - R"(OpSubgroupAvcImeConvertToMcePayloadINTEL)", - &s_operands[1873], - &s_operands[1874], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeSetMaxMotionVectorCountINTEL, - R"(OpSubgroupAvcImeSetMaxMotionVectorCountINTEL)", - &s_operands[1876], - &s_operands[1877], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL, - R"(OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL)", - &s_operands[1880], - &s_operands[1881], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL, - R"(OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL)", - &s_operands[1883], - &s_operands[1884], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeSetWeightedSadINTEL, - R"(OpSubgroupAvcImeSetWeightedSadINTEL)", - &s_operands[1887], - &s_operands[1888], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL, - R"(OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL)", - &s_operands[1891], - &s_operands[1892], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithDualReferenceINTEL, - R"(OpSubgroupAvcImeEvaluateWithDualReferenceINTEL)", - &s_operands[1896], - &s_operands[1897], - 6, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL, - R"(OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL)", - &s_operands[1902], - &s_operands[1903], - 6, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL, - R"(OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL)", - &s_operands[1908], - &s_operands[1909], - 7, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL, - R"(OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL)", - &s_operands[1915], - &s_operands[1916], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL, - R"(OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL)", - &s_operands[1920], - &s_operands[1921], - 6, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL, - R"(OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL)", - &s_operands[1926], - &s_operands[1927], - 6, - }, - { - SpirvOp::OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL, - R"(OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL)", - &s_operands[1932], - &s_operands[1933], - 7, - }, - { - SpirvOp::OpSubgroupAvcImeConvertToMceResultINTEL, - R"(OpSubgroupAvcImeConvertToMceResultINTEL)", - &s_operands[1939], - &s_operands[1940], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeGetSingleReferenceStreaminINTEL, - R"(OpSubgroupAvcImeGetSingleReferenceStreaminINTEL)", - &s_operands[1942], - &s_operands[1943], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeGetDualReferenceStreaminINTEL, - R"(OpSubgroupAvcImeGetDualReferenceStreaminINTEL)", - &s_operands[1945], - &s_operands[1946], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL, - R"(OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL)", - &s_operands[1948], - &s_operands[1949], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeStripDualReferenceStreamoutINTEL, - R"(OpSubgroupAvcImeStripDualReferenceStreamoutINTEL)", - &s_operands[1951], - &s_operands[1952], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL, - R"(OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL)", - &s_operands[1954], - &s_operands[1955], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL, - R"(OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL)", - &s_operands[1958], - &s_operands[1959], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL, - R"(OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL)", - &s_operands[1962], - &s_operands[1963], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL, - R"(OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL)", - &s_operands[1966], - &s_operands[1967], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL, - R"(OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL)", - &s_operands[1971], - &s_operands[1972], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL, - R"(OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL)", - &s_operands[1976], - &s_operands[1977], - 5, - }, - { - SpirvOp::OpSubgroupAvcImeGetBorderReachedINTEL, - R"(OpSubgroupAvcImeGetBorderReachedINTEL)", - &s_operands[1981], - &s_operands[1982], - 4, - }, - { - SpirvOp::OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL, - R"(OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL)", - &s_operands[1985], - &s_operands[1986], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL, - R"(OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL)", - &s_operands[1988], - &s_operands[1989], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL, - R"(OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL)", - &s_operands[1991], - &s_operands[1992], - 3, - }, - { - SpirvOp::OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL, - R"(OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL)", - &s_operands[1994], - &s_operands[1995], - 3, - }, - { - SpirvOp::OpSubgroupAvcFmeInitializeINTEL, - R"(OpSubgroupAvcFmeInitializeINTEL)", - &s_operands[1997], - &s_operands[1998], - 9, - }, - { - SpirvOp::OpSubgroupAvcBmeInitializeINTEL, - R"(OpSubgroupAvcBmeInitializeINTEL)", - &s_operands[2006], - &s_operands[2007], - 10, - }, - { - SpirvOp::OpSubgroupAvcRefConvertToMcePayloadINTEL, - R"(OpSubgroupAvcRefConvertToMcePayloadINTEL)", - &s_operands[2016], - &s_operands[2017], - 3, - }, - { - SpirvOp::OpSubgroupAvcRefSetBidirectionalMixDisableINTEL, - R"(OpSubgroupAvcRefSetBidirectionalMixDisableINTEL)", - &s_operands[2019], - &s_operands[2020], - 3, - }, - { - SpirvOp::OpSubgroupAvcRefSetBilinearFilterEnableINTEL, - R"(OpSubgroupAvcRefSetBilinearFilterEnableINTEL)", - &s_operands[2022], - &s_operands[2023], - 3, - }, - { - SpirvOp::OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL, - R"(OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL)", - &s_operands[2025], - &s_operands[2026], - 5, - }, - { - SpirvOp::OpSubgroupAvcRefEvaluateWithDualReferenceINTEL, - R"(OpSubgroupAvcRefEvaluateWithDualReferenceINTEL)", - &s_operands[2030], - &s_operands[2031], - 6, - }, - { - SpirvOp::OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL, - R"(OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL)", - &s_operands[2036], - &s_operands[2037], - 5, - }, - { - SpirvOp::OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL, - R"(OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL)", - &s_operands[2041], - &s_operands[2042], - 6, - }, - { - SpirvOp::OpSubgroupAvcRefConvertToMceResultINTEL, - R"(OpSubgroupAvcRefConvertToMceResultINTEL)", - &s_operands[2047], - &s_operands[2048], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicInitializeINTEL, - R"(OpSubgroupAvcSicInitializeINTEL)", - &s_operands[2050], - &s_operands[2051], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicConfigureSkcINTEL, - R"(OpSubgroupAvcSicConfigureSkcINTEL)", - &s_operands[2053], - &s_operands[2054], - 8, - }, - { - SpirvOp::OpSubgroupAvcSicConfigureIpeLumaINTEL, - R"(OpSubgroupAvcSicConfigureIpeLumaINTEL)", - &s_operands[2061], - &s_operands[2062], - 10, - }, - { - SpirvOp::OpSubgroupAvcSicConfigureIpeLumaChromaINTEL, - R"(OpSubgroupAvcSicConfigureIpeLumaChromaINTEL)", - &s_operands[2071], - &s_operands[2072], - 13, - }, - { - SpirvOp::OpSubgroupAvcSicGetMotionVectorMaskINTEL, - R"(OpSubgroupAvcSicGetMotionVectorMaskINTEL)", - &s_operands[2084], - &s_operands[2085], - 4, - }, - { - SpirvOp::OpSubgroupAvcSicConvertToMcePayloadINTEL, - R"(OpSubgroupAvcSicConvertToMcePayloadINTEL)", - &s_operands[2088], - &s_operands[2089], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL, - R"(OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL)", - &s_operands[2091], - &s_operands[2092], - 4, - }, - { - SpirvOp::OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL, - R"(OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL)", - &s_operands[2095], - &s_operands[2096], - 6, - }, - { - SpirvOp::OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL, - R"(OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL)", - &s_operands[2101], - &s_operands[2102], - 4, - }, - { - SpirvOp::OpSubgroupAvcSicSetBilinearFilterEnableINTEL, - R"(OpSubgroupAvcSicSetBilinearFilterEnableINTEL)", - &s_operands[2105], - &s_operands[2106], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL, - R"(OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL)", - &s_operands[2108], - &s_operands[2109], - 4, - }, - { - SpirvOp::OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL, - R"(OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL)", - &s_operands[2112], - &s_operands[2113], - 4, - }, - { - SpirvOp::OpSubgroupAvcSicEvaluateIpeINTEL, - R"(OpSubgroupAvcSicEvaluateIpeINTEL)", - &s_operands[2116], - &s_operands[2117], - 4, - }, - { - SpirvOp::OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL, - R"(OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL)", - &s_operands[2120], - &s_operands[2121], - 5, - }, - { - SpirvOp::OpSubgroupAvcSicEvaluateWithDualReferenceINTEL, - R"(OpSubgroupAvcSicEvaluateWithDualReferenceINTEL)", - &s_operands[2125], - &s_operands[2126], - 6, - }, - { - SpirvOp::OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL, - R"(OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL)", - &s_operands[2131], - &s_operands[2132], - 5, - }, - { - SpirvOp::OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL, - R"(OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL)", - &s_operands[2136], - &s_operands[2137], - 6, - }, - { - SpirvOp::OpSubgroupAvcSicConvertToMceResultINTEL, - R"(OpSubgroupAvcSicConvertToMceResultINTEL)", - &s_operands[2142], - &s_operands[2143], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetIpeLumaShapeINTEL, - R"(OpSubgroupAvcSicGetIpeLumaShapeINTEL)", - &s_operands[2145], - &s_operands[2146], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL, - R"(OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL)", - &s_operands[2148], - &s_operands[2149], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL, - R"(OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL)", - &s_operands[2151], - &s_operands[2152], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetPackedIpeLumaModesINTEL, - R"(OpSubgroupAvcSicGetPackedIpeLumaModesINTEL)", - &s_operands[2154], - &s_operands[2155], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetIpeChromaModeINTEL, - R"(OpSubgroupAvcSicGetIpeChromaModeINTEL)", - &s_operands[2157], - &s_operands[2158], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL, - R"(OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL)", - &s_operands[2160], - &s_operands[2161], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL, - R"(OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL)", - &s_operands[2163], - &s_operands[2164], - 3, - }, - { - SpirvOp::OpSubgroupAvcSicGetInterRawSadsINTEL, - R"(OpSubgroupAvcSicGetInterRawSadsINTEL)", - &s_operands[2166], - &s_operands[2167], - 3, - }, - { - SpirvOp::OpVariableLengthArrayINTEL, - R"(OpVariableLengthArrayINTEL)", - &s_operands[2169], - &s_operands[2170], - 3, - }, - { - SpirvOp::OpSaveMemoryINTEL, - R"(OpSaveMemoryINTEL)", - &s_operands[2172], - &s_operands[2173], - 2, - }, - { - SpirvOp::OpRestoreMemoryINTEL, - R"(OpRestoreMemoryINTEL)", - &s_operands[2174], - nullptr, - 1, - }, - { - SpirvOp::OpArbitraryFloatSinCosPiINTEL, - R"(OpArbitraryFloatSinCosPiINTEL)", - &s_operands[2175], - &s_operands[2176], - 9, - }, - { - SpirvOp::OpArbitraryFloatCastINTEL, - R"(OpArbitraryFloatCastINTEL)", - &s_operands[2184], - &s_operands[2185], - 8, - }, - { - SpirvOp::OpArbitraryFloatCastFromIntINTEL, - R"(OpArbitraryFloatCastFromIntINTEL)", - &s_operands[2192], - &s_operands[2193], - 8, - }, - { - SpirvOp::OpArbitraryFloatCastToIntINTEL, - R"(OpArbitraryFloatCastToIntINTEL)", - &s_operands[2200], - &s_operands[2201], - 7, - }, - { - SpirvOp::OpArbitraryFloatAddINTEL, - R"(OpArbitraryFloatAddINTEL)", - &s_operands[2207], - &s_operands[2208], - 10, - }, - { - SpirvOp::OpArbitraryFloatSubINTEL, - R"(OpArbitraryFloatSubINTEL)", - &s_operands[2217], - &s_operands[2218], - 10, - }, - { - SpirvOp::OpArbitraryFloatMulINTEL, - R"(OpArbitraryFloatMulINTEL)", - &s_operands[2227], - &s_operands[2228], - 10, - }, - { - SpirvOp::OpArbitraryFloatDivINTEL, - R"(OpArbitraryFloatDivINTEL)", - &s_operands[2237], - &s_operands[2238], - 10, - }, - { - SpirvOp::OpArbitraryFloatGTINTEL, - R"(OpArbitraryFloatGTINTEL)", - &s_operands[2247], - &s_operands[2248], - 6, - }, - { - SpirvOp::OpArbitraryFloatGEINTEL, - R"(OpArbitraryFloatGEINTEL)", - &s_operands[2253], - &s_operands[2254], - 6, - }, - { - SpirvOp::OpArbitraryFloatLTINTEL, - R"(OpArbitraryFloatLTINTEL)", - &s_operands[2259], - &s_operands[2260], - 6, - }, - { - SpirvOp::OpArbitraryFloatLEINTEL, - R"(OpArbitraryFloatLEINTEL)", - &s_operands[2265], - &s_operands[2266], - 6, - }, - { - SpirvOp::OpArbitraryFloatEQINTEL, - R"(OpArbitraryFloatEQINTEL)", - &s_operands[2271], - &s_operands[2272], - 6, - }, - { - SpirvOp::OpArbitraryFloatRecipINTEL, - R"(OpArbitraryFloatRecipINTEL)", - &s_operands[2277], - &s_operands[2278], - 8, - }, - { - SpirvOp::OpArbitraryFloatRSqrtINTEL, - R"(OpArbitraryFloatRSqrtINTEL)", - &s_operands[2285], - &s_operands[2286], - 8, - }, - { - SpirvOp::OpArbitraryFloatCbrtINTEL, - R"(OpArbitraryFloatCbrtINTEL)", - &s_operands[2293], - &s_operands[2294], - 8, - }, - { - SpirvOp::OpArbitraryFloatHypotINTEL, - R"(OpArbitraryFloatHypotINTEL)", - &s_operands[2301], - &s_operands[2302], - 10, - }, - { - SpirvOp::OpArbitraryFloatSqrtINTEL, - R"(OpArbitraryFloatSqrtINTEL)", - &s_operands[2311], - &s_operands[2312], - 8, - }, - { - SpirvOp::OpArbitraryFloatLogINTEL, - R"(OpArbitraryFloatLogINTEL)", - &s_operands[2319], - &s_operands[2320], - 8, - }, - { - SpirvOp::OpArbitraryFloatLog2INTEL, - R"(OpArbitraryFloatLog2INTEL)", - &s_operands[2327], - &s_operands[2328], - 8, - }, - { - SpirvOp::OpArbitraryFloatLog10INTEL, - R"(OpArbitraryFloatLog10INTEL)", - &s_operands[2335], - &s_operands[2336], - 8, - }, - { - SpirvOp::OpArbitraryFloatLog1pINTEL, - R"(OpArbitraryFloatLog1pINTEL)", - &s_operands[2343], - &s_operands[2344], - 8, - }, - { - SpirvOp::OpArbitraryFloatExpINTEL, - R"(OpArbitraryFloatExpINTEL)", - &s_operands[2351], - &s_operands[2352], - 8, - }, - { - SpirvOp::OpArbitraryFloatExp2INTEL, - R"(OpArbitraryFloatExp2INTEL)", - &s_operands[2359], - &s_operands[2360], - 8, - }, - { - SpirvOp::OpArbitraryFloatExp10INTEL, - R"(OpArbitraryFloatExp10INTEL)", - &s_operands[2367], - &s_operands[2368], - 8, - }, - { - SpirvOp::OpArbitraryFloatExpm1INTEL, - R"(OpArbitraryFloatExpm1INTEL)", - &s_operands[2375], - &s_operands[2376], - 8, - }, - { - SpirvOp::OpArbitraryFloatSinINTEL, - R"(OpArbitraryFloatSinINTEL)", - &s_operands[2383], - &s_operands[2384], - 8, - }, - { - SpirvOp::OpArbitraryFloatCosINTEL, - R"(OpArbitraryFloatCosINTEL)", - &s_operands[2391], - &s_operands[2392], - 8, - }, - { - SpirvOp::OpArbitraryFloatSinCosINTEL, - R"(OpArbitraryFloatSinCosINTEL)", - &s_operands[2399], - &s_operands[2400], - 8, - }, - { - SpirvOp::OpArbitraryFloatSinPiINTEL, - R"(OpArbitraryFloatSinPiINTEL)", - &s_operands[2407], - &s_operands[2408], - 8, - }, - { - SpirvOp::OpArbitraryFloatCosPiINTEL, - R"(OpArbitraryFloatCosPiINTEL)", - &s_operands[2415], - &s_operands[2416], - 8, - }, - { - SpirvOp::OpArbitraryFloatASinINTEL, - R"(OpArbitraryFloatASinINTEL)", - &s_operands[2423], - &s_operands[2424], - 8, - }, - { - SpirvOp::OpArbitraryFloatASinPiINTEL, - R"(OpArbitraryFloatASinPiINTEL)", - &s_operands[2431], - &s_operands[2432], - 8, - }, - { - SpirvOp::OpArbitraryFloatACosINTEL, - R"(OpArbitraryFloatACosINTEL)", - &s_operands[2439], - &s_operands[2440], - 8, - }, - { - SpirvOp::OpArbitraryFloatACosPiINTEL, - R"(OpArbitraryFloatACosPiINTEL)", - &s_operands[2447], - &s_operands[2448], - 8, - }, - { - SpirvOp::OpArbitraryFloatATanINTEL, - R"(OpArbitraryFloatATanINTEL)", - &s_operands[2455], - &s_operands[2456], - 8, - }, - { - SpirvOp::OpArbitraryFloatATanPiINTEL, - R"(OpArbitraryFloatATanPiINTEL)", - &s_operands[2463], - &s_operands[2464], - 8, - }, - { - SpirvOp::OpArbitraryFloatATan2INTEL, - R"(OpArbitraryFloatATan2INTEL)", - &s_operands[2471], - &s_operands[2472], - 10, - }, - { - SpirvOp::OpArbitraryFloatPowINTEL, - R"(OpArbitraryFloatPowINTEL)", - &s_operands[2481], - &s_operands[2482], - 10, - }, - { - SpirvOp::OpArbitraryFloatPowRINTEL, - R"(OpArbitraryFloatPowRINTEL)", - &s_operands[2491], - &s_operands[2492], - 10, - }, - { - SpirvOp::OpArbitraryFloatPowNINTEL, - R"(OpArbitraryFloatPowNINTEL)", - &s_operands[2501], - &s_operands[2502], - 9, - }, - { - SpirvOp::OpLoopControlINTEL, - R"(OpLoopControlINTEL)", - &s_operands[2510], - nullptr, - 1, - }, - { - SpirvOp::OpAliasDomainDeclINTEL, - R"(OpAliasDomainDeclINTEL)", - &s_operands[2511], - &s_operands[2511], - 2, - }, - { - SpirvOp::OpAliasScopeDeclINTEL, - R"(OpAliasScopeDeclINTEL)", - &s_operands[2513], - &s_operands[2513], - 3, - }, - { - SpirvOp::OpAliasScopeListDeclINTEL, - R"(OpAliasScopeListDeclINTEL)", - &s_operands[2516], - &s_operands[2516], - 2, - }, - { - SpirvOp::OpFixedSqrtINTEL, - R"(OpFixedSqrtINTEL)", - &s_operands[2518], - &s_operands[2519], - 9, - }, - { - SpirvOp::OpFixedRecipINTEL, - R"(OpFixedRecipINTEL)", - &s_operands[2527], - &s_operands[2528], - 9, - }, - { - SpirvOp::OpFixedRsqrtINTEL, - R"(OpFixedRsqrtINTEL)", - &s_operands[2536], - &s_operands[2537], - 9, - }, - { - SpirvOp::OpFixedSinINTEL, - R"(OpFixedSinINTEL)", - &s_operands[2545], - &s_operands[2546], - 9, - }, - { - SpirvOp::OpFixedCosINTEL, - R"(OpFixedCosINTEL)", - &s_operands[2554], - &s_operands[2555], - 9, - }, - { - SpirvOp::OpFixedSinCosINTEL, - R"(OpFixedSinCosINTEL)", - &s_operands[2563], - &s_operands[2564], - 9, - }, - { - SpirvOp::OpFixedSinPiINTEL, - R"(OpFixedSinPiINTEL)", - &s_operands[2572], - &s_operands[2573], - 9, - }, - { - SpirvOp::OpFixedCosPiINTEL, - R"(OpFixedCosPiINTEL)", - &s_operands[2581], - &s_operands[2582], - 9, - }, - { - SpirvOp::OpFixedSinCosPiINTEL, - R"(OpFixedSinCosPiINTEL)", - &s_operands[2590], - &s_operands[2591], - 9, - }, - { - SpirvOp::OpFixedLogINTEL, - R"(OpFixedLogINTEL)", - &s_operands[2599], - &s_operands[2600], - 9, - }, - { - SpirvOp::OpFixedExpINTEL, - R"(OpFixedExpINTEL)", - &s_operands[2608], - &s_operands[2609], - 9, - }, - { - SpirvOp::OpPtrCastToCrossWorkgroupINTEL, - R"(OpPtrCastToCrossWorkgroupINTEL)", - &s_operands[2617], - &s_operands[2618], - 3, - }, - { - SpirvOp::OpCrossWorkgroupCastToPtrINTEL, - R"(OpCrossWorkgroupCastToPtrINTEL)", - &s_operands[2620], - &s_operands[2621], - 3, - }, - { - SpirvOp::OpReadPipeBlockingINTEL, - R"(OpReadPipeBlockingINTEL)", - &s_operands[2623], - &s_operands[2624], - 4, - }, - { - SpirvOp::OpWritePipeBlockingINTEL, - R"(OpWritePipeBlockingINTEL)", - &s_operands[2627], - &s_operands[2628], - 4, - }, - { - SpirvOp::OpFPGARegINTEL, - R"(OpFPGARegINTEL)", - &s_operands[2631], - &s_operands[2632], - 4, - }, - { - SpirvOp::OpRayQueryGetRayTMinKHR, - R"(OpRayQueryGetRayTMinKHR)", - &s_operands[2635], - &s_operands[2636], - 3, - }, - { - SpirvOp::OpRayQueryGetRayFlagsKHR, - R"(OpRayQueryGetRayFlagsKHR)", - &s_operands[2638], - &s_operands[2639], - 3, - }, - { - SpirvOp::OpRayQueryGetIntersectionTKHR, - R"(OpRayQueryGetIntersectionTKHR)", - &s_operands[2641], - &s_operands[2642], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionInstanceCustomIndexKHR, - R"(OpRayQueryGetIntersectionInstanceCustomIndexKHR)", - &s_operands[2645], - &s_operands[2646], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionInstanceIdKHR, - R"(OpRayQueryGetIntersectionInstanceIdKHR)", - &s_operands[2649], - &s_operands[2650], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR, - R"(OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR)", - &s_operands[2653], - &s_operands[2654], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionGeometryIndexKHR, - R"(OpRayQueryGetIntersectionGeometryIndexKHR)", - &s_operands[2657], - &s_operands[2658], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionPrimitiveIndexKHR, - R"(OpRayQueryGetIntersectionPrimitiveIndexKHR)", - &s_operands[2661], - &s_operands[2662], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionBarycentricsKHR, - R"(OpRayQueryGetIntersectionBarycentricsKHR)", - &s_operands[2665], - &s_operands[2666], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionFrontFaceKHR, - R"(OpRayQueryGetIntersectionFrontFaceKHR)", - &s_operands[2669], - &s_operands[2670], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR, - R"(OpRayQueryGetIntersectionCandidateAABBOpaqueKHR)", - &s_operands[2673], - &s_operands[2674], - 3, - }, - { - SpirvOp::OpRayQueryGetIntersectionObjectRayDirectionKHR, - R"(OpRayQueryGetIntersectionObjectRayDirectionKHR)", - &s_operands[2676], - &s_operands[2677], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionObjectRayOriginKHR, - R"(OpRayQueryGetIntersectionObjectRayOriginKHR)", - &s_operands[2680], - &s_operands[2681], - 4, - }, - { - SpirvOp::OpRayQueryGetWorldRayDirectionKHR, - R"(OpRayQueryGetWorldRayDirectionKHR)", - &s_operands[2684], - &s_operands[2685], - 3, - }, - { - SpirvOp::OpRayQueryGetWorldRayOriginKHR, - R"(OpRayQueryGetWorldRayOriginKHR)", - &s_operands[2687], - &s_operands[2688], - 3, - }, - { - SpirvOp::OpRayQueryGetIntersectionObjectToWorldKHR, - R"(OpRayQueryGetIntersectionObjectToWorldKHR)", - &s_operands[2690], - &s_operands[2691], - 4, - }, - { - SpirvOp::OpRayQueryGetIntersectionWorldToObjectKHR, - R"(OpRayQueryGetIntersectionWorldToObjectKHR)", - &s_operands[2694], - &s_operands[2695], - 4, - }, - { - SpirvOp::OpAtomicFAddEXT, - R"(OpAtomicFAddEXT)", - &s_operands[2698], - &s_operands[2699], - 6, - }, - { - SpirvOp::OpTypeBufferSurfaceINTEL, - R"(OpTypeBufferSurfaceINTEL)", - &s_operands[2704], - &s_operands[2704], - 2, - }, - { - SpirvOp::OpTypeStructContinuedINTEL, - R"(OpTypeStructContinuedINTEL)", - &s_operands[2706], - nullptr, - 1, - }, - { - SpirvOp::OpConstantCompositeContinuedINTEL, - R"(OpConstantCompositeContinuedINTEL)", - &s_operands[2707], - nullptr, - 1, - }, - { - SpirvOp::OpSpecConstantCompositeContinuedINTEL, - R"(OpSpecConstantCompositeContinuedINTEL)", - &s_operands[2708], - nullptr, - 1, - }, - { - SpirvOp::OpControlBarrierArriveINTEL, - R"(OpControlBarrierArriveINTEL)", - &s_operands[2709], - nullptr, - 3, - }, - { - SpirvOp::OpControlBarrierWaitINTEL, - R"(OpControlBarrierWaitINTEL)", - &s_operands[2712], - nullptr, - 3, - }, - { - SpirvOp::OpGroupIMulKHR, - R"(OpGroupIMulKHR)", - &s_operands[2715], - &s_operands[2716], - 5, - }, - { - SpirvOp::OpGroupFMulKHR, - R"(OpGroupFMulKHR)", - &s_operands[2720], - &s_operands[2721], - 5, - }, - { - SpirvOp::OpGroupBitwiseAndKHR, - R"(OpGroupBitwiseAndKHR)", - &s_operands[2725], - &s_operands[2726], - 5, - }, - { - SpirvOp::OpGroupBitwiseOrKHR, - R"(OpGroupBitwiseOrKHR)", - &s_operands[2730], - &s_operands[2731], - 5, - }, - { - SpirvOp::OpGroupBitwiseXorKHR, - R"(OpGroupBitwiseXorKHR)", - &s_operands[2735], - &s_operands[2736], - 5, - }, - { - SpirvOp::OpGroupLogicalAndKHR, - R"(OpGroupLogicalAndKHR)", - &s_operands[2740], - &s_operands[2741], - 5, - }, - { - SpirvOp::OpGroupLogicalOrKHR, - R"(OpGroupLogicalOrKHR)", - &s_operands[2745], - &s_operands[2746], - 5, - }, - { - SpirvOp::OpGroupLogicalXorKHR, - R"(OpGroupLogicalXorKHR)", - &s_operands[2750], - &s_operands[2751], - 5, - }, - } - }; - - const SpirvInstruction* GetInstructionData(UInt16 op) - { - auto it = std::lower_bound(std::begin(s_instructions), std::end(s_instructions), op, [](const SpirvInstruction& inst, UInt16 op) { return UInt16(inst.op) < op; }); - if (it != std::end(s_instructions) && UInt16(it->op) == op) - return &*it; - else - return nullptr; - } -} diff --git a/src/Nazara/Shader/SpirvDecoder.cpp b/src/Nazara/Shader/SpirvDecoder.cpp deleted file mode 100644 index 63578fdd9..000000000 --- a/src/Nazara/Shader/SpirvDecoder.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - void SpirvDecoder::Decode(const UInt32* codepoints, std::size_t count) - { - m_currentCodepoint = codepoints; - m_codepointEnd = codepoints + count; - - UInt32 magicNumber = ReadWord(); - if (magicNumber != SpirvMagicNumber) - throw std::runtime_error("invalid Spir-V: magic number didn't match"); - - UInt32 versionNumber = ReadWord(); - if (versionNumber > SpirvVersion) - throw std::runtime_error("Spir-V is more recent than decoder, dismissing"); - - SpirvHeader header; - header.generatorId = ReadWord(); - header.bound = ReadWord(); - header.schema = ReadWord(); - header.versionNumber = versionNumber; - - if (!HandleHeader(header)) - return; - - while (m_currentCodepoint < m_codepointEnd) - { - const UInt32* instructionBegin = m_currentCodepoint; - - UInt32 firstWord = ReadWord(); - - UInt16 wordCount = static_cast((firstWord >> 16) & 0xFFFF); - UInt16 opcode = static_cast(firstWord & 0xFFFF); - - const SpirvInstruction* inst = GetInstructionData(opcode); - if (!inst) - throw std::runtime_error("invalid instruction"); - - if (!HandleOpcode(*inst, wordCount)) - break; - - m_currentCodepoint = instructionBegin + wordCount; - } - } - - bool SpirvDecoder::HandleHeader(const SpirvHeader& /*header*/) - { - return true; - } - - std::string SpirvDecoder::ReadString() - { - std::string str; - - for (;;) - { - UInt32 value = ReadWord(); - for (std::size_t j = 0; j < 4; ++j) - { - char c = static_cast((value >> (j * 8)) & 0xFF); - if (c == '\0') - return str; - - str.push_back(c); - } - } - } - - UInt32 SpirvDecoder::ReadWord() - { - if (m_currentCodepoint >= m_codepointEnd) - throw std::runtime_error("unexpected end of stream"); - - return *m_currentCodepoint++; - } -} diff --git a/src/Nazara/Shader/SpirvExpressionLoad.cpp b/src/Nazara/Shader/SpirvExpressionLoad.cpp deleted file mode 100644 index 690b535b0..000000000 --- a/src/Nazara/Shader/SpirvExpressionLoad.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - UInt32 SpirvExpressionLoad::Evaluate(ShaderAst::Expression& node) - { - node.Visit(*this); - - return std::visit(Overloaded - { - [this](const Pointer& pointer) -> UInt32 - { - UInt32 resultId = m_visitor.AllocateResultId(); - m_block.Append(SpirvOp::OpLoad, pointer.pointedTypeId, resultId, pointer.pointerId); - - return resultId; - }, - [this](const PointerChainAccess& pointerChainAccess) -> UInt32 - { - UInt32 pointerType = m_writer.RegisterPointerType(*pointerChainAccess.exprType, pointerChainAccess.storage); //< FIXME: We shouldn't register this so late - - UInt32 pointerId = m_visitor.AllocateResultId(); - - m_block.AppendVariadic(SpirvOp::OpAccessChain, [&](const auto& appender) - { - appender(pointerType); - appender(pointerId); - appender(pointerChainAccess.pointerId); - - for (UInt32 id : pointerChainAccess.indices) - appender(id); - }); - - UInt32 resultId = m_visitor.AllocateResultId(); - m_block.Append(SpirvOp::OpLoad, m_writer.GetTypeId(*pointerChainAccess.exprType), resultId, pointerId); - - return resultId; - }, - [](const Value& value) -> UInt32 - { - return value.valueId; - }, - [this](const ValueExtraction& extractedValue) -> UInt32 - { - UInt32 resultId = m_visitor.AllocateResultId(); - - m_block.AppendVariadic(SpirvOp::OpCompositeExtract, [&](const auto& appender) - { - appender(extractedValue.typeId); - appender(resultId); - appender(extractedValue.valueId); - - for (UInt32 id : extractedValue.indices) - appender(id); - }); - - return resultId; - }, - [](std::monostate) -> UInt32 - { - throw std::runtime_error("an internal error occurred"); - } - }, m_value); - } - - void SpirvExpressionLoad::Visit(ShaderAst::AccessIndexExpression& node) - { - node.expr->Visit(*this); - - const ShaderAst::ExpressionType* exprType = GetExpressionType(node); - assert(exprType); - - UInt32 typeId = m_writer.GetTypeId(*exprType); - - assert(node.indices.size() == 1); - UInt32 indexId = m_visitor.EvaluateExpression(node.indices.front()); - - std::visit(Overloaded - { - [&](const Pointer& pointer) - { - PointerChainAccess pointerChainAccess; - pointerChainAccess.exprType = exprType; - pointerChainAccess.indices = { indexId }; - pointerChainAccess.pointedTypeId = pointer.pointedTypeId; - pointerChainAccess.pointerId = pointer.pointerId; - pointerChainAccess.storage = pointer.storage; - - m_value = std::move(pointerChainAccess); - }, - [&](PointerChainAccess& pointerChainAccess) - { - pointerChainAccess.exprType = exprType; - pointerChainAccess.indices.push_back(indexId); - }, - [&](const Value& value) - { - ValueExtraction extractedValue; - extractedValue.indices = { indexId }; - extractedValue.typeId = typeId; - extractedValue.valueId = value.valueId; - - m_value = std::move(extractedValue); - }, - [&](ValueExtraction& extractedValue) - { - extractedValue.indices.push_back(indexId); - extractedValue.typeId = typeId; - }, - [](std::monostate) - { - throw std::runtime_error("an internal error occurred"); - } - }, m_value); - } - - void SpirvExpressionLoad::Visit(ShaderAst::VariableValueExpression& node) - { - const auto& var = m_visitor.GetVariable(node.variableId); - m_value = Pointer{ var.storage, var.pointerId, var.pointedTypeId }; - } -} diff --git a/src/Nazara/Shader/SpirvExpressionStore.cpp b/src/Nazara/Shader/SpirvExpressionStore.cpp deleted file mode 100644 index b9c654e38..000000000 --- a/src/Nazara/Shader/SpirvExpressionStore.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - void SpirvExpressionStore::Store(ShaderAst::ExpressionPtr& node, UInt32 resultId) - { - node->Visit(*this); - - std::visit(Overloaded - { - [&](const Pointer& pointer) - { - m_block.Append(SpirvOp::OpStore, pointer.pointerId, resultId); - }, - [&](const SwizzledPointer& swizzledPointer) - { - if (swizzledPointer.componentCount > 1) - { - std::size_t vectorSize = swizzledPointer.swizzledType.componentCount; - - UInt32 exprTypeId = m_writer.GetTypeId(swizzledPointer.swizzledType); - - // Load original value (which will then be shuffled with new value) - UInt32 originalVecId = m_visitor.AllocateResultId(); - m_block.Append(SpirvOp::OpLoad, exprTypeId, originalVecId, swizzledPointer.pointerId); - - // Build a new composite type using OpVectorShuffle and store it - StackArray indices = NazaraStackArrayNoInit(UInt32, vectorSize); - std::iota(indices.begin(), indices.end(), UInt32(0u)); //< init with regular swizzle (0,1,2,3) - - // override with swizzle components - for (std::size_t i = 0; i < swizzledPointer.componentCount; ++i) - indices[swizzledPointer.swizzleIndices[i]] = SafeCast(vectorSize + i); - - UInt32 shuffleResultId = m_visitor.AllocateResultId(); - m_block.AppendVariadic(SpirvOp::OpVectorShuffle, [&](const auto& appender) - { - appender(exprTypeId); - appender(shuffleResultId); - - appender(originalVecId); - appender(resultId); - - for (UInt32 index : indices) - appender(index); - }); - - // Store result - m_block.Append(SpirvOp::OpStore, swizzledPointer.pointerId, shuffleResultId); - } - else - { - assert(swizzledPointer.componentCount == 1); - - const ShaderAst::ExpressionType* exprType = GetExpressionType(*node); - assert(exprType); - - UInt32 pointerType = m_writer.RegisterPointerType(*exprType, swizzledPointer.storage); //< FIXME - - // Access chain - UInt32 indexId = m_writer.GetConstantId(SafeCast(swizzledPointer.swizzleIndices[0])); - - UInt32 pointerId = m_visitor.AllocateResultId(); - m_block.Append(SpirvOp::OpAccessChain, pointerType, pointerId, swizzledPointer.pointerId, indexId); - m_block.Append(SpirvOp::OpStore, pointerId, resultId); - } - }, - [](std::monostate) - { - throw std::runtime_error("an internal error occurred"); - } - }, m_value); - } - - void SpirvExpressionStore::Visit(ShaderAst::AccessIndexExpression& node) - { - node.expr->Visit(*this); - - const ShaderAst::ExpressionType* exprType = GetExpressionType(node); - assert(exprType); - - std::visit(Overloaded - { - [&](const Pointer& pointer) - { - UInt32 resultId = m_visitor.AllocateResultId(); - UInt32 pointerType = m_writer.RegisterPointerType(*exprType, pointer.storage); //< FIXME - - assert(node.indices.size() == 1); - UInt32 indexId = m_visitor.EvaluateExpression(node.indices.front()); - - m_block.Append(SpirvOp::OpAccessChain, pointerType, resultId, pointer.pointerId, indexId); - - m_value = Pointer { pointer.storage, resultId }; - }, - [](std::monostate) - { - throw std::runtime_error("an internal error occurred"); - } - }, m_value); - } - - void SpirvExpressionStore::Visit(ShaderAst::SwizzleExpression& node) - { - node.expression->Visit(*this); - - std::visit(Overloaded - { - [&](const Pointer& pointer) - { - const ShaderAst::ExpressionType* expressionType = GetExpressionType(*node.expression); - assert(expressionType); - assert(IsVectorType(*expressionType)); - - SwizzledPointer swizzledPointer; - swizzledPointer.pointerId = pointer.pointerId; - swizzledPointer.storage = pointer.storage; - swizzledPointer.swizzledType = std::get(*expressionType); - swizzledPointer.componentCount = node.componentCount; - swizzledPointer.swizzleIndices = node.components; - - m_value = swizzledPointer; - }, - [&](SwizzledPointer& swizzledPointer) - { - // Swizzle the swizzle, keep common components - std::array newIndices; - newIndices.fill(0); //< keep compiler happy - - for (std::size_t i = 0; i < node.componentCount; ++i) - { - assert(node.components[i] < swizzledPointer.componentCount); - newIndices[i] = swizzledPointer.swizzleIndices[node.components[i]]; - } - - swizzledPointer.componentCount = node.componentCount; - swizzledPointer.swizzleIndices = newIndices; - }, - [](std::monostate) - { - throw std::runtime_error("an internal error occurred"); - } - }, m_value); - } - - void SpirvExpressionStore::Visit(ShaderAst::VariableValueExpression& node) - { - const auto& var = m_visitor.GetVariable(node.variableId); - m_value = Pointer{ var.storage, var.pointerId }; - } -} diff --git a/src/Nazara/Shader/SpirvPrinter.cpp b/src/Nazara/Shader/SpirvPrinter.cpp deleted file mode 100644 index 4a8193464..000000000 --- a/src/Nazara/Shader/SpirvPrinter.cpp +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - struct SpirvPrinter::State - { - State(const Settings& s) : - settings(s) - { - } - - std::size_t resultOffset; - std::ostringstream stream; - const Settings& settings; - }; - - std::string SpirvPrinter::Print(const UInt32* codepoints, std::size_t count, const Settings& settings) - { - State state(settings); - - m_currentState = &state; - CallOnExit resetOnExit([&] { m_currentState = nullptr; }); - - Decode(codepoints, count); - - return m_currentState->stream.str(); - } - - bool SpirvPrinter::HandleHeader(const SpirvHeader& header) - { - UInt8 majorVersion = ((header.versionNumber) >> 16) & 0xFF; - UInt8 minorVersion = ((header.versionNumber) >> 8) & 0xFF; - - m_currentState->resultOffset = std::snprintf(nullptr, 0, "%%%u = ", header.bound); - - if (m_currentState->settings.printHeader) - { - m_currentState->stream << "Version " + std::to_string(+majorVersion) << "." << std::to_string(+minorVersion) << "\n"; - m_currentState->stream << "Generator: " << std::to_string(header.generatorId) << "\n"; - m_currentState->stream << "Bound: " << std::to_string(header.bound) << "\n"; - m_currentState->stream << "Schema: " << std::to_string(header.schema) << "\n"; - } - - return true; - } - - bool SpirvPrinter::HandleOpcode(const SpirvInstruction& instruction, UInt32 wordCount) - { - const UInt32* startPtr = GetCurrentPtr(); - - if (m_currentState->settings.printParameters) - { - std::ostringstream instructionStream; - instructionStream << instruction.name; - - UInt32 resultId = 0; - - std::size_t currentOperand = 0; - const UInt32* endPtr = startPtr + wordCount - 1; - while (GetCurrentPtr() < endPtr) - { - const SpirvInstruction::Operand* operand = &instruction.operands[currentOperand]; - - if (operand->kind != SpirvOperandKind::IdResult) - { - switch (operand->kind) - { - case SpirvOperandKind::IdRef: - case SpirvOperandKind::IdResultType: - case SpirvOperandKind::IdMemorySemantics: - case SpirvOperandKind::IdScope: - { - UInt32 value = ReadWord(); - instructionStream << " %" << value; - break; - } - - case SpirvOperandKind::ImageOperands: - case SpirvOperandKind::FPFastMathMode: - case SpirvOperandKind::SelectionControl: - case SpirvOperandKind::LoopControl: - case SpirvOperandKind::FunctionControl: - case SpirvOperandKind::MemorySemantics: - case SpirvOperandKind::MemoryAccess: - case SpirvOperandKind::KernelProfilingInfo: - case SpirvOperandKind::RayFlags: - case SpirvOperandKind::SourceLanguage: - case SpirvOperandKind::ExecutionModel: - case SpirvOperandKind::AddressingModel: - case SpirvOperandKind::MemoryModel: - case SpirvOperandKind::ExecutionMode: - case SpirvOperandKind::StorageClass: - case SpirvOperandKind::Dim: - case SpirvOperandKind::SamplerAddressingMode: - case SpirvOperandKind::SamplerFilterMode: - case SpirvOperandKind::ImageFormat: - case SpirvOperandKind::ImageChannelOrder: - case SpirvOperandKind::ImageChannelDataType: - case SpirvOperandKind::FPRoundingMode: - case SpirvOperandKind::LinkageType: - case SpirvOperandKind::AccessQualifier: - case SpirvOperandKind::FunctionParameterAttribute: - case SpirvOperandKind::Decoration: - case SpirvOperandKind::BuiltIn: - case SpirvOperandKind::Scope: - case SpirvOperandKind::GroupOperation: - case SpirvOperandKind::KernelEnqueueFlags: - case SpirvOperandKind::Capability: - case SpirvOperandKind::RayQueryIntersection: - case SpirvOperandKind::RayQueryCommittedIntersectionType: - case SpirvOperandKind::RayQueryCandidateIntersectionType: - case SpirvOperandKind::LiteralExtInstInteger: - case SpirvOperandKind::LiteralSpecConstantOpInteger: - case SpirvOperandKind::LiteralContextDependentNumber: //< FIXME - { - UInt32 value = ReadWord(); - instructionStream << " " << operand->name << "(" << value << ")"; - break; - } - - case SpirvOperandKind::LiteralInteger: - { - UInt32 value = ReadWord(); - instructionStream << " " << value; - break; - } - - case SpirvOperandKind::LiteralString: - { - std::string str = ReadString(); - instructionStream << " \"" << str << "\""; - - /* - std::size_t offset = GetOutputOffset(); - - std::size_t size4 = CountWord(str); - for (std::size_t i = 0; i < size4; ++i) - { - UInt32 codepoint = 0; - for (std::size_t j = 0; j < 4; ++j) - { - std::size_t pos = i * 4 + j; - if (pos < str.size()) - codepoint |= UInt32(str[pos]) << (j * 8); - } - - Append(codepoint); - } - */ - break; - } - - - case SpirvOperandKind::PairLiteralIntegerIdRef: - { - ReadWord(); - ReadWord(); - break; - } - - case SpirvOperandKind::PairIdRefLiteralInteger: - { - ReadWord(); - ReadWord(); - break; - } - - case SpirvOperandKind::PairIdRefIdRef: - { - ReadWord(); - ReadWord(); - break; - } - - /*case SpirvOperandKind::LiteralContextDependentNumber: - { - throw std::runtime_error("not yet implemented"); - }*/ - - default: - break; - } - } - else - resultId = ReadWord(); - - if (currentOperand < instruction.minOperandCount - 1) - currentOperand++; - } - - if (resultId != 0) - { - std::string resultInfo = "%" + std::to_string(resultId) + " = "; - m_currentState->stream << std::setw(m_currentState->resultOffset) << resultInfo; - } - else - m_currentState->stream << std::string(m_currentState->resultOffset, ' '); - - m_currentState->stream << instructionStream.str(); - - assert(GetCurrentPtr() == startPtr + wordCount - 1); - } - else - m_currentState->stream << instruction.name; - - m_currentState->stream << "\n"; - - return true; - } -} diff --git a/src/Nazara/Shader/SpirvSectionBase.cpp b/src/Nazara/Shader/SpirvSectionBase.cpp deleted file mode 100644 index cb0f6675a..000000000 --- a/src/Nazara/Shader/SpirvSectionBase.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - std::size_t SpirvSectionBase::AppendRaw(const Raw& raw) - { - std::size_t offset = GetOutputOffset(); - - const UInt8* ptr = static_cast(raw.ptr); - - std::size_t size4 = CountWord(raw); - for (std::size_t i = 0; i < size4; ++i) - { - UInt32 codepoint = 0; - for (std::size_t j = 0; j < 4; ++j) - { -#ifdef NAZARA_BIG_ENDIAN - std::size_t pos = i * 4 + (3 - j); -#else - std::size_t pos = i * 4 + j; -#endif - - if (pos < raw.size) - codepoint |= UInt32(ptr[pos]) << (j * 8); - } - - AppendRaw(codepoint); - } - - return offset; - } -} diff --git a/src/Nazara/Shader/SpirvWriter.cpp b/src/Nazara/Shader/SpirvWriter.cpp deleted file mode 100644 index 830ba5be0..000000000 --- a/src/Nazara/Shader/SpirvWriter.cpp +++ /dev/null @@ -1,741 +0,0 @@ -// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) -// This file is part of the "Nazara Engine - Shader module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - namespace - { - struct SpirvBuiltin - { - const char* debugName; - ShaderStageTypeFlags compatibleStages; - SpirvBuiltIn decoration; - }; - - constexpr auto s_spirvBuiltinMapping = frozen::make_unordered_map({ - { ShaderAst::BuiltinEntry::FragCoord, { "FragmentCoordinates", ShaderStageType::Fragment, SpirvBuiltIn::FragCoord } }, - { ShaderAst::BuiltinEntry::FragDepth, { "FragmentDepth", ShaderStageType::Fragment, SpirvBuiltIn::FragDepth } }, - { ShaderAst::BuiltinEntry::VertexPosition, { "VertexPosition", ShaderStageType::Vertex, SpirvBuiltIn::Position } } - }); - - class SpirvPreVisitor : public ShaderAst::AstRecursiveVisitor - { - public: - struct UniformVar - { - UInt32 bindingIndex; - UInt32 descriptorSet; - UInt32 pointerId; - }; - - using BuiltinDecoration = std::map; - using LocationDecoration = std::map; - using ExtInstList = std::unordered_set; - using ExtVarContainer = std::unordered_map; - using LocalContainer = std::unordered_set; - using FunctionContainer = std::vector>; - using StructContainer = std::vector; - - SpirvPreVisitor(SpirvConstantCache& constantCache, std::unordered_map& funcs) : - m_constantCache(constantCache), - m_funcs(funcs) - { - m_constantCache.SetStructCallback([this](std::size_t structIndex) -> const ShaderAst::StructDescription& - { - assert(structIndex < declaredStructs.size()); - return *declaredStructs[structIndex]; - }); - } - - void Visit(ShaderAst::AccessIndexExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - m_constantCache.Register(*m_constantCache.BuildType(node.cachedExpressionType.value())); - } - - void Visit(ShaderAst::BinaryExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - m_constantCache.Register(*m_constantCache.BuildType(node.cachedExpressionType.value())); - } - - void Visit(ShaderAst::CallFunctionExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - assert(m_funcIndex); - auto& func = Retrieve(m_funcs, *m_funcIndex); - - auto& funcCall = func.funcCalls.emplace_back(); - funcCall.firstVarIndex = func.variables.size(); - - for (const auto& parameter : node.parameters) - { - auto& var = func.variables.emplace_back(); - var.typeId = m_constantCache.Register(*m_constantCache.BuildPointerType(*GetExpressionType(*parameter), SpirvStorageClass::Function)); - } - } - - void Visit(ShaderAst::ConditionalExpression& /*node*/) override - { - throw std::runtime_error("unexpected conditional expression, did you forget to sanitize the shader?"); - } - - void Visit(ShaderAst::ConditionalStatement& /*node*/) override - { - throw std::runtime_error("unexpected conditional expression, did you forget to sanitize the shader?"); - } - - void Visit(ShaderAst::ConstantValueExpression& node) override - { - std::visit([&](auto&& arg) - { - m_constantCache.Register(*m_constantCache.BuildConstant(arg)); - }, node.value); - - AstRecursiveVisitor::Visit(node); - } - - void Visit(ShaderAst::DeclareExternalStatement& node) override - { - for (auto& extVar : node.externalVars) - { - SpirvConstantCache::Variable variable; - variable.debugName = extVar.name; - - const ShaderAst::ExpressionType& extVarType = extVar.type.GetResultingValue(); - - if (ShaderAst::IsSamplerType(extVarType)) - { - variable.storageClass = SpirvStorageClass::UniformConstant; - variable.type = m_constantCache.BuildPointerType(extVarType, variable.storageClass); - } - else - { - assert(ShaderAst::IsUniformType(extVarType)); - const auto& uniformType = std::get(extVarType); - const auto& structType = uniformType.containedType; - assert(structType.structIndex < declaredStructs.size()); - const auto& type = m_constantCache.BuildType(*declaredStructs[structType.structIndex], { SpirvDecoration::Block }); - - variable.storageClass = SpirvStorageClass::Uniform; - variable.type = m_constantCache.BuildPointerType(type, variable.storageClass); - } - - assert(extVar.bindingIndex.IsResultingValue()); - - assert(extVar.varIndex); - UniformVar& uniformVar = extVars[*extVar.varIndex]; - uniformVar.pointerId = m_constantCache.Register(variable); - uniformVar.bindingIndex = extVar.bindingIndex.GetResultingValue(); - uniformVar.descriptorSet = (extVar.bindingSet.HasValue()) ? extVar.bindingSet.GetResultingValue() : 0; - } - } - - void Visit(ShaderAst::DeclareFunctionStatement& node) override - { - std::optional entryPointType; - if (node.entryStage.HasValue()) - entryPointType = node.entryStage.GetResultingValue(); - - assert(node.funcIndex); - std::size_t funcIndex = *node.funcIndex; - - auto& funcData = m_funcs[funcIndex]; - funcData.name = node.name; - funcData.funcIndex = funcIndex; - - if (!entryPointType) - { - std::vector parameterTypes; - for (auto& parameter : node.parameters) - parameterTypes.push_back(parameter.type.GetResultingValue()); - - if (node.returnType.HasValue()) - { - const auto& returnType = node.returnType.GetResultingValue(); - funcData.returnTypeId = m_constantCache.Register(*m_constantCache.BuildType(returnType)); - funcData.funcTypeId = m_constantCache.Register(*m_constantCache.BuildFunctionType(returnType, parameterTypes)); - } - else - { - funcData.returnTypeId = m_constantCache.Register(*m_constantCache.BuildType(ShaderAst::NoType{})); - funcData.funcTypeId = m_constantCache.Register(*m_constantCache.BuildFunctionType(ShaderAst::NoType{}, parameterTypes)); - } - - for (auto& parameter : node.parameters) - { - const auto& parameterType = parameter.type.GetResultingValue(); - - auto& funcParam = funcData.parameters.emplace_back(); - funcParam.pointerTypeId = m_constantCache.Register(*m_constantCache.BuildPointerType(parameterType, SpirvStorageClass::Function)); - funcParam.typeId = m_constantCache.Register(*m_constantCache.BuildType(parameterType)); - } - } - else - { - using EntryPoint = SpirvAstVisitor::EntryPoint; - - std::vector executionModes; - - if (*entryPointType == ShaderStageType::Fragment) - { - executionModes.push_back(SpirvExecutionMode::OriginUpperLeft); - if (node.earlyFragmentTests.HasValue() && node.earlyFragmentTests.GetResultingValue()) - executionModes.push_back(SpirvExecutionMode::EarlyFragmentTests); - - if (node.depthWrite.HasValue()) - { - executionModes.push_back(SpirvExecutionMode::DepthReplacing); - - switch (node.depthWrite.GetResultingValue()) - { - case ShaderAst::DepthWriteMode::Replace: break; - case ShaderAst::DepthWriteMode::Greater: executionModes.push_back(SpirvExecutionMode::DepthGreater); break; - case ShaderAst::DepthWriteMode::Less: executionModes.push_back(SpirvExecutionMode::DepthLess); break; - case ShaderAst::DepthWriteMode::Unchanged: executionModes.push_back(SpirvExecutionMode::DepthUnchanged); break; - } - } - } - - funcData.returnTypeId = m_constantCache.Register(*m_constantCache.BuildType(ShaderAst::NoType{})); - funcData.funcTypeId = m_constantCache.Register(*m_constantCache.BuildFunctionType(ShaderAst::NoType{}, {})); - - std::optional inputStruct; - std::vector inputs; - if (!node.parameters.empty()) - { - assert(node.parameters.size() == 1); - auto& parameter = node.parameters.front(); - const auto& parameterType = parameter.type.GetResultingValue(); - - assert(std::holds_alternative(parameterType)); - - std::size_t structIndex = std::get(parameterType).structIndex; - const ShaderAst::StructDescription* structDesc = declaredStructs[structIndex]; - - std::size_t memberIndex = 0; - for (const auto& member : structDesc->members) - { - if (member.cond.HasValue() && !member.cond.GetResultingValue()) - continue; - - if (UInt32 varId = HandleEntryInOutType(*entryPointType, funcIndex, member, SpirvStorageClass::Input); varId != 0) - { - inputs.push_back({ - m_constantCache.Register(*m_constantCache.BuildConstant(Int32(memberIndex))), - m_constantCache.Register(*m_constantCache.BuildPointerType(member.type.GetResultingValue(), SpirvStorageClass::Function)), - varId - }); - } - - memberIndex++; - } - - inputStruct = EntryPoint::InputStruct{ - m_constantCache.Register(*m_constantCache.BuildPointerType(parameterType, SpirvStorageClass::Function)), - m_constantCache.Register(*m_constantCache.BuildType(parameter.type.GetResultingValue())) - }; - } - - std::optional outputStructId; - std::vector outputs; - if (node.returnType.HasValue() && !IsNoType(node.returnType.GetResultingValue())) - { - const ShaderAst::ExpressionType& returnType = node.returnType.GetResultingValue(); - - assert(std::holds_alternative(returnType)); - - std::size_t structIndex = std::get(returnType).structIndex; - const ShaderAst::StructDescription* structDesc = declaredStructs[structIndex]; - - std::size_t memberIndex = 0; - for (const auto& member : structDesc->members) - { - if (member.cond.HasValue() && !member.cond.GetResultingValue()) - continue; - - if (UInt32 varId = HandleEntryInOutType(*entryPointType, funcIndex, member, SpirvStorageClass::Output); varId != 0) - { - outputs.push_back({ - Int32(memberIndex), - m_constantCache.Register(*m_constantCache.BuildType(member.type.GetResultingValue())), - varId - }); - } - - memberIndex++; - } - - outputStructId = m_constantCache.Register(*m_constantCache.BuildType(returnType)); - } - - funcData.entryPointData = EntryPoint{ - *entryPointType, - inputStruct, - outputStructId, - std::move(inputs), - std::move(outputs), - std::move(executionModes) - }; - } - - m_funcIndex = funcIndex; - AstRecursiveVisitor::Visit(node); - m_funcIndex.reset(); - } - - void Visit(ShaderAst::DeclareStructStatement& node) override - { - AstRecursiveVisitor::Visit(node); - - assert(node.structIndex); - std::size_t structIndex = *node.structIndex; - if (structIndex >= declaredStructs.size()) - declaredStructs.resize(structIndex + 1); - - declaredStructs[structIndex] = &node.description; - - m_constantCache.Register(*m_constantCache.BuildType(node.description)); - } - - void Visit(ShaderAst::DeclareVariableStatement& node) override - { - AstRecursiveVisitor::Visit(node); - - assert(m_funcIndex); - auto& func = m_funcs[*m_funcIndex]; - - assert(node.varIndex); - func.varIndexToVarId[*node.varIndex] = func.variables.size(); - - auto& var = func.variables.emplace_back(); - var.typeId = m_constantCache.Register(*m_constantCache.BuildPointerType(node.varType.GetResultingValue(), SpirvStorageClass::Function)); - } - - void Visit(ShaderAst::IdentifierExpression& node) override - { - m_constantCache.Register(*m_constantCache.BuildType(node.cachedExpressionType.value())); - - AstRecursiveVisitor::Visit(node); - } - - void Visit(ShaderAst::IntrinsicExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - switch (node.intrinsic) - { - // Require GLSL.std.450 - case ShaderAst::IntrinsicType::CrossProduct: - case ShaderAst::IntrinsicType::Exp: - case ShaderAst::IntrinsicType::Length: - case ShaderAst::IntrinsicType::Max: - case ShaderAst::IntrinsicType::Min: - case ShaderAst::IntrinsicType::Normalize: - case ShaderAst::IntrinsicType::Pow: - case ShaderAst::IntrinsicType::Reflect: - extInsts.emplace("GLSL.std.450"); - break; - - // Part of SPIR-V core - case ShaderAst::IntrinsicType::DotProduct: - case ShaderAst::IntrinsicType::SampleTexture: - break; - } - - m_constantCache.Register(*m_constantCache.BuildType(node.cachedExpressionType.value())); - } - - void Visit(ShaderAst::SwizzleExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - for (std::size_t i = 0; i < node.componentCount; ++i) - { - Int32 indexCount = SafeCast(node.components[i]); - m_constantCache.Register(*m_constantCache.BuildConstant(indexCount)); - } - - m_constantCache.Register(*m_constantCache.BuildType(node.cachedExpressionType.value())); - } - - void Visit(ShaderAst::UnaryExpression& node) override - { - AstRecursiveVisitor::Visit(node); - - m_constantCache.Register(*m_constantCache.BuildType(node.cachedExpressionType.value())); - } - - UInt32 HandleEntryInOutType(ShaderStageType entryPointType, std::size_t funcIndex, const ShaderAst::StructDescription::StructMember& member, SpirvStorageClass storageClass) - { - if (member.builtin.HasValue()) - { - auto it = s_spirvBuiltinMapping.find(member.builtin.GetResultingValue()); - assert(it != s_spirvBuiltinMapping.end()); - - const SpirvBuiltin& builtin = it->second; - if ((builtin.compatibleStages & entryPointType) == 0) - return 0; - - SpirvBuiltIn builtinDecoration = builtin.decoration; - - SpirvConstantCache::Variable variable; - variable.debugName = builtin.debugName; - variable.funcId = funcIndex; - variable.storageClass = storageClass; - variable.type = m_constantCache.BuildPointerType(member.type.GetResultingValue(), storageClass); - - UInt32 varId = m_constantCache.Register(variable); - builtinDecorations[varId] = builtinDecoration; - - return varId; - } - else if (member.locationIndex.HasValue()) - { - SpirvConstantCache::Variable variable; - variable.debugName = member.name; - variable.funcId = funcIndex; - variable.storageClass = storageClass; - variable.type = m_constantCache.BuildPointerType(member.type.GetResultingValue(), storageClass); - - UInt32 varId = m_constantCache.Register(variable); - locationDecorations[varId] = member.locationIndex.GetResultingValue(); - - return varId; - } - - return 0; - } - - BuiltinDecoration builtinDecorations; - ExtInstList extInsts; - ExtVarContainer extVars; - LocationDecoration locationDecorations; - StructContainer declaredStructs; - - private: - SpirvConstantCache& m_constantCache; - std::optional m_funcIndex; - std::unordered_map& m_funcs; - }; - } - - struct SpirvWriter::State - { - State() : - constantTypeCache(nextVarIndex) - { - } - - struct Func - { - const ShaderAst::DeclareFunctionStatement* statement = nullptr; - UInt32 typeId; - UInt32 id; - }; - - std::unordered_map extensionInstructionSet; - std::unordered_map varToResult; - std::unordered_map funcs; - std::vector resultIds; - UInt32 nextVarIndex = 1; - SpirvConstantCache constantTypeCache; //< init after nextVarIndex - SpirvPreVisitor* previsitor; - - // Output - SpirvSection header; - SpirvSection constants; - SpirvSection debugInfo; - SpirvSection annotations; - SpirvSection instructions; - }; - - SpirvWriter::SpirvWriter() : - m_currentState(nullptr) - { - } - - std::vector SpirvWriter::Generate(const ShaderAst::Module& module, const States& states) - { - ShaderAst::ModulePtr sanitizedModule; - const ShaderAst::Module* targetModule; - if (!states.sanitized) - { - ShaderAst::SanitizeVisitor::Options options; - options.moduleResolver = states.shaderModuleResolver; - options.optionValues = states.optionValues; - options.reduceLoopsToWhile = true; - options.removeAliases = true; - options.removeCompoundAssignments = true; - options.removeConstDeclaration = true; - options.removeMatrixCast = true; - options.removeOptionDeclaration = true; - options.splitMultipleBranches = true; - options.useIdentifierAccessesForStructs = false; - - sanitizedModule = ShaderAst::Sanitize(module, options); - targetModule = sanitizedModule.get(); - } - else - targetModule = &module; - - ShaderAst::ModulePtr optimizedModule; - if (states.optimize) - { - ShaderAst::StatementPtr tempAst; - - ShaderAst::DependencyCheckerVisitor::Config dependencyConfig; - dependencyConfig.usedShaderStages = ShaderStageType_All; - - optimizedModule = ShaderAst::PropagateConstants(*targetModule); - optimizedModule = ShaderAst::EliminateUnusedPass(*optimizedModule, dependencyConfig); - - targetModule = optimizedModule.get(); - } - - // Previsitor - - m_context.states = &states; - - State state; - m_currentState = &state; - CallOnExit onExit([this]() - { - m_currentState = nullptr; - }); - - // Register all extended instruction sets - SpirvPreVisitor previsitor(state.constantTypeCache, state.funcs); - for (const auto& importedModule : targetModule->importedModules) - importedModule.module->rootNode->Visit(previsitor); - - targetModule->rootNode->Visit(previsitor); - - m_currentState->previsitor = &previsitor; - - for (const std::string& extInst : previsitor.extInsts) - state.extensionInstructionSet[extInst] = AllocateResultId(); - - // Assign function ID (required for forward declaration) - for (auto&& [funcIndex, func] : state.funcs) - func.funcId = AllocateResultId(); - - SpirvAstVisitor visitor(*this, state.instructions, state.funcs); - for (const auto& importedModule : targetModule->importedModules) - importedModule.module->rootNode->Visit(visitor); - - targetModule->rootNode->Visit(visitor); - - AppendHeader(); - - for (auto&& [varIndex, extVar] : previsitor.extVars) - { - state.annotations.Append(SpirvOp::OpDecorate, extVar.pointerId, SpirvDecoration::Binding, extVar.bindingIndex); - state.annotations.Append(SpirvOp::OpDecorate, extVar.pointerId, SpirvDecoration::DescriptorSet, extVar.descriptorSet); - } - - for (auto&& [varId, builtin] : previsitor.builtinDecorations) - state.annotations.Append(SpirvOp::OpDecorate, varId, SpirvDecoration::BuiltIn, builtin); - - for (auto&& [varId, location] : previsitor.locationDecorations) - state.annotations.Append(SpirvOp::OpDecorate, varId, SpirvDecoration::Location, location); - - m_currentState->constantTypeCache.Write(m_currentState->annotations, m_currentState->constants, m_currentState->debugInfo); - - std::vector ret; - MergeSections(ret, state.header); - MergeSections(ret, state.debugInfo); - MergeSections(ret, state.annotations); - MergeSections(ret, state.constants); - MergeSections(ret, state.instructions); - - return ret; - } - - void SpirvWriter::SetEnv(Environment environment) - { - m_environment = std::move(environment); - } - - UInt32 SpirvWriter::AllocateResultId() - { - return m_currentState->nextVarIndex++; - } - - void SpirvWriter::AppendHeader() - { - m_currentState->header.AppendRaw(SpirvMagicNumber); //< Spir-V magic number - - UInt32 version = (m_environment.spvMajorVersion << 16) | m_environment.spvMinorVersion << 8; - m_currentState->header.AppendRaw(version); //< Spir-V version number (1.0 for compatibility) - m_currentState->header.AppendRaw(0); //< Generator identifier (TODO: Register generator to Khronos) - - m_currentState->header.AppendRaw(m_currentState->nextVarIndex); //< Bound (ID count) - m_currentState->header.AppendRaw(0); //< Instruction schema (required to be 0 for now) - - m_currentState->header.Append(SpirvOp::OpCapability, SpirvCapability::Shader); - - for (const auto& [extInst, resultId] : m_currentState->extensionInstructionSet) - m_currentState->header.Append(SpirvOp::OpExtInstImport, resultId, extInst); - - m_currentState->header.Append(SpirvOp::OpMemoryModel, SpirvAddressingModel::Logical, SpirvMemoryModel::GLSL450); - - for (auto&& [funcIndex, func] : m_currentState->funcs) - { - m_currentState->debugInfo.Append(SpirvOp::OpName, func.funcId, func.name); - - if (func.entryPointData) - { - auto& entryPointData = func.entryPointData.value(); - - SpirvExecutionModel execModel; - - switch (entryPointData.stageType) - { - case ShaderStageType::Fragment: - execModel = SpirvExecutionModel::Fragment; - break; - - case ShaderStageType::Vertex: - execModel = SpirvExecutionModel::Vertex; - break; - - default: - throw std::runtime_error("not yet implemented"); - } - - auto& funcData = func; - m_currentState->header.AppendVariadic(SpirvOp::OpEntryPoint, [&](const auto& appender) - { - appender(execModel); - appender(funcData.funcId); - appender(funcData.name); - - for (const auto& input : entryPointData.inputs) - appender(input.varId); - - for (const auto& output : entryPointData.outputs) - appender(output.varId); - }); - } - } - - // Write execution modes - for (auto&& [funcIndex, func] : m_currentState->funcs) - { - if (func.entryPointData) - { - for (SpirvExecutionMode executionMode : func.entryPointData->executionModes) - m_currentState->header.Append(SpirvOp::OpExecutionMode, func.funcId, executionMode); - } - } - } - - SpirvConstantCache::TypePtr SpirvWriter::BuildFunctionType(const ShaderAst::DeclareFunctionStatement& functionNode) - { - std::vector parameterTypes; - parameterTypes.reserve(functionNode.parameters.size()); - - for (const auto& parameter : functionNode.parameters) - parameterTypes.push_back(parameter.type.GetResultingValue()); - - if (functionNode.returnType.HasValue()) - return m_currentState->constantTypeCache.BuildFunctionType(functionNode.returnType.GetResultingValue(), parameterTypes); - else - return m_currentState->constantTypeCache.BuildFunctionType(ShaderAst::NoType{}, parameterTypes); - } - - UInt32 SpirvWriter::GetConstantId(const ShaderAst::ConstantValue& value) const - { - return m_currentState->constantTypeCache.GetId(*m_currentState->constantTypeCache.BuildConstant(value)); - } - - UInt32 SpirvWriter::GetExtendedInstructionSet(const std::string& instructionSetName) const - { - auto it = m_currentState->extensionInstructionSet.find(instructionSetName); - assert(it != m_currentState->extensionInstructionSet.end()); - - return it->second; - } - - UInt32 SpirvWriter::GetExtVarPointerId(std::size_t extVarIndex) const - { - auto it = m_currentState->previsitor->extVars.find(extVarIndex); - assert(it != m_currentState->previsitor->extVars.end()); - - return it->second.pointerId; - } - - UInt32 SpirvWriter::GetFunctionTypeId(const ShaderAst::DeclareFunctionStatement& functionNode) - { - return m_currentState->constantTypeCache.GetId({ *BuildFunctionType(functionNode) }); - } - - UInt32 SpirvWriter::GetPointerTypeId(const ShaderAst::ExpressionType& type, SpirvStorageClass storageClass) const - { - return m_currentState->constantTypeCache.GetId(*m_currentState->constantTypeCache.BuildPointerType(type, storageClass)); - } - - UInt32 SpirvWriter::GetTypeId(const ShaderAst::ExpressionType& type) const - { - return m_currentState->constantTypeCache.GetId(*m_currentState->constantTypeCache.BuildType(type)); - } - - UInt32 SpirvWriter::RegisterConstant(const ShaderAst::ConstantValue& value) - { - return m_currentState->constantTypeCache.Register(*m_currentState->constantTypeCache.BuildConstant(value)); - } - - UInt32 SpirvWriter::RegisterFunctionType(const ShaderAst::DeclareFunctionStatement& functionNode) - { - return m_currentState->constantTypeCache.Register({ *BuildFunctionType(functionNode) }); - } - - UInt32 SpirvWriter::RegisterPointerType(ShaderAst::ExpressionType type, SpirvStorageClass storageClass) - { - return m_currentState->constantTypeCache.Register(*m_currentState->constantTypeCache.BuildPointerType(type, storageClass)); - } - - UInt32 SpirvWriter::RegisterType(ShaderAst::ExpressionType type) - { - assert(m_currentState); - return m_currentState->constantTypeCache.Register(*m_currentState->constantTypeCache.BuildType(type)); - } - - void SpirvWriter::MergeSections(std::vector& output, const SpirvSection& from) - { - const std::vector& bytecode = from.GetBytecode(); - - std::size_t prevSize = output.size(); - output.resize(prevSize + bytecode.size()); - std::copy(bytecode.begin(), bytecode.end(), output.begin() + prevSize); - } -} diff --git a/src/Nazara/Utility/AlgorithmUtility.cpp b/src/Nazara/Utility/AlgorithmUtility.cpp index c76309014..6dbd5a208 100644 --- a/src/Nazara/Utility/AlgorithmUtility.cpp +++ b/src/Nazara/Utility/AlgorithmUtility.cpp @@ -25,8 +25,8 @@ * THE SOFTWARE. */ -#include #include +#include #include #include #include diff --git a/src/Nazara/Utility/Formats/FreeTypeLoader.cpp b/src/Nazara/Utility/Formats/FreeTypeLoader.cpp index 88338e6a1..4afd72a10 100644 --- a/src/Nazara/Utility/Formats/FreeTypeLoader.cpp +++ b/src/Nazara/Utility/Formats/FreeTypeLoader.cpp @@ -8,7 +8,7 @@ #include FT_BITMAP_H #include FT_STROKER_H #include FT_OUTLINE_H -#include +#include #include #include #include diff --git a/src/Nazara/Utility/Formats/GIFLoader.cpp b/src/Nazara/Utility/Formats/GIFLoader.cpp index 63e26e91f..bf8680758 100644 --- a/src/Nazara/Utility/Formats/GIFLoader.cpp +++ b/src/Nazara/Utility/Formats/GIFLoader.cpp @@ -3,14 +3,14 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include -#include -#include #include #include #include #include +#include +#include +#include #include // based on https://www.w3.org/Graphics/GIF/spec-gif89a.txt, with help from the following public domain libraries source code: diff --git a/src/Nazara/Utility/Formats/MD2Loader.cpp b/src/Nazara/Utility/Formats/MD2Loader.cpp index f2a802f69..5d04d98b9 100644 --- a/src/Nazara/Utility/Formats/MD2Loader.cpp +++ b/src/Nazara/Utility/Formats/MD2Loader.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -12,6 +11,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Nazara/Utility/Formats/MTLParser.cpp b/src/Nazara/Utility/Formats/MTLParser.cpp index 03b39bda0..ac3e6949c 100644 --- a/src/Nazara/Utility/Formats/MTLParser.cpp +++ b/src/Nazara/Utility/Formats/MTLParser.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include +#include #include #include diff --git a/src/Nazara/Utility/Formats/OBJParser.cpp b/src/Nazara/Utility/Formats/OBJParser.cpp index ca7dbd49f..31056d85d 100644 --- a/src/Nazara/Utility/Formats/OBJParser.cpp +++ b/src/Nazara/Utility/Formats/OBJParser.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include +#include #include #include #include @@ -515,7 +515,7 @@ namespace Nz Emit("# position count: "); EmitLine(m_positions.size()); - for (const Nz::Vector4f& position : m_positions) + for (const Vector4f& position : m_positions) { Emit("v "); Emit(position.x); diff --git a/src/Nazara/Utility/Formats/PCXLoader.cpp b/src/Nazara/Utility/Formats/PCXLoader.cpp index 7111a8293..316d9539f 100644 --- a/src/Nazara/Utility/Formats/PCXLoader.cpp +++ b/src/Nazara/Utility/Formats/PCXLoader.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include #include diff --git a/src/Nazara/Utility/Formats/STBLoader.cpp b/src/Nazara/Utility/Formats/STBLoader.cpp index 1f08e3412..4240d2eda 100644 --- a/src/Nazara/Utility/Formats/STBLoader.cpp +++ b/src/Nazara/Utility/Formats/STBLoader.cpp @@ -3,11 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include #include #include +#include +#include #include #include #define STB_IMAGE_IMPLEMENTATION diff --git a/src/Nazara/Utility/PixelFormat.cpp b/src/Nazara/Utility/PixelFormat.cpp index 42664e5a0..ea80f63a3 100644 --- a/src/Nazara/Utility/PixelFormat.cpp +++ b/src/Nazara/Utility/PixelFormat.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include +#include +#include #include namespace Nz diff --git a/src/Nazara/Utility/Utility.cpp b/src/Nazara/Utility/Utility.cpp index dc019bbbc..d5171afcc 100644 --- a/src/Nazara/Utility/Utility.cpp +++ b/src/Nazara/Utility/Utility.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -26,6 +25,7 @@ #include #include #include +#include #include #include diff --git a/src/Nazara/Utility/VertexDeclaration.cpp b/src/Nazara/Utility/VertexDeclaration.cpp index d2fd0ca21..18556dbff 100644 --- a/src/Nazara/Utility/VertexDeclaration.cpp +++ b/src/Nazara/Utility/VertexDeclaration.cpp @@ -5,11 +5,11 @@ #include #include #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/VulkanRenderer/Vulkan.cpp b/src/Nazara/VulkanRenderer/Vulkan.cpp index 661d17e30..5c181623e 100644 --- a/src/Nazara/VulkanRenderer/Vulkan.cpp +++ b/src/Nazara/VulkanRenderer/Vulkan.cpp @@ -3,13 +3,13 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include #include +#include #include #include #include diff --git a/src/Nazara/VulkanRenderer/VulkanBuffer.cpp b/src/Nazara/VulkanRenderer/VulkanBuffer.cpp index cdffd37a0..9ffc2e8b5 100644 --- a/src/Nazara/VulkanRenderer/VulkanBuffer.cpp +++ b/src/Nazara/VulkanRenderer/VulkanBuffer.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include #include diff --git a/src/Nazara/VulkanRenderer/VulkanCommandBufferBuilder.cpp b/src/Nazara/VulkanRenderer/VulkanCommandBufferBuilder.cpp index b341cf01c..3dd5b28e2 100644 --- a/src/Nazara/VulkanRenderer/VulkanCommandBufferBuilder.cpp +++ b/src/Nazara/VulkanRenderer/VulkanCommandBufferBuilder.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -14,6 +13,7 @@ #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/VulkanRenderer/VulkanCommandPool.cpp b/src/Nazara/VulkanRenderer/VulkanCommandPool.cpp index 0167ae880..61458df38 100644 --- a/src/Nazara/VulkanRenderer/VulkanCommandPool.cpp +++ b/src/Nazara/VulkanRenderer/VulkanCommandPool.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/VulkanRenderer/VulkanDevice.cpp b/src/Nazara/VulkanRenderer/VulkanDevice.cpp index 74288070c..c4d757b77 100644 --- a/src/Nazara/VulkanRenderer/VulkanDevice.cpp +++ b/src/Nazara/VulkanRenderer/VulkanDevice.cpp @@ -61,7 +61,7 @@ namespace Nz return pipelineLayout; } - std::shared_ptr VulkanDevice::InstantiateShaderModule(ShaderStageTypeFlags stages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) + std::shared_ptr VulkanDevice::InstantiateShaderModule(nzsl::ShaderStageTypeFlags stages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) { auto stage = std::make_shared(); if (!stage->Create(*this, stages, shaderModule, states)) @@ -70,7 +70,7 @@ namespace Nz return stage; } - std::shared_ptr VulkanDevice::InstantiateShaderModule(ShaderStageTypeFlags stages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) + std::shared_ptr VulkanDevice::InstantiateShaderModule(nzsl::ShaderStageTypeFlags stages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) { auto stage = std::make_shared(); if (!stage->Create(*this, stages, lang, source, sourceSize, states)) diff --git a/src/Nazara/VulkanRenderer/VulkanRenderPass.cpp b/src/Nazara/VulkanRenderer/VulkanRenderPass.cpp index 58356145e..3a57cbd0f 100644 --- a/src/Nazara/VulkanRenderer/VulkanRenderPass.cpp +++ b/src/Nazara/VulkanRenderer/VulkanRenderPass.cpp @@ -3,8 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include +#include #include #include diff --git a/src/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.cpp b/src/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.cpp index 63217da79..ac2866b38 100644 --- a/src/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.cpp +++ b/src/Nazara/VulkanRenderer/VulkanRenderPipelineLayout.cpp @@ -4,11 +4,11 @@ #include #include -#include -#include -#include #include #include +#include +#include +#include #include #include #include diff --git a/src/Nazara/VulkanRenderer/VulkanRenderWindow.cpp b/src/Nazara/VulkanRenderer/VulkanRenderWindow.cpp index 76d014f37..97d614a07 100644 --- a/src/Nazara/VulkanRenderer/VulkanRenderWindow.cpp +++ b/src/Nazara/VulkanRenderer/VulkanRenderWindow.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -13,6 +12,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Nazara/VulkanRenderer/VulkanShaderBinding.cpp b/src/Nazara/VulkanRenderer/VulkanShaderBinding.cpp index 7f0b936ce..f8b79f5da 100644 --- a/src/Nazara/VulkanRenderer/VulkanShaderBinding.cpp +++ b/src/Nazara/VulkanRenderer/VulkanShaderBinding.cpp @@ -4,11 +4,11 @@ #include #include -#include #include #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/VulkanRenderer/VulkanShaderModule.cpp b/src/Nazara/VulkanRenderer/VulkanShaderModule.cpp index 5969ece38..07e782247 100644 --- a/src/Nazara/VulkanRenderer/VulkanShaderModule.cpp +++ b/src/Nazara/VulkanRenderer/VulkanShaderModule.cpp @@ -3,41 +3,41 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace Nz { namespace { - struct SpirvEntryPointExtractor : SpirvDecoder + struct SpirvEntryPointExtractor : nzsl::SpirvDecoder { struct EntryPoint { - SpirvExecutionModel executionModel; + nzsl::SpirvExecutionModel executionModel; std::string name; }; std::vector entryPoints; - bool HandleOpcode(const SpirvInstruction& instruction, UInt32 /*wordCount*/) override + bool HandleOpcode(const nzsl::SpirvInstruction& instruction, UInt32 /*wordCount*/) override { switch (instruction.op) { // All instructions that can appear before OpEntryPoint - case SpirvOp::OpCapability: - case SpirvOp::OpExtension: - case SpirvOp::OpExtInstImport: - case SpirvOp::OpMemoryModel: + case nzsl::SpirvOp::OpCapability: + case nzsl::SpirvOp::OpExtension: + case nzsl::SpirvOp::OpExtInstImport: + case nzsl::SpirvOp::OpMemoryModel: return true; - case SpirvOp::OpEntryPoint: + case nzsl::SpirvOp::OpEntryPoint: { - SpirvExecutionModel executionModel = static_cast(ReadWord()); + nzsl::SpirvExecutionModel executionModel = static_cast(ReadWord()); ReadWord(); // func id std::string name = ReadString(); @@ -57,18 +57,18 @@ namespace Nz }; } - bool VulkanShaderModule::Create(Vk::Device& device, ShaderStageTypeFlags shaderStages, const ShaderAst::Module& shaderModule, const ShaderWriter::States& states) + bool VulkanShaderModule::Create(Vk::Device& device, nzsl::ShaderStageTypeFlags shaderStages, const nzsl::Ast::Module& shaderModule, const nzsl::ShaderWriter::States& states) { - SpirvWriter::Environment env; + nzsl::SpirvWriter::Environment env; - SpirvWriter writer; + nzsl::SpirvWriter writer; writer.SetEnv(env); std::vector code = writer.Generate(shaderModule, states); return Create(device, shaderStages, ShaderLanguage::SpirV, code.data(), code.size() * sizeof(UInt32), {}); } - bool VulkanShaderModule::Create(Vk::Device& device, ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) + bool VulkanShaderModule::Create(Vk::Device& device, nzsl::ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const nzsl::ShaderWriter::States& states) { switch (lang) { @@ -79,16 +79,17 @@ namespace Nz case ShaderLanguage::NazaraBinary: { - auto shader = ShaderAst::UnserializeShader(source, sourceSize); + nzsl::Unserializer unserializer(source, sourceSize); + auto shader = nzsl::Ast::UnserializeShader(unserializer); return Create(device, shaderStages, *shader, {}); } case ShaderLanguage::NazaraShader: { - std::vector tokens = ShaderLang::Tokenize(std::string_view(static_cast(source), sourceSize)); + std::vector tokens = nzsl::Tokenize(std::string_view(static_cast(source), sourceSize)); - ShaderLang::Parser parser; - ShaderAst::ModulePtr shaderModule = parser.Parse(tokens); + nzsl::Parser parser; + nzsl::Ast::ModulePtr shaderModule = parser.Parse(tokens); return Create(device, shaderStages, *shaderModule, states); } @@ -97,18 +98,18 @@ namespace Nz SpirvEntryPointExtractor extractor; extractor.Decode(reinterpret_cast(source), sourceSize / sizeof(UInt32)); - ShaderStageTypeFlags remainingStages = shaderStages; + nzsl::ShaderStageTypeFlags remainingStages = shaderStages; for (auto& entryPoint : extractor.entryPoints) { - ShaderStageType stageType; + nzsl::ShaderStageType stageType; switch (entryPoint.executionModel) { - case SpirvExecutionModel::Fragment: - stageType = ShaderStageType::Fragment; + case nzsl::SpirvExecutionModel::Fragment: + stageType = nzsl::ShaderStageType::Fragment; break; - case SpirvExecutionModel::Vertex: - stageType = ShaderStageType::Vertex; + case nzsl::SpirvExecutionModel::Vertex: + stageType = nzsl::ShaderStageType::Vertex; break; default: diff --git a/src/Nazara/VulkanRenderer/VulkanTexture.cpp b/src/Nazara/VulkanRenderer/VulkanTexture.cpp index a09736d95..856e84da1 100644 --- a/src/Nazara/VulkanRenderer/VulkanTexture.cpp +++ b/src/Nazara/VulkanRenderer/VulkanTexture.cpp @@ -3,10 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include +#include #include #include #include diff --git a/src/Nazara/VulkanRenderer/VulkanTextureFramebuffer.cpp b/src/Nazara/VulkanRenderer/VulkanTextureFramebuffer.cpp index b41a6a48e..cb017f4fb 100644 --- a/src/Nazara/VulkanRenderer/VulkanTextureFramebuffer.cpp +++ b/src/Nazara/VulkanRenderer/VulkanTextureFramebuffer.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include +#include #include #include diff --git a/src/Nazara/VulkanRenderer/Wrapper/Device.cpp b/src/Nazara/VulkanRenderer/Wrapper/Device.cpp index 93e0f4c71..0b89b57c8 100644 --- a/src/Nazara/VulkanRenderer/Wrapper/Device.cpp +++ b/src/Nazara/VulkanRenderer/Wrapper/Device.cpp @@ -3,13 +3,13 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include #include +#include #define VMA_IMPLEMENTATION #define VMA_USE_STL_CONTAINERS 1 diff --git a/src/ShaderCompiler/main.cpp b/src/ShaderCompiler/main.cpp deleted file mode 100644 index 04a3d9e24..000000000 --- a/src/ShaderCompiler/main.cpp +++ /dev/null @@ -1,262 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum class LogFormat -{ - Classic, - VisualStudio -}; - -std::vector ReadFileContent(const std::filesystem::path& filePath) -{ - Nz::File file(filePath); - if (!file.Open(Nz::OpenMode::ReadOnly | Nz::OpenMode::Text)) - throw std::runtime_error("failed to open " + filePath.generic_u8string()); - - std::size_t length = static_cast(file.GetSize()); - if (length == 0) - return {}; - - std::vector content(length); - if (file.Read(&content[0], length) != length) - throw std::runtime_error("failed to read " + filePath.generic_u8string()); - - return content; -} - -std::string ReadSourceFileContent(const std::filesystem::path& filePath) -{ - std::vector content = ReadFileContent(filePath); - return std::string(reinterpret_cast(&content[0]), content.size()); -} - -void WriteFileContent(std::filesystem::path& filePath, const void* data, std::size_t size) -{ - Nz::File file(filePath); - if (!file.Open(Nz::OpenMode::WriteOnly | Nz::OpenMode::Truncate)) - throw std::runtime_error("failed to open " + filePath.generic_u8string()); - - if (file.Write(data, size) != size) - throw std::runtime_error("failed to write " + filePath.generic_u8string()); -} - -int main(int argc, char* argv[]) -{ - cxxopts::Options options("nzslc", "Tool for validating and compiling NZSL shaders"); - options.add_options() - ("c,compile", "Compile input shader") - ("output-nzsl", "Output shader as NZSL to stdout") - ("header-file", "Generate an includable header file") - ("log-format", "Set log format (classic, vs)", cxxopts::value()) - ("i,input", "Input file(s)", cxxopts::value()) - ("o,output", "Output path", cxxopts::value()->default_value("."), "path") - ("p,partial", "Allow partial compilation") - ("s,show", "Show informations about the shader (default)") - ("h,help", "Print usage") - ; - - options.parse_positional("input"); - options.positional_help("shader path"); - - try - { - auto result = options.parse(argc, argv); - if (result.count("help") > 0) - { - fmt::print("{}\n", options.help()); - return EXIT_SUCCESS; - } - - if (result.count("input") == 0) - { - fmt::print(stderr, "no input file\n{}\n", options.help()); - return EXIT_SUCCESS; - } - - LogFormat logFormat = LogFormat::Classic; - if (result.count("log-format") != 0) - { - const std::string& formatStr = result["log-format"].as(); - if (formatStr == "vs") - logFormat = LogFormat::VisualStudio; - else if (formatStr != "classic") - { - fmt::print(stderr, "{} is not a file\n", formatStr); - return EXIT_FAILURE; - } - } - - std::filesystem::path inputPath = result["input"].as(); - if (!std::filesystem::is_regular_file(inputPath)) - { - fmt::print(stderr, "{} is not a file\n", inputPath.generic_u8string()); - return EXIT_FAILURE; - } - - try - { - Nz::ShaderAst::ModulePtr shaderModule; - if (inputPath.extension() == ".nzsl") - { - std::string sourceContent = ReadSourceFileContent(inputPath); - - std::vector tokens = Nz::ShaderLang::Tokenize(sourceContent, inputPath.generic_u8string()); - - shaderModule = Nz::ShaderLang::Parse(tokens); - } - else if (inputPath.extension() == ".nzslb") - { - std::vector sourceContent = ReadFileContent(inputPath); - - shaderModule = Nz::ShaderAst::UnserializeShader(sourceContent.data(), sourceContent.size()); - } - else - { - fmt::print("{} has unknown extension\n", inputPath.generic_u8string()); - return EXIT_FAILURE; - } - - if (result.count("compile") > 0) - { - Nz::ShaderAst::SanitizeVisitor::Options sanitizeOptions; - sanitizeOptions.allowPartialSanitization = result.count("partial") > 0; - - shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, sanitizeOptions); - - Nz::ByteArray shaderData = Nz::ShaderAst::SerializeShader(shaderModule); - - std::filesystem::path outputPath = inputPath; - if (result.count("header-file") > 0) - { - outputPath.replace_extension(".nzslb.h"); - - std::stringstream ss; - - bool first = true; - for (std::size_t i = 0; i < shaderData.size(); ++i) - { - if (!first) - ss << ','; - - ss << +shaderData[i]; - - first = false; - } - - std::string headerFile = std::move(ss).str(); - WriteFileContent(outputPath, headerFile.data(), headerFile.size()); - } - else - { - outputPath.replace_extension(".nzslb"); - WriteFileContent(outputPath, shaderData.GetConstBuffer(), shaderData.GetSize()); - } - } - - if (result.count("output-nzsl") > 0) - { - Nz::LangWriter nzslWriter; - fmt::print("{}", nzslWriter.Generate(*shaderModule)); - } - - return EXIT_SUCCESS; - } - catch (const Nz::ShaderLang::Error& error) - { - const Nz::ShaderLang::SourceLocation& errorLocation = error.GetSourceLocation(); - if (errorLocation.IsValid()) - { - if (logFormat == LogFormat::Classic) - { - fmt::print(stderr, (fmt::emphasis::bold | fg(fmt::color::red)), "{}\n", error.what()); - - try - { - // Retrieve line - std::string sourceContent = ReadSourceFileContent(*errorLocation.file); - - std::size_t lineStartOffset = 0; - if (errorLocation.startLine > 1) - { - lineStartOffset = sourceContent.find('\n') + 1; - for (std::size_t i = 0; i < errorLocation.startLine - 2; ++i) //< remember startLine is 1-based - { - lineStartOffset = sourceContent.find('\n', lineStartOffset); - if (lineStartOffset == std::string::npos) - throw std::runtime_error("file content doesn't match original source"); - - ++lineStartOffset; - } - } - std::size_t lineEndOffset = sourceContent.find('\n', lineStartOffset); - - std::string errorLine = sourceContent.substr(lineStartOffset, lineEndOffset - lineStartOffset); - - // handle tabs - Nz::UInt32 startColumn = errorLocation.startColumn - 1; - std::size_t startPos = 0; - while ((startPos = errorLine.find('\t', startPos)) != std::string::npos) - { - if (startPos < startColumn) - startColumn += 3; - - errorLine.replace(startPos, 1, " "); - startPos += 4; - } - - std::size_t columnSize; - if (errorLocation.startLine == errorLocation.endLine) - columnSize = errorLocation.endColumn - errorLocation.startColumn + 1; - else - columnSize = 1; - - std::string lineStr = std::to_string(errorLocation.startLine); - - fmt::print(stderr, " {} | {}\n", lineStr, errorLine); - fmt::print(stderr, " {} | {}", std::string(lineStr.size(), ' '), std::string(startColumn, ' ')); - fmt::print(stderr, fg(fmt::color::green), "{}\n", std::string(columnSize, '^')); - } - catch (const std::exception& e) - { - fmt::print(stderr, "failed to print error line: {}\n", e.what()); - } - } - else if (logFormat == LogFormat::VisualStudio) - { - // VS requires absolute path - std::filesystem::path fullPath; - if (errorLocation.file) - fullPath = std::filesystem::absolute(*errorLocation.file); - - fmt::print(stderr, "{}({},{}): error {}: {}\n", fullPath.generic_u8string(), errorLocation.startLine, errorLocation.startColumn, ToString(error.GetErrorType()), error.GetErrorMessage()); - } - } - else - fmt::print(stderr, (fmt::emphasis::bold | fg(fmt::color::red)), "{}\n", error.what()); - - return EXIT_FAILURE; - } - } - catch (const cxxopts::OptionException& e) - { - fmt::print(stderr, "{}\n{}\n", e.what(), options.help()); - return EXIT_FAILURE; - } - catch (const std::exception& e) - { - fmt::print(stderr, "{}\n", e.what()); - return EXIT_FAILURE; - } -} diff --git a/src/ShaderNode/DataModels/BinOp.hpp b/src/ShaderNode/DataModels/BinOp.hpp index e8dcfd8a1..ce4576f9f 100644 --- a/src/ShaderNode/DataModels/BinOp.hpp +++ b/src/ShaderNode/DataModels/BinOp.hpp @@ -7,14 +7,14 @@ #include #include -template +template class BinOp : public ShaderNode { public: BinOp(ShaderGraph& graph); ~BinOp() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; virtual QString GetOperationString() const = 0; @@ -33,7 +33,7 @@ class BinOp : public ShaderNode QString validationMessage() const override; private: - virtual void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) = 0; + virtual void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) = 0; bool ComputePreview(QPixmap& pixmap) override; void UpdateOutput(); @@ -45,42 +45,42 @@ class BinOp : public ShaderNode template -class BinAdd : public BinOp +class BinAdd : public BinOp { public: - using BinOp::BinOp; + using BinOp::BinOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class BinMul : public BinOp +class BinMul : public BinOp { public: - using BinOp::BinOp; + using BinOp::BinOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class BinSub : public BinOp +class BinSub : public BinOp { public: - using BinOp::BinOp; + using BinOp::BinOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class BinDiv : public BinOp +class BinDiv : public BinOp { public: - using BinOp::BinOp; + using BinOp::BinOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; diff --git a/src/ShaderNode/DataModels/BinOp.inl b/src/ShaderNode/DataModels/BinOp.inl index b91999e18..33fa64a99 100644 --- a/src/ShaderNode/DataModels/BinOp.inl +++ b/src/ShaderNode/DataModels/BinOp.inl @@ -1,23 +1,23 @@ #include -#include +#include -template +template BinOp::BinOp(ShaderGraph& graph) : ShaderNode(graph) { UpdateOutput(); } -template -Nz::ShaderAst::NodePtr BinOp::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +template +nzsl::Ast::NodePtr BinOp::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); - return Nz::ShaderBuilder::Binary(Op, std::move(expressions[0]), std::move(expressions[1])); + return nzsl::ShaderBuilder::Binary(Op, std::move(expressions[0]), std::move(expressions[1])); } -template +template QtNodes::NodeDataType BinOp::dataType(QtNodes::PortType /*portType*/, QtNodes::PortIndex portIndex) const { assert(portIndex == 0 || portIndex == 1); @@ -25,7 +25,7 @@ QtNodes::NodeDataType BinOp::dataType(QtNodes::PortType /*portType return DataType::Type(); } -template +template unsigned int BinOp::nPorts(QtNodes::PortType portType) const { switch (portType) @@ -39,14 +39,14 @@ unsigned int BinOp::nPorts(QtNodes::PortType portType) const throw std::runtime_error("invalid port type"); } -template +template std::shared_ptr BinOp::outData(QtNodes::PortIndex port) { assert(port == 0); return m_output; } -template +template QString BinOp::portCaption(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const { switch (portType) @@ -79,14 +79,14 @@ QString BinOp::portCaption(QtNodes::PortType portType, QtNodes::Po return QString{}; } -template +template bool BinOp::portCaptionVisible(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const { assert(portIndex == 0 || portIndex == 1); return portType == QtNodes::PortType::In || portType == QtNodes::PortType::Out; } -template +template void BinOp::setInData(std::shared_ptr value, int index) { assert(index == 0 || index == 1); @@ -103,7 +103,7 @@ void BinOp::setInData(std::shared_ptr value, in UpdateOutput(); } -template +template QtNodes::NodeValidationState BinOp::validationState() const { if (!m_lhs || !m_rhs) @@ -118,7 +118,7 @@ QtNodes::NodeValidationState BinOp::validationState() const return QtNodes::NodeValidationState::Valid; } -template +template QString BinOp::validationMessage() const { if (!m_lhs || !m_rhs) @@ -133,7 +133,7 @@ QString BinOp::validationMessage() const return QString(); } -template +template bool BinOp::ComputePreview(QPixmap& pixmap) { if (!m_lhs || !m_rhs) @@ -143,7 +143,7 @@ bool BinOp::ComputePreview(QPixmap& pixmap) return true; } -template +template void BinOp::UpdateOutput() { if (validationState() != QtNodes::NodeValidationState::Valid) @@ -154,7 +154,7 @@ void BinOp::UpdateOutput() m_output = std::make_shared(); m_output->preview = PreviewValues(1, 1); - m_output->preview.Fill(Nz::Vector4f::Zero()); + m_output->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); return; } @@ -186,7 +186,7 @@ void BinOp::UpdateOutput() } template -void BinAdd::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void BinAdd::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) output[i] = left[i] + right[i]; @@ -199,7 +199,7 @@ QString BinAdd::GetOperationString() const } template -void BinMul::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void BinMul::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) output[i] = left[i] * right[i]; @@ -212,7 +212,7 @@ QString BinMul::GetOperationString() const } template -void BinSub::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void BinSub::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) output[i] = left[i] - right[i]; @@ -225,7 +225,7 @@ QString BinSub::GetOperationString() const } template -void BinDiv::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void BinDiv::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) output[i] = left[i] / right[i]; diff --git a/src/ShaderNode/DataModels/BoolValue.cpp b/src/ShaderNode/DataModels/BoolValue.cpp index 2e06c627e..e1ee4f362 100644 --- a/src/ShaderNode/DataModels/BoolValue.cpp +++ b/src/ShaderNode/DataModels/BoolValue.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include @@ -53,7 +53,7 @@ std::shared_ptr BoolValue::outData(QtNodes::PortIndex port) float c = (m_value) ? 1.f : 0.f; auto out = std::make_shared(); - out->preview(0, 0) = Nz::Vector4f(c, c, c, 1.f); + out->preview(0, 0) = nzsl::Vector4f(c, c, c, 1.f); return out; } @@ -89,12 +89,12 @@ void BoolValue::BuildNodeEdition(QFormLayout* layout) layout->addRow(tr("Value"), checkbox); } -Nz::ShaderAst::NodePtr BoolValue::BuildNode(Nz::ShaderAst::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr BoolValue::BuildNode(nzsl::Ast::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const { assert(count == 0); assert(outputIndex == 0); - return Nz::ShaderBuilder::Constant(m_value); + return nzsl::ShaderBuilder::Constant(m_value); } bool BoolValue::ComputePreview(QPixmap& pixmap) diff --git a/src/ShaderNode/DataModels/BoolValue.hpp b/src/ShaderNode/DataModels/BoolValue.hpp index 8e906e97b..f2dd25dbb 100644 --- a/src/ShaderNode/DataModels/BoolValue.hpp +++ b/src/ShaderNode/DataModels/BoolValue.hpp @@ -17,7 +17,7 @@ class BoolValue : public ShaderNode BoolValue(ShaderGraph& graph); ~BoolValue() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; void BuildNodeEdition(QFormLayout* layout) override; QString caption() const override; diff --git a/src/ShaderNode/DataModels/BufferField.cpp b/src/ShaderNode/DataModels/BufferField.cpp index b191aeba4..72788eda9 100644 --- a/src/ShaderNode/DataModels/BufferField.cpp +++ b/src/ShaderNode/DataModels/BufferField.cpp @@ -1,11 +1,11 @@ #include -#include +#include #include #include #include #include #include -#include +#include #include #include #include @@ -49,7 +49,7 @@ ShaderNode(graph) UpdatePreview(); } -Nz::ShaderAst::NodePtr BufferField::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr BufferField::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 0); assert(outputIndex == 0); @@ -65,7 +65,7 @@ Nz::ShaderAst::NodePtr BufferField::BuildNode(Nz::ShaderAst::ExpressionPtr* expr assert(m_currentFieldIndex); const CurrentField& currentField = *m_currentFieldIndex; - Nz::ShaderAst::ExpressionPtr sourceExpr = Nz::ShaderBuilder::Identifier(bufferEntry.name); + nzsl::Ast::ExpressionPtr sourceExpr = nzsl::ShaderBuilder::Identifier(bufferEntry.name); std::vector memberIdentifiers; memberIdentifiers.reserve(currentField.nestedFields.size() + 1); @@ -89,8 +89,7 @@ Nz::ShaderAst::NodePtr BufferField::BuildNode(Nz::ShaderAst::ExpressionPtr* expr memberIdentifiers.push_back(memberEntry.name); - using namespace Nz; - return ShaderBuilder::AccessMember(std::move(sourceExpr), std::move(memberIdentifiers)); + return nzsl::ShaderBuilder::AccessMember(std::move(sourceExpr), std::move(memberIdentifiers)); } unsigned int BufferField::nPorts(QtNodes::PortType portType) const diff --git a/src/ShaderNode/DataModels/BufferField.hpp b/src/ShaderNode/DataModels/BufferField.hpp index eed42d9e1..df3138290 100644 --- a/src/ShaderNode/DataModels/BufferField.hpp +++ b/src/ShaderNode/DataModels/BufferField.hpp @@ -15,7 +15,7 @@ class BufferField : public ShaderNode BufferField(ShaderGraph& graph); ~BufferField() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; void BuildNodeEdition(QFormLayout* layout) override; QString caption() const override { return "BufferField"; } diff --git a/src/ShaderNode/DataModels/Cast.hpp b/src/ShaderNode/DataModels/Cast.hpp index 47f954f81..1439f8cbd 100644 --- a/src/ShaderNode/DataModels/Cast.hpp +++ b/src/ShaderNode/DataModels/Cast.hpp @@ -17,7 +17,7 @@ class CastVec : public ShaderNode CastVec(ShaderGraph& graph); ~CastVec() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const; void BuildNodeEdition(QFormLayout* layout) override; QString caption() const override; diff --git a/src/ShaderNode/DataModels/Cast.inl b/src/ShaderNode/DataModels/Cast.inl index 82ba201e2..5c07d701e 100644 --- a/src/ShaderNode/DataModels/Cast.inl +++ b/src/ShaderNode/DataModels/Cast.inl @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -18,7 +18,7 @@ ShaderNode(graph) } template -Nz::ShaderAst::NodePtr CastVec::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr CastVec::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(m_input); assert(count == 1); @@ -30,12 +30,12 @@ Nz::ShaderAst::NodePtr CastVec::BuildNode(Nz::ShaderAst::Expre { std::size_t overflowComponentCount = ToComponentCount - fromComponentCount; - std::vector params; + std::vector params; params.emplace_back(std::move(expressions[0])); for (std::size_t i = 0; i < overflowComponentCount; ++i) - params.emplace_back(Nz::ShaderBuilder::Constant(m_overflowComponents[i])); + params.emplace_back(nzsl::ShaderBuilder::Constant(m_overflowComponents[i])); - return Nz::ShaderBuilder::Cast(Nz::ShaderAst::ExpressionType{ Nz::ShaderAst::VectorType{ ToComponentCount, Nz::ShaderAst::PrimitiveType::Float32 } }, std::move(params)); + return nzsl::ShaderBuilder::Cast(nzsl::Ast::ExpressionType{ nzsl::Ast::VectorType{ ToComponentCount, nzsl::Ast::PrimitiveType::Float32 } }, std::move(params)); } else if (ToComponentCount < fromComponentCount) { @@ -46,7 +46,7 @@ Nz::ShaderAst::NodePtr CastVec::BuildNode(Nz::ShaderAst::Expre return std::apply([&](auto... components) { std::initializer_list componentList{ components... }; - return Nz::ShaderBuilder::Swizzle(std::move(expressions[0]), componentList); + return nzsl::ShaderBuilder::Swizzle(std::move(expressions[0]), componentList); }, swizzleComponents); } else @@ -187,7 +187,7 @@ void CastVec::UpdateOutput() if (!m_input) { m_output->preview = PreviewValues(1, 1); - m_output->preview(0, 0) = Nz::Vector4f::Zero(); + m_output->preview(0, 0) = nzsl::Vector4f(0.f, 0.f, 0.f, 0.f); return; } @@ -208,9 +208,9 @@ void CastVec::UpdateOutput() { for (std::size_t x = 0; x < inputWidth; ++x) { - Nz::Vector4f color = input(x, y); + nzsl::Vector4f color = input(x, y); - float* colorPtr = &color.x; + float* colorPtr = &color[0]; for (std::size_t i = 0; i < overflowComponentCount; ++i) *colorPtr++ = m_overflowComponents[i]; diff --git a/src/ShaderNode/DataModels/CompOp.hpp b/src/ShaderNode/DataModels/CompOp.hpp index 134fe87ca..db9efd2f6 100644 --- a/src/ShaderNode/DataModels/CompOp.hpp +++ b/src/ShaderNode/DataModels/CompOp.hpp @@ -8,14 +8,14 @@ #include #include -template +template class CompOp : public ShaderNode { public: CompOp(ShaderGraph& graph); ~CompOp() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; virtual QString GetOperationString() const = 0; @@ -34,7 +34,7 @@ class CompOp : public ShaderNode QString validationMessage() const override; private: - virtual void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) = 0; + virtual void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) = 0; bool ComputePreview(QPixmap& pixmap) override; void UpdateOutput(); @@ -46,62 +46,62 @@ class CompOp : public ShaderNode template -class CompEq : public CompOp +class CompEq : public CompOp { public: - using CompOp::CompOp; + using CompOp::CompOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class CompGe : public CompOp +class CompGe : public CompOp { public: - using CompOp::CompOp; + using CompOp::CompOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class CompGt : public CompOp +class CompGt : public CompOp { public: - using CompOp::CompOp; + using CompOp::CompOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class CompLe : public CompOp +class CompLe : public CompOp { public: - using CompOp::CompOp; + using CompOp::CompOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class CompLt : public CompOp +class CompLt : public CompOp { public: - using CompOp::CompOp; + using CompOp::CompOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; template -class CompNe : public CompOp +class CompNe : public CompOp { public: - using CompOp::CompOp; + using CompOp::CompOp; - void ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) override; + void ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) override; QString GetOperationString() const final; }; diff --git a/src/ShaderNode/DataModels/CompOp.inl b/src/ShaderNode/DataModels/CompOp.inl index ba4b55ad8..07ba38ea1 100644 --- a/src/ShaderNode/DataModels/CompOp.inl +++ b/src/ShaderNode/DataModels/CompOp.inl @@ -1,23 +1,23 @@ #include -#include +#include -template +template CompOp::CompOp(ShaderGraph& graph) : ShaderNode(graph) { UpdateOutput(); } -template -Nz::ShaderAst::NodePtr CompOp::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +template +nzsl::Ast::NodePtr CompOp::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); - return Nz::ShaderBuilder::Binary(Op, std::move(expressions[0]), std::move(expressions[1])); + return nzsl::ShaderBuilder::Binary(Op, std::move(expressions[0]), std::move(expressions[1])); } -template +template QtNodes::NodeDataType CompOp::dataType(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const { switch (portType) @@ -41,7 +41,7 @@ QtNodes::NodeDataType CompOp::dataType(QtNodes::PortType portType, throw std::runtime_error("invalid port type"); } -template +template unsigned int CompOp::nPorts(QtNodes::PortType portType) const { switch (portType) @@ -55,14 +55,14 @@ unsigned int CompOp::nPorts(QtNodes::PortType portType) const throw std::runtime_error("invalid port type"); } -template +template std::shared_ptr CompOp::outData(QtNodes::PortIndex port) { assert(port == 0); return m_output; } -template +template QString CompOp::portCaption(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const { switch (portType) @@ -95,14 +95,14 @@ QString CompOp::portCaption(QtNodes::PortType portType, QtNodes::P return QString{}; } -template +template bool CompOp::portCaptionVisible(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const { assert(portIndex == 0 || portIndex == 1); return portType == QtNodes::PortType::In || portType == QtNodes::PortType::Out; } -template +template void CompOp::setInData(std::shared_ptr value, int index) { assert(index == 0 || index == 1); @@ -119,7 +119,7 @@ void CompOp::setInData(std::shared_ptr value, i UpdateOutput(); } -template +template QtNodes::NodeValidationState CompOp::validationState() const { if (!m_lhs || !m_rhs) @@ -134,7 +134,7 @@ QtNodes::NodeValidationState CompOp::validationState() const return QtNodes::NodeValidationState::Valid; } -template +template QString CompOp::validationMessage() const { if (!m_lhs || !m_rhs) @@ -149,7 +149,7 @@ QString CompOp::validationMessage() const return QString(); } -template +template bool CompOp::ComputePreview(QPixmap& pixmap) { if (!m_lhs || !m_rhs) @@ -159,14 +159,14 @@ bool CompOp::ComputePreview(QPixmap& pixmap) return true; } -template +template void CompOp::UpdateOutput() { if (validationState() != QtNodes::NodeValidationState::Valid) { m_output = std::make_shared(); m_output->preview = PreviewValues(1, 1); - m_output->preview.Fill(Nz::Vector4f::Zero()); + m_output->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); return; } @@ -195,12 +195,12 @@ void CompOp::UpdateOutput() } template -void CompEq::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void CompEq::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) { float r = (left[i] == right[i]) ? 1.f : 0.f; - output[i] = Nz::Vector4f(r, r, r, r); + output[i] = nzsl::Vector4f(r, r, r, r); } } @@ -211,12 +211,12 @@ QString CompEq::GetOperationString() const } template -void CompGe::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void CompGe::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) { - float r = (left[i] >= right[i]) ? 1.f : 0.f; - output[i] = Nz::Vector4f(r, r, r, r); + float r = (left[i][0] >= right[i][0]) ? 1.f : 0.f; + output[i] = nzsl::Vector4f(r, r, r, r); } } @@ -227,12 +227,12 @@ QString CompGe::GetOperationString() const } template -void CompGt::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void CompGt::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) { - float r = (left[i] > right[i]) ? 1.f : 0.f; - output[i] = Nz::Vector4f(r, r, r, r); + float r = (left[i][0] > right[i][0]) ? 1.f : 0.f; + output[i] = nzsl::Vector4f(r, r, r, r); } } @@ -243,12 +243,12 @@ QString CompGt::GetOperationString() const } template -void CompLe::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void CompLe::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) { - float r = (left[i] >= right[i]) ? 1.f : 0.f; - output[i] = Nz::Vector4f(r, r, r, r); + float r = (left[i][0] <= right[i][0]) ? 1.f : 0.f; + output[i] = nzsl::Vector4f(r, r, r, r); } } @@ -259,12 +259,12 @@ QString CompLe::GetOperationString() const } template -void CompLt::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void CompLt::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) { - float r = (left[i] > right[i]) ? 1.f : 0.f; - output[i] = Nz::Vector4f(r, r, r, r); + float r = (left[i][0] < right[i][0]) ? 1.f : 0.f; + output[i] = nzsl::Vector4f(r, r, r, r); } } @@ -275,12 +275,12 @@ QString CompLt::GetOperationString() const } template -void CompNe::ApplyOp(const Nz::Vector4f* left, const Nz::Vector4f* right, Nz::Vector4f* output, std::size_t pixelCount) +void CompNe::ApplyOp(const nzsl::Vector4f* left, const nzsl::Vector4f* right, nzsl::Vector4f* output, std::size_t pixelCount) { for (std::size_t i = 0; i < pixelCount; ++i) { float r = (left[i] != right[i]) ? 1.f : 0.f; - output[i] = Nz::Vector4f(r, r, r, r); + output[i] = nzsl::Vector4f(r, r, r, r); } } diff --git a/src/ShaderNode/DataModels/ConditionalExpression.cpp b/src/ShaderNode/DataModels/ConditionalExpression.cpp index 7137b0464..37a238489 100644 --- a/src/ShaderNode/DataModels/ConditionalExpression.cpp +++ b/src/ShaderNode/DataModels/ConditionalExpression.cpp @@ -1,11 +1,11 @@ #include -#include +#include #include #include #include #include #include -#include +#include #include #include #include @@ -35,7 +35,7 @@ ShaderNode(graph) UpdatePreview(); } -Nz::ShaderAst::NodePtr ConditionalExpression::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr ConditionalExpression::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); @@ -46,7 +46,7 @@ Nz::ShaderAst::NodePtr ConditionalExpression::BuildNode(Nz::ShaderAst::Expressio const ShaderGraph& graph = GetGraph(); const auto& optionEntry = graph.GetOption(*m_currentOptionIndex); - return Nz::ShaderBuilder::ConditionalExpression(Nz::ShaderBuilder::Identifier(optionEntry.name), std::move(expressions[0]), std::move(expressions[1])); + return nzsl::ShaderBuilder::ConditionalExpression(nzsl::ShaderBuilder::Identifier(optionEntry.name), std::move(expressions[0]), std::move(expressions[1])); } QString ConditionalExpression::caption() const diff --git a/src/ShaderNode/DataModels/ConditionalExpression.hpp b/src/ShaderNode/DataModels/ConditionalExpression.hpp index afa9796c6..42a61aab0 100644 --- a/src/ShaderNode/DataModels/ConditionalExpression.hpp +++ b/src/ShaderNode/DataModels/ConditionalExpression.hpp @@ -15,7 +15,7 @@ class ConditionalExpression : public ShaderNode ConditionalExpression(ShaderGraph& graph); ~ConditionalExpression() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; void BuildNodeEdition(QFormLayout* layout) override; QString caption() const override; diff --git a/src/ShaderNode/DataModels/Discard.cpp b/src/ShaderNode/DataModels/Discard.cpp index aa3035155..0f22f24a8 100644 --- a/src/ShaderNode/DataModels/Discard.cpp +++ b/src/ShaderNode/DataModels/Discard.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -16,14 +16,14 @@ ShaderNode(graph) DisableCustomVariableName(); } -Nz::ShaderAst::NodePtr Discard::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr Discard::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 1); assert(outputIndex == 0); - using namespace Nz; + using namespace nzsl; - auto condition = ShaderBuilder::Binary(ShaderAst::BinaryType::CompEq, std::move(expressions[0]), ShaderBuilder::Constant(true)); + auto condition = ShaderBuilder::Binary(nzsl::Ast::BinaryType::CompEq, std::move(expressions[0]), ShaderBuilder::Constant(true)); return ShaderBuilder::Branch(std::move(condition), ShaderBuilder::Discard()); } diff --git a/src/ShaderNode/DataModels/Discard.hpp b/src/ShaderNode/DataModels/Discard.hpp index 91f88edea..e1f309df8 100644 --- a/src/ShaderNode/DataModels/Discard.hpp +++ b/src/ShaderNode/DataModels/Discard.hpp @@ -14,7 +14,7 @@ class Discard : public ShaderNode public: Discard(ShaderGraph& graph); - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; int GetOutputOrder() const; QString caption() const override { return "Discard"; } diff --git a/src/ShaderNode/DataModels/FloatValue.cpp b/src/ShaderNode/DataModels/FloatValue.cpp index 49513baa6..c29bde220 100644 --- a/src/ShaderNode/DataModels/FloatValue.cpp +++ b/src/ShaderNode/DataModels/FloatValue.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include FloatValue::FloatValue(ShaderGraph& graph) : @@ -50,7 +50,7 @@ std::shared_ptr FloatValue::outData(QtNodes::PortIndex port) assert(port == 0); auto out = std::make_shared(); - out->preview(0, 0) = Nz::Vector4f(m_value, m_value, m_value, 1.f); + out->preview(0, 0) = nzsl::Vector4f(m_value, m_value, m_value, 1.f); return out; } @@ -89,12 +89,12 @@ void FloatValue::BuildNodeEdition(QFormLayout* layout) layout->addRow(tr("Value"), spinbox); } -Nz::ShaderAst::NodePtr FloatValue::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr FloatValue::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 0); assert(outputIndex == 0); - return Nz::ShaderBuilder::Constant(m_value); + return nzsl::ShaderBuilder::Constant(m_value); } bool FloatValue::ComputePreview(QPixmap& pixmap) diff --git a/src/ShaderNode/DataModels/FloatValue.hpp b/src/ShaderNode/DataModels/FloatValue.hpp index 722ee44ca..207a2c56d 100644 --- a/src/ShaderNode/DataModels/FloatValue.hpp +++ b/src/ShaderNode/DataModels/FloatValue.hpp @@ -17,7 +17,7 @@ class FloatValue : public ShaderNode FloatValue(ShaderGraph& graph); ~FloatValue() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; void BuildNodeEdition(QFormLayout* layout) override; QString caption() const override; diff --git a/src/ShaderNode/DataModels/InputValue.cpp b/src/ShaderNode/DataModels/InputValue.cpp index 51dc4953b..10f05daa1 100644 --- a/src/ShaderNode/DataModels/InputValue.cpp +++ b/src/ShaderNode/DataModels/InputValue.cpp @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include InputValue::InputValue(ShaderGraph& graph) : @@ -109,7 +109,7 @@ void InputValue::BuildNodeEdition(QFormLayout* layout) layout->addRow(tr("Input"), inputSelection); } -Nz::ShaderAst::NodePtr InputValue::BuildNode(Nz::ShaderAst::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr InputValue::BuildNode(nzsl::Ast::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const { assert(count == 0); assert(outputIndex == 0); @@ -118,7 +118,7 @@ Nz::ShaderAst::NodePtr InputValue::BuildNode(Nz::ShaderAst::ExpressionPtr* /*exp throw std::runtime_error("no input"); const auto& inputEntry = GetGraph().GetInput(*m_currentInputIndex); - return Nz::ShaderBuilder::AccessMember(Nz::ShaderBuilder::Identifier("input"), { inputEntry.name }); + return nzsl::ShaderBuilder::AccessMember(nzsl::ShaderBuilder::Identifier("input"), { inputEntry.name }); } auto InputValue::dataType(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const -> QtNodes::NodeDataType diff --git a/src/ShaderNode/DataModels/InputValue.hpp b/src/ShaderNode/DataModels/InputValue.hpp index 63cbf197c..52f7a1a43 100644 --- a/src/ShaderNode/DataModels/InputValue.hpp +++ b/src/ShaderNode/DataModels/InputValue.hpp @@ -19,7 +19,7 @@ class InputValue : public ShaderNode void BuildNodeEdition(QFormLayout* layout) override; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override { return "Input"; } QString name() const override { return "Input"; } diff --git a/src/ShaderNode/DataModels/Mat4BinOp.hpp b/src/ShaderNode/DataModels/Mat4BinOp.hpp index e752b21a4..7f4ab2942 100644 --- a/src/ShaderNode/DataModels/Mat4BinOp.hpp +++ b/src/ShaderNode/DataModels/Mat4BinOp.hpp @@ -6,14 +6,14 @@ #include #include -template +template class Mat4BinOp : public ShaderNode { public: Mat4BinOp(ShaderGraph& graph); ~Mat4BinOp() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const; unsigned int nPorts(QtNodes::PortType portType) const override; @@ -35,28 +35,28 @@ class Mat4BinOp : public ShaderNode std::shared_ptr m_output; }; -class Mat4Add : public Mat4BinOp +class Mat4Add : public Mat4BinOp { public: - using Mat4BinOp::Mat4BinOp; + using Mat4BinOp::Mat4BinOp; QString caption() const override; QString name() const override; }; -class Mat4Mul : public Mat4BinOp +class Mat4Mul : public Mat4BinOp { public: - using Mat4BinOp::Mat4BinOp; + using Mat4BinOp::Mat4BinOp; QString caption() const override; QString name() const override; }; -class Mat4Sub : public Mat4BinOp +class Mat4Sub : public Mat4BinOp { public: - using Mat4BinOp::Mat4BinOp; + using Mat4BinOp::Mat4BinOp; QString caption() const override; QString name() const override; diff --git a/src/ShaderNode/DataModels/Mat4BinOp.inl b/src/ShaderNode/DataModels/Mat4BinOp.inl index 894328be9..cff646419 100644 --- a/src/ShaderNode/DataModels/Mat4BinOp.inl +++ b/src/ShaderNode/DataModels/Mat4BinOp.inl @@ -1,23 +1,23 @@ #include -#include +#include -template +template Mat4BinOp::Mat4BinOp(ShaderGraph& graph) : ShaderNode(graph) { UpdateOutput(); } -template -Nz::ShaderAst::NodePtr Mat4BinOp::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +template +nzsl::Ast::NodePtr Mat4BinOp::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); - return Nz::ShaderBuilder::Binary(Op, std::move(expressions[0]), std::move(expressions[1])); + return nzsl::ShaderBuilder::Binary(Op, std::move(expressions[0]), std::move(expressions[1])); } -template +template QtNodes::NodeDataType Mat4BinOp::dataType(QtNodes::PortType /*portType*/, QtNodes::PortIndex portIndex) const { assert(portIndex == 0 || portIndex == 1); @@ -25,7 +25,7 @@ QtNodes::NodeDataType Mat4BinOp::dataType(QtNodes::PortType /*portType*/, Qt return Matrix4Data::Type(); } -template +template unsigned int Mat4BinOp::nPorts(QtNodes::PortType portType) const { switch (portType) @@ -39,14 +39,14 @@ unsigned int Mat4BinOp::nPorts(QtNodes::PortType portType) const throw std::runtime_error("invalid port type"); } -template +template std::shared_ptr Mat4BinOp::outData(QtNodes::PortIndex port) { assert(port == 0); return m_output; } -template +template void Mat4BinOp::setInData(std::shared_ptr value, int index) { assert(index == 0 || index == 1); @@ -66,7 +66,7 @@ void Mat4BinOp::setInData(std::shared_ptr value, int inde UpdateOutput(); } -template +template QtNodes::NodeValidationState Mat4BinOp::validationState() const { if (!m_lhs || !m_rhs) @@ -75,7 +75,7 @@ QtNodes::NodeValidationState Mat4BinOp::validationState() const return QtNodes::NodeValidationState::Valid; } -template +template QString Mat4BinOp::validationMessage() const { if (!m_lhs || !m_rhs) @@ -84,7 +84,7 @@ QString Mat4BinOp::validationMessage() const return QString(); } -template +template bool Mat4BinOp::ComputePreview(QPixmap& pixmap) { if (!m_lhs || !m_rhs) @@ -96,7 +96,7 @@ bool Mat4BinOp::ComputePreview(QPixmap& pixmap) //return true; } -template +template void Mat4BinOp::UpdateOutput() { if (validationState() != QtNodes::NodeValidationState::Valid) diff --git a/src/ShaderNode/DataModels/Mat4VecMul.cpp b/src/ShaderNode/DataModels/Mat4VecMul.cpp index 0e723584d..905ee24cb 100644 --- a/src/ShaderNode/DataModels/Mat4VecMul.cpp +++ b/src/ShaderNode/DataModels/Mat4VecMul.cpp @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include Mat4VecMul::Mat4VecMul(ShaderGraph& graph) : ShaderNode(graph) @@ -8,12 +8,12 @@ ShaderNode(graph) UpdateOutput(); } -Nz::ShaderAst::NodePtr Mat4VecMul::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr Mat4VecMul::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); - return Nz::ShaderBuilder::Binary(Nz::ShaderAst::BinaryType::Multiply, std::move(expressions[0]), std::move(expressions[1])); + return nzsl::ShaderBuilder::Binary(nzsl::Ast::BinaryType::Multiply, std::move(expressions[0]), std::move(expressions[1])); } QString Mat4VecMul::caption() const @@ -148,13 +148,13 @@ void Mat4VecMul::UpdateOutput() { m_output = std::make_shared(4); m_output->preview = PreviewValues(1, 1); - m_output->preview.Fill(Nz::Vector4f::Zero()); + m_output->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); return; } m_output = std::make_shared(4); m_output->preview = PreviewValues(1, 1); - m_output->preview.Fill(Nz::Vector4f::Zero()); + m_output->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); /*m_output = std::make_shared(m_rhs->componentCount); @@ -174,9 +174,9 @@ void Mat4VecMul::UpdateOutput() m_output->preview = PreviewValues(maxWidth, maxHeight); - const Nz::Vector4f* left = leftResized.GetData(); - const Nz::Vector4f* right = rightPreview.GetData(); - Nz::Vector4f* output = m_output->preview.GetData(); + const nzsl::Vector4f* left = leftResized.GetData(); + const nzsl::Vector4f* right = rightPreview.GetData(); + nzsl::Vector4f* output = m_output->preview.GetData(); std::size_t pixelCount = maxWidth * maxHeight; for (std::size_t i = 0; i < pixelCount; ++i) diff --git a/src/ShaderNode/DataModels/Mat4VecMul.hpp b/src/ShaderNode/DataModels/Mat4VecMul.hpp index 76debc88f..d801dffde 100644 --- a/src/ShaderNode/DataModels/Mat4VecMul.hpp +++ b/src/ShaderNode/DataModels/Mat4VecMul.hpp @@ -13,7 +13,7 @@ class Mat4VecMul : public ShaderNode Mat4VecMul(ShaderGraph& graph); ~Mat4VecMul() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override; QString name() const override; diff --git a/src/ShaderNode/DataModels/OutputValue.cpp b/src/ShaderNode/DataModels/OutputValue.cpp index e3471fff8..030448ea6 100644 --- a/src/ShaderNode/DataModels/OutputValue.cpp +++ b/src/ShaderNode/DataModels/OutputValue.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -54,7 +54,7 @@ void OutputValue::BuildNodeEdition(QFormLayout* layout) layout->addRow(tr("Output"), outputSelection); } -Nz::ShaderAst::NodePtr OutputValue::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr OutputValue::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 1); assert(outputIndex == 0); @@ -63,10 +63,10 @@ Nz::ShaderAst::NodePtr OutputValue::BuildNode(Nz::ShaderAst::ExpressionPtr* expr throw std::runtime_error("no output"); const auto& outputEntry = GetGraph().GetOutput(*m_currentOutputIndex); - auto output = Nz::ShaderBuilder::AccessMember(Nz::ShaderBuilder::Identifier("output"), { outputEntry.name }); + auto output = nzsl::ShaderBuilder::AccessMember(nzsl::ShaderBuilder::Identifier("output"), { outputEntry.name }); using namespace Nz; - return Nz::ShaderBuilder::Assign(ShaderAst::AssignType::Simple, std::move(output), std::move(expressions[0])); + return nzsl::ShaderBuilder::Assign(nzsl::Ast::AssignType::Simple, std::move(output), std::move(expressions[0])); } std::shared_ptr OutputValue::outData(QtNodes::PortIndex /*port*/) diff --git a/src/ShaderNode/DataModels/OutputValue.hpp b/src/ShaderNode/DataModels/OutputValue.hpp index a44284e1a..760993bf7 100644 --- a/src/ShaderNode/DataModels/OutputValue.hpp +++ b/src/ShaderNode/DataModels/OutputValue.hpp @@ -16,7 +16,7 @@ class OutputValue : public ShaderNode void BuildNodeEdition(QFormLayout* layout) override; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override { return "Output"; } QString name() const override { return "Output"; } diff --git a/src/ShaderNode/DataModels/PositionOutputValue.cpp b/src/ShaderNode/DataModels/PositionOutputValue.cpp index dd82ac2b2..d904f8d8d 100644 --- a/src/ShaderNode/DataModels/PositionOutputValue.cpp +++ b/src/ShaderNode/DataModels/PositionOutputValue.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -14,15 +14,15 @@ ShaderNode(graph) DisableCustomVariableName(); } -Nz::ShaderAst::NodePtr PositionOutputValue::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr PositionOutputValue::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { using namespace Nz; assert(count == 1); assert(outputIndex == 0); - auto output = Nz::ShaderBuilder::AccessMember(Nz::ShaderBuilder::Identifier("output"), { "position" }); - return ShaderBuilder::Assign(ShaderAst::AssignType::Simple, std::move(output), std::move(expressions[0])); + auto output = nzsl::ShaderBuilder::AccessMember(nzsl::ShaderBuilder::Identifier("output"), { "position" }); + return nzsl::ShaderBuilder::Assign(nzsl::Ast::AssignType::Simple, std::move(output), std::move(expressions[0])); } QtNodes::NodeDataType PositionOutputValue::dataType(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const diff --git a/src/ShaderNode/DataModels/PositionOutputValue.hpp b/src/ShaderNode/DataModels/PositionOutputValue.hpp index 1cb8ed8ef..aba7d5edf 100644 --- a/src/ShaderNode/DataModels/PositionOutputValue.hpp +++ b/src/ShaderNode/DataModels/PositionOutputValue.hpp @@ -14,7 +14,7 @@ class PositionOutputValue : public ShaderNode public: PositionOutputValue(ShaderGraph& graph); - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override { return "PositionOutputValue"; } QString name() const override { return "PositionOutputValue"; } diff --git a/src/ShaderNode/DataModels/SampleTexture.cpp b/src/ShaderNode/DataModels/SampleTexture.cpp index 7a697f7a7..fe467cbfa 100644 --- a/src/ShaderNode/DataModels/SampleTexture.cpp +++ b/src/ShaderNode/DataModels/SampleTexture.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include SampleTexture::SampleTexture(ShaderGraph& graph) : ShaderNode(graph) @@ -28,7 +28,7 @@ void SampleTexture::UpdateOutput() if (!m_texture || !m_uv) { output = PreviewValues(1, 1); - output.Fill(Nz::Vector4f::Zero()); + output.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); return; } @@ -48,12 +48,12 @@ void SampleTexture::UpdateOutput() { for (std::size_t x = 0; x < uvWidth; ++x) { - Nz::Vector4f uvValue = uv(x, y); + nzsl::Vector4f uvValue = uv(x, y); if (textureWidth > 0 && textureHeight > 0) - output(x, y) = texturePreview.Sample(uvValue.x, uvValue.y); + output(x, y) = texturePreview.Sample(uvValue.x(), uvValue.y()); else - output(x, y) = Nz::Vector4f(0.f, 0.f, 0.f, 1.f); + output(x, y) = nzsl::Vector4f(0.f, 0.f, 0.f, 1.f); } } @@ -71,18 +71,18 @@ bool SampleTexture::ComputePreview(QPixmap& pixmap) return true; } -Nz::ShaderAst::NodePtr SampleTexture::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr SampleTexture::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(m_texture); assert(m_uv); assert(count == 2); assert(outputIndex == 0); - std::vector params; + std::vector params; params.push_back(std::move(expressions[0])); params.push_back(std::move(expressions[1])); - return Nz::ShaderBuilder::Intrinsic(Nz::ShaderAst::IntrinsicType::SampleTexture, std::move(params)); + return nzsl::ShaderBuilder::Intrinsic(nzsl::Ast::IntrinsicType::SampleTexture, std::move(params)); } auto SampleTexture::dataType(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const -> QtNodes::NodeDataType diff --git a/src/ShaderNode/DataModels/SampleTexture.hpp b/src/ShaderNode/DataModels/SampleTexture.hpp index d09c71521..f8b49442f 100644 --- a/src/ShaderNode/DataModels/SampleTexture.hpp +++ b/src/ShaderNode/DataModels/SampleTexture.hpp @@ -17,7 +17,7 @@ class SampleTexture : public ShaderNode SampleTexture(ShaderGraph& graph); ~SampleTexture() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override { return "Sample texture"; } QString name() const override { return "SampleTexture"; } diff --git a/src/ShaderNode/DataModels/ShaderNode.hpp b/src/ShaderNode/DataModels/ShaderNode.hpp index c0aa8afcf..dd2353b45 100644 --- a/src/ShaderNode/DataModels/ShaderNode.hpp +++ b/src/ShaderNode/DataModels/ShaderNode.hpp @@ -4,7 +4,7 @@ #define NAZARA_SHADERNODES_SHADERNODE_HPP #include -#include +#include #include #include #include @@ -18,7 +18,7 @@ class ShaderNode : public QtNodes::NodeDataModel public: ShaderNode(ShaderGraph& graph); - virtual Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const = 0; + virtual nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const = 0; virtual void BuildNodeEdition(QFormLayout* layout); inline void DisablePreview(); diff --git a/src/ShaderNode/DataModels/TextureValue.cpp b/src/ShaderNode/DataModels/TextureValue.cpp index 8015b47ee..72ca51550 100644 --- a/src/ShaderNode/DataModels/TextureValue.cpp +++ b/src/ShaderNode/DataModels/TextureValue.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include TextureValue::TextureValue(ShaderGraph& graph) : @@ -110,7 +110,7 @@ void TextureValue::BuildNodeEdition(QFormLayout* layout) layout->addRow(tr("Texture"), textureSelection); } -Nz::ShaderAst::NodePtr TextureValue::BuildNode(Nz::ShaderAst::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr TextureValue::BuildNode(nzsl::Ast::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const { if (!m_currentTextureIndex) throw std::runtime_error("invalid texture input"); @@ -119,7 +119,7 @@ Nz::ShaderAst::NodePtr TextureValue::BuildNode(Nz::ShaderAst::ExpressionPtr* /*e assert(outputIndex == 0); const auto& textureEntry = GetGraph().GetTexture(*m_currentTextureIndex); - return Nz::ShaderBuilder::Identifier(textureEntry.name); + return nzsl::ShaderBuilder::Identifier(textureEntry.name); } auto TextureValue::dataType(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const -> QtNodes::NodeDataType @@ -160,7 +160,7 @@ std::shared_ptr TextureValue::outData(QtNodes::PortIndex port { QColor pixelColor = previewImage.pixelColor(int(x), int(y)); - textureData->preview(x, y) = Nz::Vector4f(pixelColor.redF(), pixelColor.greenF(), pixelColor.blueF(), pixelColor.alphaF()); + textureData->preview(x, y) = nzsl::Vector4f(pixelColor.redF(), pixelColor.greenF(), pixelColor.blueF(), pixelColor.alphaF()); } } diff --git a/src/ShaderNode/DataModels/TextureValue.hpp b/src/ShaderNode/DataModels/TextureValue.hpp index 5de2a556d..845010886 100644 --- a/src/ShaderNode/DataModels/TextureValue.hpp +++ b/src/ShaderNode/DataModels/TextureValue.hpp @@ -18,7 +18,7 @@ class TextureValue : public ShaderNode void BuildNodeEdition(QFormLayout* layout) override; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override { return "Texture"; } QString name() const override { return "Texture"; } diff --git a/src/ShaderNode/DataModels/VecComposition.hpp b/src/ShaderNode/DataModels/VecComposition.hpp index d6dfca579..e9e284097 100644 --- a/src/ShaderNode/DataModels/VecComposition.hpp +++ b/src/ShaderNode/DataModels/VecComposition.hpp @@ -17,7 +17,7 @@ class VecComposition : public ShaderNode VecComposition(ShaderGraph& graph); ~VecComposition() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override; QString name() const override; diff --git a/src/ShaderNode/DataModels/VecComposition.inl b/src/ShaderNode/DataModels/VecComposition.inl index 5cf98a037..308296991 100644 --- a/src/ShaderNode/DataModels/VecComposition.inl +++ b/src/ShaderNode/DataModels/VecComposition.inl @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -14,16 +14,16 @@ ShaderNode(graph) } template -Nz::ShaderAst::NodePtr VecComposition::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr VecComposition::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == ComponentCount); assert(outputIndex == 0); - std::vector params; + std::vector params; for (std::size_t i = 0; i < count; ++i) params.emplace_back(std::move(expressions[i])); - return Nz::ShaderBuilder::Cast(Nz::ShaderAst::ExpressionType{ Nz::ShaderAst::VectorType{ ComponentCount, Nz::ShaderAst::PrimitiveType::Float32 } }, std::move(params)); + return nzsl::ShaderBuilder::Cast(nzsl::Ast::ExpressionType{ nzsl::Ast::VectorType{ ComponentCount, nzsl::Ast::PrimitiveType::Float32 } }, std::move(params)); } template @@ -147,7 +147,7 @@ void VecComposition::UpdateOutput() if (validationState() != QtNodes::NodeValidationState::Valid) { m_output->preview = PreviewValues(1, 1); - m_output->preview(0, 0) = Nz::Vector4f::Zero(); + m_output->preview(0, 0) = nzsl::Vector4f(0.f, 0.f, 0.f, 0.f); return; } @@ -177,7 +177,7 @@ void VecComposition::UpdateOutput() { for (std::size_t x = 0; x < maxInputWidth; ++x) { - Nz::Vector4f color(0.f, 0.f, 0.f, 1.f); + nzsl::Vector4f color(0.f, 0.f, 0.f, 1.f); for (std::size_t i = 0; i < ComponentCount; ++i) color[i] = previewResized[i](x, y)[0]; diff --git a/src/ShaderNode/DataModels/VecDecomposition.cpp b/src/ShaderNode/DataModels/VecDecomposition.cpp index 2cc8e8d94..0fedb26da 100644 --- a/src/ShaderNode/DataModels/VecDecomposition.cpp +++ b/src/ShaderNode/DataModels/VecDecomposition.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -16,12 +16,12 @@ ShaderNode(graph) DisableCustomVariableName(); } -Nz::ShaderAst::NodePtr VecDecomposition::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr VecDecomposition::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 1); assert(outputIndex < m_outputs.size()); - return Nz::ShaderBuilder::Swizzle(std::move(expressions[0]), { Nz::SafeCast(outputIndex) }); + return nzsl::ShaderBuilder::Swizzle(std::move(expressions[0]), { Nz::SafeCast(outputIndex) }); } QString VecDecomposition::caption() const @@ -139,7 +139,7 @@ void VecDecomposition::UpdateOutputs() { auto dummy = std::make_shared(); dummy->preview = PreviewValues(1, 1); - dummy->preview.Fill(Nz::Vector4f::Zero()); + dummy->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); m_outputs.fill(dummy); return; @@ -154,13 +154,13 @@ void VecDecomposition::UpdateOutputs() m_outputs[i] = std::make_shared(); m_outputs[i]->preview = PreviewValues(previewWidth, previewHeight); - const Nz::Vector4f* inputData = m_input->preview.GetData(); - Nz::Vector4f* outputData = m_outputs[i]->preview.GetData(); + const nzsl::Vector4f* inputData = m_input->preview.GetData(); + nzsl::Vector4f* outputData = m_outputs[i]->preview.GetData(); for (std::size_t j = 0; j < pixelCount; ++j) { - const Nz::Vector4f& input = *inputData++; + const nzsl::Vector4f& input = *inputData++; - *outputData++ = Nz::Vector4f(input[i], input[i], input[i], input[i]); + *outputData++ = nzsl::Vector4f(input[i], input[i], input[i], input[i]); } Q_EMIT dataUpdated(i); diff --git a/src/ShaderNode/DataModels/VecDecomposition.hpp b/src/ShaderNode/DataModels/VecDecomposition.hpp index a66326fbf..dc72fb808 100644 --- a/src/ShaderNode/DataModels/VecDecomposition.hpp +++ b/src/ShaderNode/DataModels/VecDecomposition.hpp @@ -18,7 +18,7 @@ class VecDecomposition : public ShaderNode VecDecomposition(ShaderGraph& graph); ~VecDecomposition() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override; QString name() const override; diff --git a/src/ShaderNode/DataModels/VecDot.cpp b/src/ShaderNode/DataModels/VecDot.cpp index 21849ec03..933e90bad 100644 --- a/src/ShaderNode/DataModels/VecDot.cpp +++ b/src/ShaderNode/DataModels/VecDot.cpp @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include VecDot::VecDot(ShaderGraph& graph) : ShaderNode(graph) @@ -9,16 +9,16 @@ ShaderNode(graph) UpdateOutput(); } -Nz::ShaderAst::NodePtr VecDot::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr VecDot::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); - std::vector params; + std::vector params; params.push_back(std::move(expressions[0])); params.push_back(std::move(expressions[1])); - return Nz::ShaderBuilder::Intrinsic(Nz::ShaderAst::IntrinsicType::DotProduct, std::move(params)); + return nzsl::ShaderBuilder::Intrinsic(nzsl::Ast::IntrinsicType::DotProduct, std::move(params)); } QString VecDot::caption() const @@ -126,7 +126,7 @@ void VecDot::UpdateOutput() if (validationState() != QtNodes::NodeValidationState::Valid) { m_output->preview = PreviewValues(1, 1); - m_output->preview.Fill(Nz::Vector4f::Zero()); + m_output->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); return; } @@ -146,9 +146,9 @@ void VecDot::UpdateOutput() m_output->preview = PreviewValues(maxWidth, maxHeight); - const Nz::Vector4f* left = leftResized.GetData(); - const Nz::Vector4f* right = rightPreview.GetData(); - Nz::Vector4f* output = m_output->preview.GetData(); + const nzsl::Vector4f* left = leftResized.GetData(); + const nzsl::Vector4f* right = rightPreview.GetData(); + nzsl::Vector4f* output = m_output->preview.GetData(); std::size_t pixelCount = maxWidth * maxHeight; for (std::size_t i = 0; i < pixelCount; ++i) diff --git a/src/ShaderNode/DataModels/VecDot.hpp b/src/ShaderNode/DataModels/VecDot.hpp index 194037bc6..c7e786fe8 100644 --- a/src/ShaderNode/DataModels/VecDot.hpp +++ b/src/ShaderNode/DataModels/VecDot.hpp @@ -13,7 +13,7 @@ class VecDot : public ShaderNode VecDot(ShaderGraph& graph); ~VecDot() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override; QString name() const override; diff --git a/src/ShaderNode/DataModels/VecFloatMul.cpp b/src/ShaderNode/DataModels/VecFloatMul.cpp index 9ddcb8bc0..3056fd86a 100644 --- a/src/ShaderNode/DataModels/VecFloatMul.cpp +++ b/src/ShaderNode/DataModels/VecFloatMul.cpp @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include VecFloatMul::VecFloatMul(ShaderGraph& graph) : ShaderNode(graph) @@ -8,12 +8,12 @@ ShaderNode(graph) UpdateOutput(); } -Nz::ShaderAst::NodePtr VecFloatMul::BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr VecFloatMul::BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const { assert(count == 2); assert(outputIndex == 0); - return Nz::ShaderBuilder::Binary(Nz::ShaderAst::BinaryType::Multiply, std::move(expressions[0]), std::move(expressions[1])); + return nzsl::ShaderBuilder::Binary(nzsl::Ast::BinaryType::Multiply, std::move(expressions[0]), std::move(expressions[1])); } QString VecFloatMul::caption() const @@ -142,7 +142,7 @@ void VecFloatMul::UpdateOutput() { m_output = std::make_shared(4); m_output->preview = PreviewValues(1, 1); - m_output->preview.Fill(Nz::Vector4f::Zero()); + m_output->preview.Fill(nzsl::Vector4f(0.f, 0.f, 0.f, 0.f)); return; } @@ -164,9 +164,9 @@ void VecFloatMul::UpdateOutput() m_output->preview = PreviewValues(maxWidth, maxHeight); - const Nz::Vector4f* left = leftResized.GetData(); - const Nz::Vector4f* right = rightPreview.GetData(); - Nz::Vector4f* output = m_output->preview.GetData(); + const nzsl::Vector4f* left = leftResized.GetData(); + const nzsl::Vector4f* right = rightPreview.GetData(); + nzsl::Vector4f* output = m_output->preview.GetData(); std::size_t pixelCount = maxWidth * maxHeight; for (std::size_t i = 0; i < pixelCount; ++i) diff --git a/src/ShaderNode/DataModels/VecFloatMul.hpp b/src/ShaderNode/DataModels/VecFloatMul.hpp index 7295d75ce..90c6f437a 100644 --- a/src/ShaderNode/DataModels/VecFloatMul.hpp +++ b/src/ShaderNode/DataModels/VecFloatMul.hpp @@ -13,7 +13,7 @@ class VecFloatMul : public ShaderNode VecFloatMul(ShaderGraph& graph); ~VecFloatMul() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; QString caption() const override; QString name() const override; diff --git a/src/ShaderNode/DataModels/VecValue.hpp b/src/ShaderNode/DataModels/VecValue.hpp index 40035655c..b12607e17 100644 --- a/src/ShaderNode/DataModels/VecValue.hpp +++ b/src/ShaderNode/DataModels/VecValue.hpp @@ -18,7 +18,7 @@ class VecValue : public ShaderNode VecValue(ShaderGraph& graph); ~VecValue() = default; - Nz::ShaderAst::NodePtr BuildNode(Nz::ShaderAst::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; + nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override; void BuildNodeEdition(QFormLayout* layout) override; QString caption() const override; diff --git a/src/ShaderNode/DataModels/VecValue.inl b/src/ShaderNode/DataModels/VecValue.inl index e65924845..84ffd59e3 100644 --- a/src/ShaderNode/DataModels/VecValue.inl +++ b/src/ShaderNode/DataModels/VecValue.inl @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include #include @@ -12,12 +12,8 @@ ShaderNode(graph) { static_assert(ComponentCount <= s_vectorComponents.size()); - std::array defaultValues; - for (std::size_t i = 0; i < ComponentCount; ++i) - defaultValues[i] = (i == 3) ? 1.f : 0.f; - - m_value.Set(defaultValues.data()); + m_value[i] = (i == 3) ? 1.f : 0.f; UpdatePreview(); } @@ -70,7 +66,7 @@ std::shared_ptr VecValue::outData(QtNodes::Po values[i] = m_value[i]; out->preview = PreviewValues(1, 1); - out->preview(0, 0) = Nz::Vector4f(values[0], values[1], values[2], values[3]); + out->preview(0, 0) = nzsl::Vector4f(values[0], values[1], values[2], values[3]); return out; } @@ -127,12 +123,12 @@ void VecValue::BuildNodeEdition(QFormLayout* layout) } template -Nz::ShaderAst::NodePtr VecValue::BuildNode(Nz::ShaderAst::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const +nzsl::Ast::NodePtr VecValue::BuildNode(nzsl::Ast::ExpressionPtr* /*expressions*/, std::size_t count, std::size_t outputIndex) const { assert(count == 0); assert(outputIndex == 0); - return Nz::ShaderBuilder::Constant(m_value); + return nzsl::ShaderBuilder::Constant(m_value); } template diff --git a/src/ShaderNode/DataTypes/BoolData.inl b/src/ShaderNode/DataTypes/BoolData.inl index c12b8f72c..1a736c1ba 100644 --- a/src/ShaderNode/DataTypes/BoolData.inl +++ b/src/ShaderNode/DataTypes/BoolData.inl @@ -3,5 +3,5 @@ inline BoolData::BoolData() : preview(1, 1) { - preview(0, 0) = Nz::Vector4f(1.f, 1.f, 1.f, 0.f); + preview(0, 0) = nzsl::Vector4f(1.f, 1.f, 1.f, 0.f); } diff --git a/src/ShaderNode/DataTypes/FloatData.inl b/src/ShaderNode/DataTypes/FloatData.inl index 4f889aa90..0081ca894 100644 --- a/src/ShaderNode/DataTypes/FloatData.inl +++ b/src/ShaderNode/DataTypes/FloatData.inl @@ -3,5 +3,5 @@ inline FloatData::FloatData() : preview(1, 1) { - preview(0, 0) = Nz::Vector4f(1.f, 1.f, 1.f, 0.f); + preview(0, 0) = nzsl::Vector4f(1.f, 1.f, 1.f, 0.f); } diff --git a/src/ShaderNode/DataTypes/Matrix4Data.hpp b/src/ShaderNode/DataTypes/Matrix4Data.hpp index bd2e9e978..18f1383cf 100644 --- a/src/ShaderNode/DataTypes/Matrix4Data.hpp +++ b/src/ShaderNode/DataTypes/Matrix4Data.hpp @@ -3,7 +3,7 @@ #ifndef NAZARA_SHADERNODES_MATRIXDATA_HPP #define NAZARA_SHADERNODES_MATRIXDATA_HPP -#include +#include #include #include diff --git a/src/ShaderNode/DataTypes/TextureData.hpp b/src/ShaderNode/DataTypes/TextureData.hpp index ab3bba1f2..2d529fbeb 100644 --- a/src/ShaderNode/DataTypes/TextureData.hpp +++ b/src/ShaderNode/DataTypes/TextureData.hpp @@ -4,7 +4,7 @@ #define NAZARA_SHADERNODES_TEXTUREDATA_HPP #include -#include +#include #include struct TextureData : public QtNodes::NodeData diff --git a/src/ShaderNode/DataTypes/TextureData.inl b/src/ShaderNode/DataTypes/TextureData.inl index b542dff60..b9e923d41 100644 --- a/src/ShaderNode/DataTypes/TextureData.inl +++ b/src/ShaderNode/DataTypes/TextureData.inl @@ -3,5 +3,5 @@ inline TextureData::TextureData() : preview(64, 64) { - preview.Fill(Nz::Vector4f(1.f, 1.f, 1.f, 0.f)); + preview.Fill(nzsl::Vector4f(1.f, 1.f, 1.f, 0.f)); } diff --git a/src/ShaderNode/DataTypes/VecData.hpp b/src/ShaderNode/DataTypes/VecData.hpp index 1dcd265d5..400084699 100644 --- a/src/ShaderNode/DataTypes/VecData.hpp +++ b/src/ShaderNode/DataTypes/VecData.hpp @@ -3,8 +3,11 @@ #ifndef NAZARA_SHADERNODES_VECDATA_HPP #define NAZARA_SHADERNODES_VECDATA_HPP -#include +#include +#include +#include #include +#include #include struct VecData : public QtNodes::NodeData @@ -19,43 +22,7 @@ struct VecData : public QtNodes::NodeData PreviewValues preview; }; - -struct VecTypeDummy {}; - -template -struct VecTypeHelper; - -template<> -struct VecTypeHelper<0> -{ - using Type = VecTypeDummy; -}; - -template<> -struct VecTypeHelper<1> -{ - using Type = std::array; //< To allow [0] -}; - -template<> -struct VecTypeHelper<2> -{ - using Type = Nz::Vector2f; -}; - -template<> -struct VecTypeHelper<3> -{ - using Type = Nz::Vector3f; -}; - -template<> -struct VecTypeHelper<4> -{ - using Type = Nz::Vector4f; -}; - -template using VecType = typename VecTypeHelper::Type; +template using VecType = nzsl::Vector; constexpr std::array s_vectorComponents = { 'X', 'Y', 'Z', 'W' }; diff --git a/src/ShaderNode/DataTypes/VecData.inl b/src/ShaderNode/DataTypes/VecData.inl index 7264ca7e9..a4d629fc2 100644 --- a/src/ShaderNode/DataTypes/VecData.inl +++ b/src/ShaderNode/DataTypes/VecData.inl @@ -4,7 +4,7 @@ inline VecData::VecData(std::size_t ComponentCount) : componentCount(ComponentCount), preview(64, 64) { - preview.Fill(Nz::Vector4f(1.f, 1.f, 1.f, 0.f)); + preview.Fill(nzsl::Vector4f(1.f, 1.f, 1.f, 0.f)); } inline QtNodes::NodeDataType VecData::type() const diff --git a/src/ShaderNode/Previews/PreviewValues.cpp b/src/ShaderNode/Previews/PreviewValues.cpp index 2d3574fcb..5467d029d 100644 --- a/src/ShaderNode/Previews/PreviewValues.cpp +++ b/src/ShaderNode/Previews/PreviewValues.cpp @@ -13,7 +13,7 @@ m_width(width) m_values.resize(m_width * m_height); //< RGBA } -void PreviewValues::Fill(const Nz::Vector4f& value) +void PreviewValues::Fill(const nzsl::Vector4f& value) { std::fill(m_values.begin(), m_values.end(), value); } @@ -24,7 +24,7 @@ QImage PreviewValues::GenerateImage() const Nz::UInt8* ptr = preview.bits(); - const Nz::Vector4f* src = m_values.data(); + const nzsl::Vector4f* src = m_values.data(); for (std::size_t i = 0; i < m_values.size(); ++i) { for (std::size_t y = 0; y < 4; ++y) @@ -52,7 +52,7 @@ PreviewValues PreviewValues::Resized(std::size_t newWidth, std::size_t newHeight return resizedPreview; } -Nz::Vector4f PreviewValues::Sample(float u, float v) const +nzsl::Vector4f PreviewValues::Sample(float u, float v) const { // Bilinear filtering float x = std::clamp(u * m_width, 0.f, m_width - 1.f); @@ -64,7 +64,7 @@ Nz::Vector4f PreviewValues::Sample(float u, float v) const float dX = x - iX; float dY = y - iY; - auto ColorAt = [&](std::size_t x, std::size_t y) -> Nz::Vector4f + auto ColorAt = [&](std::size_t x, std::size_t y) -> nzsl::Vector4f { x = std::min(x, m_width - 1); y = std::min(y, m_height - 1); @@ -72,22 +72,22 @@ Nz::Vector4f PreviewValues::Sample(float u, float v) const return m_values[y * m_width + x]; }; - Nz::Vector4f d00 = ColorAt(iX, iY); - Nz::Vector4f d10 = ColorAt(iX + 1, iY); - Nz::Vector4f d01 = ColorAt(iX, iY + 1); - Nz::Vector4f d11 = ColorAt(iX + 1, iY + 1); + nzsl::Vector4f d00 = ColorAt(iX, iY); + nzsl::Vector4f d10 = ColorAt(iX + 1, iY); + nzsl::Vector4f d01 = ColorAt(iX, iY + 1); + nzsl::Vector4f d11 = ColorAt(iX + 1, iY + 1); return Nz::Lerp(Nz::Lerp(d00, d10, dX), Nz::Lerp(d01, d11, dX), dY); } -Nz::Vector4f& PreviewValues::operator()(std::size_t x, std::size_t y) +nzsl::Vector4f& PreviewValues::operator()(std::size_t x, std::size_t y) { assert(x < m_width); assert(y < m_height); return m_values[y * m_width + x]; } -Nz::Vector4f PreviewValues::operator()(std::size_t x, std::size_t y) const +nzsl::Vector4f PreviewValues::operator()(std::size_t x, std::size_t y) const { assert(x < m_width); assert(y < m_height); diff --git a/src/ShaderNode/Previews/PreviewValues.hpp b/src/ShaderNode/Previews/PreviewValues.hpp index 47ce14680..a69ca68d6 100644 --- a/src/ShaderNode/Previews/PreviewValues.hpp +++ b/src/ShaderNode/Previews/PreviewValues.hpp @@ -4,8 +4,8 @@ #define NAZARA_SHADERNODES_PREVIEWVALUES_HPP #include -#include #include +#include #include #include @@ -20,21 +20,21 @@ class PreviewValues PreviewValues(PreviewValues&&) = default; ~PreviewValues() = default; - void Fill(const Nz::Vector4f& value); + void Fill(const nzsl::Vector4f& value); QImage GenerateImage() const; - inline Nz::Vector4f* GetData(); - inline const Nz::Vector4f* GetData() const; + inline nzsl::Vector4f* GetData(); + inline const nzsl::Vector4f* GetData() const; inline std::size_t GetHeight() const; inline std::size_t GetWidth() const; PreviewValues Resized(std::size_t newWidth, std::size_t newHeight) const; - Nz::Vector4f Sample(float u, float v) const; + nzsl::Vector4f Sample(float u, float v) const; - Nz::Vector4f& operator()(std::size_t x, std::size_t y); - Nz::Vector4f operator()(std::size_t x, std::size_t y) const; + nzsl::Vector4f& operator()(std::size_t x, std::size_t y); + nzsl::Vector4f operator()(std::size_t x, std::size_t y) const; PreviewValues& operator=(const PreviewValues&) = default; PreviewValues& operator=(PreviewValues&&) = default; @@ -42,7 +42,7 @@ class PreviewValues private: std::size_t m_height; std::size_t m_width; - std::vector m_values; + std::vector m_values; }; #include diff --git a/src/ShaderNode/Previews/PreviewValues.inl b/src/ShaderNode/Previews/PreviewValues.inl index 3efbebc39..af243bb5c 100644 --- a/src/ShaderNode/Previews/PreviewValues.inl +++ b/src/ShaderNode/Previews/PreviewValues.inl @@ -1,11 +1,11 @@ #include -inline Nz::Vector4f* PreviewValues::GetData() +inline nzsl::Vector4f* PreviewValues::GetData() { return m_values.data(); } -inline const Nz::Vector4f* PreviewValues::GetData() const +inline const nzsl::Vector4f* PreviewValues::GetData() const { return m_values.data(); } diff --git a/src/ShaderNode/Previews/QuadPreview.cpp b/src/ShaderNode/Previews/QuadPreview.cpp index ce6155903..bae037857 100644 --- a/src/ShaderNode/Previews/QuadPreview.cpp +++ b/src/ShaderNode/Previews/QuadPreview.cpp @@ -6,7 +6,7 @@ PreviewValues QuadPreview::GetPreview(InputRole role, std::size_t roleIndex) con if (role != InputRole::TexCoord) { PreviewValues dummy(1, 1); - dummy(0, 0) = Nz::Vector4f::Zero(); + dummy(0, 0) = nzsl::Vector4f(0.f, 0.f, 0.f, 0.f); return dummy; } @@ -19,7 +19,7 @@ PreviewValues QuadPreview::GetPreview(InputRole role, std::size_t roleIndex) con for (std::size_t y = 0; y < uv.GetHeight(); ++y) { for (std::size_t x = 0; x < uv.GetWidth(); ++x) - uv(x, y) = Nz::Vector4f(x * invWidth, y * invHeight, 0.f, 1.f); + uv(x, y) = nzsl::Vector4f(x * invWidth, y * invHeight, 0.f, 1.f); } return uv; diff --git a/src/ShaderNode/ShaderGraph.cpp b/src/ShaderNode/ShaderGraph.cpp index 46ba7d67f..e2cbe6a2b 100644 --- a/src/ShaderNode/ShaderGraph.cpp +++ b/src/ShaderNode/ShaderGraph.cpp @@ -1,9 +1,9 @@ #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include @@ -452,19 +452,19 @@ QJsonObject ShaderGraph::Save() return sceneJson; } -Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const +nzsl::Ast::ModulePtr ShaderGraph::ToModule() const { - Nz::ShaderAst::ModulePtr shaderModule = std::make_shared(100); + nzsl::Ast::ModulePtr shaderModule = std::make_shared(100); // Declare all options for (const auto& option : m_options) - shaderModule->rootNode->statements.push_back(Nz::ShaderBuilder::DeclareOption(option.name, Nz::ShaderAst::ExpressionType{ Nz::ShaderAst::PrimitiveType::Boolean })); + shaderModule->rootNode->statements.push_back(nzsl::ShaderBuilder::DeclareOption(option.name, nzsl::Ast::ExpressionType{ nzsl::Ast::PrimitiveType::Boolean })); // Declare all structures for (const auto& structInfo : m_structs) { - Nz::ShaderAst::StructDescription structDesc; - structDesc.layout = Nz::StructLayout::Std140; + nzsl::Ast::StructDescription structDesc; + structDesc.layout = nzsl::StructLayout::Std140; structDesc.name = structInfo.name; for (const auto& memberInfo : structInfo.members) @@ -474,11 +474,11 @@ Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const structMember.type = ToShaderExpressionType(memberInfo.type); } - shaderModule->rootNode->statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(structDesc), false)); + shaderModule->rootNode->statements.push_back(nzsl::ShaderBuilder::DeclareStruct(std::move(structDesc), false)); } // External block - auto external = std::make_unique(); + auto external = std::make_unique(); for (const auto& buffer : m_buffers) { @@ -491,7 +491,7 @@ Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const extVar.bindingIndex = buffer.bindingIndex; extVar.bindingSet = buffer.setIndex; extVar.name = buffer.name; - extVar.type = Nz::ShaderAst::ExpressionPtr{ Nz::ShaderBuilder::Identifier(structInfo.name) }; + extVar.type = nzsl::Ast::ExpressionPtr{ nzsl::ShaderBuilder::Identifier(structInfo.name) }; } for (const auto& texture : m_textures) @@ -509,7 +509,7 @@ Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const // Inputs / outputs if (!m_inputs.empty()) { - Nz::ShaderAst::StructDescription structDesc; + nzsl::Ast::StructDescription structDesc; structDesc.name = "InputData"; for (const auto& input : m_inputs) @@ -520,12 +520,12 @@ Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const structMember.locationIndex = input.locationIndex; } - shaderModule->rootNode->statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(structDesc), false)); + shaderModule->rootNode->statements.push_back(nzsl::ShaderBuilder::DeclareStruct(std::move(structDesc), false)); } if (!m_outputs.empty()) { - Nz::ShaderAst::StructDescription structDesc; + nzsl::Ast::StructDescription structDesc; structDesc.name = "OutputData"; for (const auto& output : m_outputs) @@ -539,12 +539,12 @@ Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const if (m_type == ShaderType::Vertex) { auto& position = structDesc.members.emplace_back(); - position.builtin = Nz::ShaderAst::BuiltinEntry::VertexPosition; + position.builtin = nzsl::Ast::BuiltinEntry::VertexPosition; position.name = "position"; - position.type = Nz::ShaderAst::ExpressionType{ Nz::ShaderAst::VectorType{ 4, Nz::ShaderAst::PrimitiveType::Float32 } }; + position.type = nzsl::Ast::ExpressionType{ nzsl::Ast::VectorType{ 4, nzsl::Ast::PrimitiveType::Float32 } }; } - shaderModule->rootNode->statements.push_back(Nz::ShaderBuilder::DeclareStruct(std::move(structDesc), false)); + shaderModule->rootNode->statements.push_back(nzsl::ShaderBuilder::DeclareStruct(std::move(structDesc), false)); } // Functions @@ -553,9 +553,9 @@ Nz::ShaderAst::ModulePtr ShaderGraph::ToModule() const return shaderModule; } -Nz::ShaderAst::ExpressionValue ShaderGraph::ToShaderExpressionType(const std::variant& type) const +nzsl::Ast::ExpressionValue ShaderGraph::ToShaderExpressionType(const std::variant& type) const { - return std::visit([&](auto&& arg) -> Nz::ShaderAst::ExpressionValue + return std::visit([&](auto&& arg) -> nzsl::Ast::ExpressionValue { using T = std::decay_t; if constexpr (std::is_same_v) @@ -564,7 +564,7 @@ Nz::ShaderAst::ExpressionValue ShaderGraph::ToSha { assert(arg < m_structs.size()); const auto& s = m_structs[arg]; - return Nz::ShaderAst::ExpressionPtr{ Nz::ShaderBuilder::Identifier(s.name) }; + return nzsl::Ast::ExpressionPtr{ nzsl::ShaderBuilder::Identifier(s.name) }; } else static_assert(Nz::AlwaysFalse::value, "non-exhaustive visitor"); @@ -685,42 +685,42 @@ QtNodes::NodeDataType ShaderGraph::ToNodeDataType(PrimitiveType type) throw std::runtime_error("Unhandled input type"); } -Nz::ShaderAst::ExpressionType ShaderGraph::ToShaderExpressionType(PrimitiveType type) +nzsl::Ast::ExpressionType ShaderGraph::ToShaderExpressionType(PrimitiveType type) { switch (type) { - case PrimitiveType::Bool: return Nz::ShaderAst::PrimitiveType::Boolean; - case PrimitiveType::Float1: return Nz::ShaderAst::PrimitiveType::Float32; - case PrimitiveType::Float2: return Nz::ShaderAst::VectorType{ 2, Nz::ShaderAst::PrimitiveType::Float32 }; - case PrimitiveType::Float3: return Nz::ShaderAst::VectorType{ 3, Nz::ShaderAst::PrimitiveType::Float32 }; - case PrimitiveType::Float4: return Nz::ShaderAst::VectorType{ 4, Nz::ShaderAst::PrimitiveType::Float32 }; - case PrimitiveType::Mat4x4: return Nz::ShaderAst::MatrixType{ 4, 4, Nz::ShaderAst::PrimitiveType::Float32 }; + case PrimitiveType::Bool: return nzsl::Ast::PrimitiveType::Boolean; + case PrimitiveType::Float1: return nzsl::Ast::PrimitiveType::Float32; + case PrimitiveType::Float2: return nzsl::Ast::VectorType{ 2, nzsl::Ast::PrimitiveType::Float32 }; + case PrimitiveType::Float3: return nzsl::Ast::VectorType{ 3, nzsl::Ast::PrimitiveType::Float32 }; + case PrimitiveType::Float4: return nzsl::Ast::VectorType{ 4, nzsl::Ast::PrimitiveType::Float32 }; + case PrimitiveType::Mat4x4: return nzsl::Ast::MatrixType{ 4, 4, nzsl::Ast::PrimitiveType::Float32 }; } assert(false); throw std::runtime_error("Unhandled primitive type"); } -Nz::ShaderAst::ExpressionType ShaderGraph::ToShaderExpressionType(TextureType type) +nzsl::Ast::ExpressionType ShaderGraph::ToShaderExpressionType(TextureType type) { switch (type) { - case TextureType::Sampler2D: return Nz::ShaderAst::SamplerType{ Nz::ImageType::E2D, Nz::ShaderAst::PrimitiveType::Float32 }; + case TextureType::Sampler2D: return nzsl::Ast::SamplerType{ nzsl::ImageType::E2D, nzsl::Ast::PrimitiveType::Float32 }; } assert(false); throw std::runtime_error("Unhandled texture type"); } -Nz::ShaderStageType ShaderGraph::ToShaderStageType(ShaderType type) +nzsl::ShaderStageType ShaderGraph::ToShaderStageType(ShaderType type) { switch (type) { case ShaderType::NotSet: throw std::runtime_error("Invalid shader type"); - case ShaderType::Fragment: return Nz::ShaderStageType::Fragment; - case ShaderType::Vertex: return Nz::ShaderStageType::Vertex; + case ShaderType::Fragment: return nzsl::ShaderStageType::Fragment; + case ShaderType::Vertex: return nzsl::ShaderStageType::Vertex; } assert(false); @@ -802,23 +802,23 @@ std::shared_ptr ShaderGraph::BuildRegistry() return registry; } -std::unique_ptr ShaderGraph::ToFunction() const +std::unique_ptr ShaderGraph::ToFunction() const { - std::vector statements; + std::vector statements; - std::vector parameters; + std::vector parameters; if (!m_inputs.empty()) { auto& parameter = parameters.emplace_back(); parameter.name = "input"; - parameter.type = Nz::ShaderAst::ExpressionPtr{ Nz::ShaderBuilder::Identifier("InputData") }; + parameter.type = nzsl::Ast::ExpressionPtr{ nzsl::ShaderBuilder::Identifier("InputData") }; } - Nz::ShaderAst::ExpressionPtr returnType; + nzsl::Ast::ExpressionPtr returnType; if (!m_outputs.empty()) { - returnType = Nz::ShaderBuilder::Identifier("OutputData"); - statements.push_back(Nz::ShaderBuilder::DeclareVariable("output", Nz::ShaderAst::Clone(*returnType), nullptr)); + returnType = nzsl::ShaderBuilder::Identifier("OutputData"); + statements.push_back(nzsl::ShaderBuilder::DeclareVariable("output", nzsl::Ast::Clone(*returnType), nullptr)); } using Key = QPair; @@ -860,13 +860,13 @@ std::unique_ptr ShaderGraph::ToFunction } }); - std::map variableExpressions; + std::map variableExpressions; unsigned int varCount = 0; std::unordered_set usedVariableNames; - std::function HandleNode; - HandleNode = [&](QtNodes::Node* node, std::size_t portIndex) -> Nz::ShaderAst::NodePtr + std::function HandleNode; + HandleNode = [&](QtNodes::Node* node, std::size_t portIndex) -> nzsl::Ast::NodePtr { ShaderNode* shaderNode = static_cast(node->nodeDataModel()); if (shaderNode->validationState() != QtNodes::NodeValidationState::Valid) @@ -874,13 +874,13 @@ std::unique_ptr ShaderGraph::ToFunction qDebug() << shaderNode->name() << node->id(); if (auto it = variableExpressions.find(BuildKey(node->id(), portIndex)); it != variableExpressions.end()) - return Nz::ShaderAst::Clone(*it->second); + return nzsl::Ast::Clone(*it->second); auto it = usageCount.find(BuildKey(node->id(), portIndex)); assert(it != usageCount.end()); std::size_t inputCount = shaderNode->nPorts(QtNodes::PortType::In); - Nz::StackArray expressions = NazaraStackArray(Nz::ShaderAst::ExpressionPtr, inputCount); + Nz::StackArray expressions = NazaraStackArray(nzsl::Ast::ExpressionPtr, inputCount); std::size_t i = 0; for (const auto& connectionSet : node->nodeState().getEntries(QtNodes::PortType::In)) @@ -888,26 +888,26 @@ std::unique_ptr ShaderGraph::ToFunction for (const auto& [uuid, conn] : connectionSet) { assert(i < expressions.size()); - Nz::ShaderAst::NodePtr inputNode = HandleNode(conn->getNode(QtNodes::PortType::Out), conn->getPortIndex(QtNodes::PortType::Out)); - if (!Nz::ShaderAst::IsExpression(inputNode->GetType())) + nzsl::Ast::NodePtr inputNode = HandleNode(conn->getNode(QtNodes::PortType::Out), conn->getPortIndex(QtNodes::PortType::Out)); + if (!nzsl::Ast::IsExpression(inputNode->GetType())) throw std::runtime_error("unexpected statement"); - expressions[i] = Nz::StaticUniquePointerCast(std::move(inputNode)); + expressions[i] = Nz::StaticUniquePointerCast(std::move(inputNode)); i++; } } auto astNode = shaderNode->BuildNode(expressions.data(), expressions.size(), portIndex); - if (!Nz::ShaderAst::IsExpression(astNode->GetType())) + if (!nzsl::Ast::IsExpression(astNode->GetType())) return astNode; - Nz::ShaderAst::ExpressionPtr expression = Nz::StaticUniquePointerCast(std::move(astNode)); + nzsl::Ast::ExpressionPtr expression = Nz::StaticUniquePointerCast(std::move(astNode)); const std::string& variableName = shaderNode->GetVariableName(); if (it->second > 1 || !variableName.empty()) { - Nz::ShaderAst::ExpressionPtr varExpression; - if (Nz::ShaderAst::GetExpressionCategory(*expression) == Nz::ShaderAst::ExpressionCategory::RValue) + nzsl::Ast::ExpressionPtr varExpression; + if (nzsl::Ast::GetExpressionCategory(*expression) == nzsl::Ast::ExpressionCategory::RValue) { std::string name; if (variableName.empty()) @@ -920,14 +920,14 @@ std::unique_ptr ShaderGraph::ToFunction usedVariableNames.insert(name); - statements.emplace_back(Nz::ShaderBuilder::DeclareVariable(name, std::move(expression))); + statements.emplace_back(nzsl::ShaderBuilder::DeclareVariable(name, std::move(expression))); - varExpression = Nz::ShaderBuilder::Identifier(name); + varExpression = nzsl::ShaderBuilder::Identifier(name); } else varExpression = std::move(expression); - variableExpressions[BuildKey(node->id(), portIndex)] = Nz::ShaderAst::Clone(*varExpression); + variableExpressions[BuildKey(node->id(), portIndex)] = nzsl::Ast::Clone(*varExpression); return varExpression; } @@ -946,14 +946,14 @@ std::unique_ptr ShaderGraph::ToFunction for (QtNodes::Node* node : outputNodes) { auto astNode = HandleNode(node, 0); - if (!Nz::ShaderAst::IsStatement(astNode->GetType())) - statements.emplace_back(Nz::ShaderBuilder::ExpressionStatement(Nz::StaticUniquePointerCast(std::move(astNode)))); + if (!nzsl::Ast::IsStatement(astNode->GetType())) + statements.emplace_back(nzsl::ShaderBuilder::ExpressionStatement(Nz::StaticUniquePointerCast(std::move(astNode)))); else - statements.emplace_back(Nz::StaticUniquePointerCast(std::move(astNode))); + statements.emplace_back(Nz::StaticUniquePointerCast(std::move(astNode))); } if (!m_outputs.empty()) - statements.push_back(Nz::ShaderBuilder::Return(Nz::ShaderBuilder::Identifier("output"))); + statements.push_back(nzsl::ShaderBuilder::Return(nzsl::ShaderBuilder::Identifier("output"))); - return Nz::ShaderBuilder::DeclareFunction(ToShaderStageType(m_type), "main", std::move(parameters), std::move(statements), std::move(returnType)); + return nzsl::ShaderBuilder::DeclareFunction(ToShaderStageType(m_type), "main", std::move(parameters), std::move(statements), std::move(returnType)); } diff --git a/src/ShaderNode/ShaderGraph.hpp b/src/ShaderNode/ShaderGraph.hpp index bcd0333d6..b887f1c5a 100644 --- a/src/ShaderNode/ShaderGraph.hpp +++ b/src/ShaderNode/ShaderGraph.hpp @@ -3,9 +3,9 @@ #ifndef NAZARA_SHADERNODES_SHADERGRAPH_HPP #define NAZARA_SHADERNODES_SHADERGRAPH_HPP -#include +#include #include -#include +#include #include #include #include @@ -67,8 +67,8 @@ class ShaderGraph void Load(const QJsonObject& data); QJsonObject Save(); - Nz::ShaderAst::ModulePtr ToModule() const; - Nz::ShaderAst::ExpressionValue ToShaderExpressionType(const std::variant& type) const; + nzsl::Ast::ModulePtr ToModule() const; + nzsl::Ast::ExpressionValue ToShaderExpressionType(const std::variant& type) const; void UpdateBuffer(std::size_t bufferIndex, std::string name, BufferType bufferType, std::size_t structIndex, std::size_t setIndex, std::size_t bindingIndex); void UpdateOption(std::size_t optionIndex, std::string option); @@ -148,13 +148,13 @@ class ShaderGraph NazaraSignal(OnTypeUpdated, ShaderGraph*); static QtNodes::NodeDataType ToNodeDataType(PrimitiveType type); - static Nz::ShaderAst::ExpressionType ToShaderExpressionType(PrimitiveType type); - static Nz::ShaderAst::ExpressionType ToShaderExpressionType(TextureType type); - static Nz::ShaderStageType ToShaderStageType(ShaderType type); + static nzsl::Ast::ExpressionType ToShaderExpressionType(PrimitiveType type); + static nzsl::Ast::ExpressionType ToShaderExpressionType(TextureType type); + static nzsl::ShaderStageType ToShaderStageType(ShaderType type); private: std::shared_ptr BuildRegistry(); - std::unique_ptr ToFunction() const; + std::unique_ptr ToFunction() const; mutable std::optional m_flowScene; std::vector m_buffers; diff --git a/src/ShaderNode/Widgets/CodeOutputWidget.cpp b/src/ShaderNode/Widgets/CodeOutputWidget.cpp index e8d25c444..183c8ec6c 100644 --- a/src/ShaderNode/Widgets/CodeOutputWidget.cpp +++ b/src/ShaderNode/Widgets/CodeOutputWidget.cpp @@ -1,11 +1,11 @@ #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -56,7 +56,7 @@ void CodeOutputWidget::Refresh() { try { - Nz::ShaderWriter::States states; + nzsl::ShaderWriter::States states; for (std::size_t i = 0; i < m_shaderGraph.GetOptionCount(); ++i) { @@ -64,18 +64,18 @@ void CodeOutputWidget::Refresh() states.optionValues[Nz::CRC32(option.name)] = m_shaderGraph.IsOptionEnabled(i); } - Nz::ShaderAst::ModulePtr shaderModule = m_shaderGraph.ToModule(); + nzsl::Ast::ModulePtr shaderModule = m_shaderGraph.ToModule(); if (m_optimisationCheckbox->isChecked()) { - Nz::ShaderAst::SanitizeVisitor::Options sanitizeOptions; + nzsl::Ast::SanitizeVisitor::Options sanitizeOptions; sanitizeOptions.optionValues = states.optionValues; - shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, sanitizeOptions); + shaderModule = nzsl::Ast::Sanitize(*shaderModule, sanitizeOptions); - Nz::ShaderAst::AstConstantPropagationVisitor optimiser; - shaderModule = Nz::ShaderAst::PropagateConstants(*shaderModule); - shaderModule = Nz::ShaderAst::EliminateUnusedPass(*shaderModule); + nzsl::Ast::ConstantPropagationVisitor optimiser; + shaderModule = nzsl::Ast::PropagateConstants(*shaderModule); + shaderModule = nzsl::Ast::EliminateUnusedPass(*shaderModule); } std::string output; @@ -84,31 +84,31 @@ void CodeOutputWidget::Refresh() { case OutputLanguage::GLSL: { - Nz::GlslWriter::BindingMapping bindingMapping; + nzsl::GlslWriter::BindingMapping bindingMapping; for (const auto& buffer : m_shaderGraph.GetBuffers()) bindingMapping.emplace(Nz::UInt64(buffer.setIndex) << 32 | Nz::UInt64(buffer.bindingIndex), bindingMapping.size()); for (const auto& texture : m_shaderGraph.GetTextures()) bindingMapping.emplace(Nz::UInt64(texture.setIndex) << 32 | Nz::UInt64(texture.bindingIndex), bindingMapping.size()); - Nz::GlslWriter writer; + nzsl::GlslWriter writer; output = writer.Generate(ShaderGraph::ToShaderStageType(m_shaderGraph.GetType()), *shaderModule, bindingMapping, states); break; } case OutputLanguage::NZSL: { - Nz::LangWriter writer; + nzsl::LangWriter writer; output = writer.Generate(*shaderModule, states); break; } case OutputLanguage::SpirV: { - Nz::SpirvWriter writer; + nzsl::SpirvWriter writer; std::vector spirv = writer.Generate(*shaderModule, states); - Nz::SpirvPrinter printer; + nzsl::SpirvPrinter printer; output = printer.Print(spirv.data(), spirv.size()); break; } diff --git a/src/ShaderNode/Widgets/MainWindow.cpp b/src/ShaderNode/Widgets/MainWindow.cpp index 8264bc003..194da1a6b 100644 --- a/src/ShaderNode/Widgets/MainWindow.cpp +++ b/src/ShaderNode/Widgets/MainWindow.cpp @@ -1,7 +1,7 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -183,15 +183,19 @@ void MainWindow::OnCompile() { auto shaderModule = m_shaderGraph.ToModule(); - QString fileName = QFileDialog::getSaveFileName(nullptr, tr("Save shader"), QString(), tr("Shader Files (*.shader)")); + QString fileName = QFileDialog::getSaveFileName(nullptr, tr("Save shader"), QString(), tr("Shader Files (*.nzslb)")); if (fileName.isEmpty()) return; - if (!fileName.endsWith("shader", Qt::CaseInsensitive)) - fileName += ".shader"; + if (!fileName.endsWith("nzslb", Qt::CaseInsensitive)) + fileName += ".nzslb"; Nz::File file(fileName.toStdString(), Nz::OpenMode::WriteOnly); - file.Write(Nz::ShaderAst::SerializeShader(shaderModule)); + nzsl::Serializer serializer; + nzsl::Ast::SerializeShader(serializer, shaderModule); + + const std::vector& data = serializer.GetData(); + file.Write(data.data(), data.size()); } catch (const std::exception& e) { diff --git a/tests/Engine/Core/AlgorithmCoreTest.cpp b/tests/Engine/Core/AlgorithmCoreTest.cpp index 23b222aa7..5f517c87d 100644 --- a/tests/Engine/Core/AlgorithmCoreTest.cpp +++ b/tests/Engine/Core/AlgorithmCoreTest.cpp @@ -9,31 +9,6 @@ std::filesystem::path GetResourceDir(); -TEST_CASE("Apply", "[CORE][ALGORITHM]") -{ - SECTION("Apply lambda to two vector2") - { - Nz::Vector2 vector = Nz::Vector2::Unit(); - auto lambda = [](const Nz::Vector2& vec1, const Nz::Vector2& vec2) - { - return vec1 + vec2; - }; - - Nz::Vector2 result = Nz::Apply(lambda, std::make_tuple(vector, vector)); - - REQUIRE(result == (Nz::Vector2::Unit() * 2)); - } - - /*SECTION("Apply member function to vector2") - { - Nz::Vector2 vector = Nz::Vector2::Unit(); - - int result = Nz::Apply(vector, (int(Nz::Vector2::*)(const Nz::Vector2&)) &Nz::Vector2::Distance, std::make_tuple(vector)); - - REQUIRE(result == 0); - }*/ -} - TEST_CASE("ComputeHash", "[CORE][ALGORITHM]") { std::filesystem::path testFilePath = GetResourceDir() / "Logo.png"; diff --git a/tests/Engine/Core/BitsetTest.cpp b/tests/Engine/Core/BitsetTest.cpp deleted file mode 100644 index 888ae3d74..000000000 --- a/tests/Engine/Core/BitsetTest.cpp +++ /dev/null @@ -1,372 +0,0 @@ -#include -#include -#include -#include -#include -#include - -template void Check(const char* title); -template void CheckAppend(const char* title); -template void CheckBitOps(const char* title); -template void CheckBitOpsMultipleBlocks(const char* title); -template void CheckConstructor(const char* title); -template void CheckCopyMoveSwap(const char* title); -template void CheckRead(const char* title); -template void CheckReverse(const char* title); - -SCENARIO("Bitset", "[CORE][BITSET]") -{ - Check("Bitset made of 8bits blocks"); - Check("Bitset made of 16bits blocks"); - Check("Bitset made of 32bits blocks"); - Check("Bitset made of 64bits blocks"); -} - -template -void Check(const char* title) -{ - CheckConstructor(title); - CheckCopyMoveSwap(title); - - CheckBitOps(title); - CheckBitOpsMultipleBlocks(title); - - CheckAppend(title); - CheckRead(title); - CheckReverse(title); -} - -template -void CheckAppend(const char* title) -{ - SECTION(title) - { - GIVEN("An empty bitset filled by bytes") - { - #define BitVal1 00110111 - #define BitVal2 11011110 - #define BitVal3 01000010 - std::array data = {{NazaraPrefixMacro(BitVal1, 0b), NazaraPrefixMacro(BitVal2, 0b), NazaraPrefixMacro(BitVal3, 0b)}}; - const char result[] = NazaraStringifyMacro(BitVal3) NazaraStringifyMacro(BitVal2) NazaraStringifyMacro(BitVal1); - std::size_t bitCount = data.size() * 8; - #undef BitVal1 - #undef BitVal2 - #undef BitVal3 - - std::array, 7> tests = { - { - {"We append bits one by one", 1}, - {"We append bits two by two", 2}, - {"We append bits three by three", 3}, - {"We append bits four by four", 4}, - {"We append bits six by six", 6}, - {"We append bits byte by byte", 8}, - {"We append bits twelve by twelve", 12} - } - }; - - for (auto& pair : tests) - { - WHEN(pair.first) - { - Nz::Bitset bitset; - - for (std::size_t i = 0; i < bitCount; i += pair.second) - { - Nz::UInt16 value = data[i / 8] >> (i % 8); - if ((i % 8) + pair.second > 8 && i/8 != data.size()-1) - value |= static_cast(data[i / 8 + 1]) << (8 - (i % 8)); - - bitset.AppendBits(value, pair.second); - } - - REQUIRE(bitset.GetSize() == bitCount); - - Nz::Bitset expectedBitset(result); - - CHECK(bitset == expectedBitset); - CHECK(bitset.GetBlockCount() == (bitCount / bitset.bitsPerBlock + std::min(1, bitCount % bitset.bitsPerBlock))); - } - } - } - } -} - -template -void CheckBitOps(const char* title) -{ - SECTION(title) - { - GIVEN("Two bitsets") - { - Nz::Bitset first("01001"); - Nz::Bitset second("10111"); - - WHEN("We perform operators") - { - Nz::Bitset andBitset = first & second; - Nz::Bitset orBitset = first | second; - Nz::Bitset xorBitset = first ^ second; - - THEN("They should operate as logical operators") - { - CHECK(andBitset == Nz::Bitset("00001")); - CHECK(orBitset == Nz::Bitset("11111")); - CHECK(orBitset.TestAll()); - CHECK(xorBitset == Nz::Bitset("11110")); - CHECK(!xorBitset.TestAll()); - CHECK((~orBitset).TestNone()); - } - } - - WHEN("We perform bit shifts") - { - first.ShiftLeft(1); - second.ShiftRight(2); - - THEN("We should obtain these") - { - CHECK(first == Nz::Bitset("10010")); - CHECK(second == Nz::Bitset("101")); - } - } - } - } -} - -template -void CheckBitOpsMultipleBlocks(const char* title) -{ - SECTION(title) - { - GIVEN("Two bitsets") - { - Nz::Bitset first("01001011010010101001010011010101001"); - Nz::Bitset second("10111111101101110110111101101110110"); - - WHEN("We perform operators") - { - Nz::Bitset andBitset = first & second; - Nz::Bitset orBitset = first | second; - Nz::Bitset xorBitset = first ^ second; - - THEN("They should operate as logical operators") - { - CHECK(andBitset == Nz::Bitset("00001011000000100000010001000100000")); - CHECK(orBitset == Nz::Bitset("11111111111111111111111111111111111")); - CHECK(orBitset.TestAll()); - CHECK(xorBitset == Nz::Bitset("11110100111111011111101110111011111")); - CHECK(!xorBitset.TestAll()); - CHECK((~orBitset).TestNone()); - } - } - - WHEN("We perform bit shifts") - { - first.ShiftLeft(16); - second.ShiftRight(16); - - THEN("We should obtain these") - { - CHECK(first == Nz::Bitset("10010100110101010010000000000000000")); - first.ShiftLeft(1); - CHECK(first == Nz::Bitset("00101001101010100100000000000000000")); - CHECK(second == Nz::Bitset("1011111110110111011")); - second.ShiftRight(1); - CHECK(second == Nz::Bitset("101111111011011101")); - } - } - } - } -} - -template -void CheckConstructor(const char* title) -{ - SECTION(title) - { - GIVEN("Allocate and constructor") - { - Nz::Bitset bitset(3, false); - - THEN("Capacity is 3 and size is 3") - { - CHECK(bitset.GetSize() == 3); - CHECK(bitset.GetCapacity() >= 3); - } - } - - GIVEN("Iterator and default constructor") - { - std::string anotherDataString("0101"); - Nz::Bitset defaultByte; - Nz::Bitset anotherData(anotherDataString.c_str()); - - WHEN("We assign 'anotherData'") - { - defaultByte = anotherDataString; - CHECK(anotherData == defaultByte); - CHECK(defaultByte.GetSize() == 4); - CHECK(defaultByte.GetCapacity() >= 4); - CHECK(anotherData.GetSize() == 4); - CHECK(anotherData.GetCapacity() >= 4); - } - } - } -} - -template -void CheckCopyMoveSwap(const char* title) -{ - SECTION(title) - { - GIVEN("Copy and Move constructor") - { - Nz::Bitset originalArray(3, true); - - WHEN("We copy") - { - Nz::Bitset copyBitset(originalArray); - - THEN("We get a copy") - { - CHECK(copyBitset == originalArray); - - AND_WHEN("We modify one") - { - for (std::size_t i = 0; i < copyBitset.GetSize(); ++i) - copyBitset[i] = false; - - THEN("They are no more equal") - { - CHECK(copyBitset != originalArray); - CHECK(copyBitset == Nz::Bitset(3, false)); - } - } - } - } - - WHEN("We move") - { - Nz::Bitset moveBitset(std::move(originalArray)); - - THEN("These results are expected") - { - CHECK(moveBitset == Nz::Bitset(3, true)); - CHECK(originalArray.GetCapacity() == 0); - } - } - } - - GIVEN("Three bitsets") - { - Nz::Bitset first("01001"); - Nz::Bitset second("10110"); - Nz::Bitset third; - - WHEN("We swap first and third, then second and third and finally third and first") - { - Nz::Bitset oldFirst(first); - Nz::Bitset oldSecond(second); - - first.Swap(third); - std::swap(second, third); - third.Swap(first); - - THEN("First and second have been swapped and third is still empty.") - { - CHECK(oldFirst == second); - CHECK(oldSecond == first); - CHECK(third.GetSize() == 0); - } - } - } - } -} - -template -void CheckRead(const char* title) -{ - SECTION(title) - { - GIVEN("An empty bitset filled by reading") - { - #define BitVal1 10010101 - #define BitVal2 11010010 - #define BitVal3 01101010 - std::array data = {{NazaraPrefixMacro(BitVal1, 0b), NazaraPrefixMacro(BitVal2, 0b), NazaraPrefixMacro(BitVal3, 0b)}}; - const char result[] = NazaraStringifyMacro(BitVal3) NazaraStringifyMacro(BitVal2) NazaraStringifyMacro(BitVal1); - std::size_t bitCount = data.size() * 8; - #undef BitVal1 - #undef BitVal2 - #undef BitVal3 - - std::array, 8> tests = { - { - {"We read bits one by one", 1}, - {"We read bits two by two", 2}, - {"We read bits three by three", 3}, - {"We read bits four by four", 4}, - {"We read bits six by six", 6}, - {"We read bits byte by byte", 8}, - {"We read bits twelve by twelve", 12}, - {"We read bits all at once", 24} - } - }; - - for (auto& pair : tests) - { - WHEN(pair.first) - { - Nz::Bitset bitset; - - auto seq = bitset.Write(data.data(), pair.second); - for (std::size_t i = pair.second; i < bitCount; i += pair.second) - seq = bitset.Write(seq, pair.second); - - REQUIRE(bitset.GetSize() == bitCount); - - Nz::Bitset expectedBitset(result); - - CHECK(bitset == expectedBitset); - CHECK(bitset.GetBlockCount() == (bitCount / bitset.bitsPerBlock + std::min(1, bitCount % bitset.bitsPerBlock))); - } - } - } - } -} - -template -void CheckReverse(const char* title) -{ - SECTION(title) - { - GIVEN("A bitset") - { - std::string bits = "010011100010001101001111"; - Nz::Bitset expected(bits); - - WHEN("We reverse the order of bits") - { - Nz::Bitset bitset(bits); - bitset.Reverse(); - - THEN("The order of bits should be reversed") - { - std::string reversedBits = bits; - std::reverse(reversedBits.begin(), reversedBits.end()); - CHECK(bitset == Nz::Bitset(reversedBits)); - } - AND_WHEN("We reverse the bit order again") - { - bitset.Reverse(); - - THEN("It should be back to normal") - { - CHECK(bitset == expected); - } - } - } - } - } -} diff --git a/tests/Engine/Core/MemoryPoolTest.cpp b/tests/Engine/Core/MemoryPoolTest.cpp deleted file mode 100644 index be6370876..000000000 --- a/tests/Engine/Core/MemoryPoolTest.cpp +++ /dev/null @@ -1,141 +0,0 @@ -#include -#include - -#include - -namespace -{ - std::size_t allocationCount = 0; - - template - struct AllocatorTest : T - { - template - AllocatorTest(Args&&... args) : - T(std::forward(args)...) - { - allocationCount++; - } - - AllocatorTest(const AllocatorTest&) = delete; - AllocatorTest(AllocatorTest&&) = delete; - - ~AllocatorTest() - { - assert(allocationCount > 0); - allocationCount--; - } - }; -} - -SCENARIO("MemoryPool", "[CORE][MEMORYPOOL]") -{ - GIVEN("A MemoryPool to contain one Nz::Vector2") - { - using T = AllocatorTest>; - - allocationCount = 0; - - Nz::MemoryPool memoryPool(2); - CHECK(memoryPool.GetAllocatedEntryCount() == 0); - CHECK(memoryPool.GetBlockCount() == 1); - CHECK(memoryPool.GetBlockSize() == 2); - CHECK(memoryPool.GetFreeEntryCount() == 2); - CHECK(allocationCount == 0); - - WHEN("We construct a Nz::Vector2") - { - std::size_t index; - T* vector2 = memoryPool.Allocate(index, 1, 2); - CHECK(allocationCount == 1); - CHECK(memoryPool.GetAllocatedEntryCount() == 1); - CHECK(memoryPool.GetFreeEntryCount() == 1); - CHECK(memoryPool.RetrieveEntryIndex(vector2) == index); - - THEN("Memory is available") - { - vector2->x = 3; - REQUIRE(*vector2 == Nz::Vector2(3, 2)); - } - - memoryPool.Free(index); - CHECK(allocationCount == 0); - CHECK(memoryPool.GetAllocatedEntryCount() == 0); - CHECK(memoryPool.GetFreeEntryCount() == 2); - } - - WHEN("We construct three vectors") - { - CHECK(memoryPool.GetAllocatedEntryCount() == 0); - CHECK(memoryPool.GetFreeEntryCount() == 2); - - std::size_t index1, index2, index3; - T* vector1 = memoryPool.Allocate(index1, 1, 2); - CHECK(allocationCount == 1); - CHECK(memoryPool.GetAllocatedEntryCount() == 1); - CHECK(memoryPool.GetBlockCount() == 1); - CHECK(memoryPool.GetFreeEntryCount() == 1); - T* vector2 = memoryPool.Allocate(index2, 3, 4); - CHECK(allocationCount == 2); - CHECK(memoryPool.GetAllocatedEntryCount() == 2); - CHECK(memoryPool.GetBlockCount() == 1); - CHECK(memoryPool.GetFreeEntryCount() == 0); - T* vector3 = memoryPool.Allocate(index3, 5, 6); - CHECK(allocationCount == 3); - CHECK(memoryPool.GetAllocatedEntryCount() == 3); - CHECK(memoryPool.GetBlockCount() == 2); - CHECK(memoryPool.GetFreeEntryCount() == 1); //< a new block has been allocated - - CHECK(memoryPool.RetrieveEntryIndex(vector1) == index1); - CHECK(memoryPool.RetrieveEntryIndex(vector2) == index2); - CHECK(memoryPool.RetrieveEntryIndex(vector3) == index3); - - THEN("Memory is available") - { - vector1->x = 3; - vector2->y = 5; - CHECK(*vector1 == Nz::Vector2(3, 2)); - CHECK(*vector2 == Nz::Vector2(3, 5)); - CHECK(vector3->GetSquaredLength() == Approx(61.f)); - - AND_THEN("We iterate on the memory pool") - { - std::size_t count = 0; - int sumX = 0; - int sumY = 0; - for (T& vec : memoryPool) - { - count++; - sumX += vec.x; - sumY += vec.y; - } - - CHECK(count == 3); - CHECK(sumX == 11); - CHECK(sumY == 13); - } - } - - memoryPool.Reset(); - CHECK(allocationCount == 0); - CHECK(memoryPool.GetAllocatedEntryCount() == 0); - CHECK(memoryPool.GetBlockCount() == 2); - CHECK(memoryPool.GetFreeEntryCount() == 4); - - bool failure = false; - for (T& vec : memoryPool) - { - NazaraUnused(vec); - failure = true; - } - - CHECK_FALSE(failure); - - memoryPool.Clear(); - CHECK(allocationCount == 0); - CHECK(memoryPool.GetAllocatedEntryCount() == 0); - CHECK(memoryPool.GetBlockCount() == 0); - CHECK(memoryPool.GetFreeEntryCount() == 0); - } - } -} diff --git a/tests/Engine/Core/SignalTest.cpp b/tests/Engine/Core/SignalTest.cpp deleted file mode 100644 index 9c5726f91..000000000 --- a/tests/Engine/Core/SignalTest.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include - -struct Incrementer -{ - void increment(int* inc) - { - *inc += 1; - } -}; - -void increment(int* inc) -{ - *inc += 1; -} - -SCENARIO("Signal", "[CORE][SIGNAL]") -{ - GIVEN("A signal") - { - Nz::Signal signal; - - WHEN("We connection different callbacks") - { - auto connection = signal.Connect(increment); - signal.Connect([](int* inc){ *inc += 1; }); - Incrementer incrementer; - signal.Connect(incrementer, &Incrementer::increment); - - THEN("The call of signal with inc = 0 must return 3") - { - int inc = 0; - signal(&inc); - REQUIRE(inc == 3); - } - - AND_THEN("When we disconnect one function, there should be only two listeners") - { - connection.Disconnect(); - REQUIRE(!connection.IsConnected()); - - int inc = 0; - signal(&inc); - REQUIRE(inc == 2); - } - } - } -} diff --git a/tests/Engine/Core/SparsePtrTest.cpp b/tests/Engine/Core/SparsePtrTest.cpp deleted file mode 100644 index d3c832a71..000000000 --- a/tests/Engine/Core/SparsePtrTest.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include - -#include - -SCENARIO("SparsePtr", "[CORE][SPARSEPTR]") -{ - GIVEN("A sparse pointer pointing to an array with a stride of 2") - { - std::array arrays = { {0, 1, 2, 3, 4} }; - Nz::SparsePtr sparsePtr(arrays.data(), 2 * sizeof(int)); - - WHEN("We use operators") - { - THEN("Operator[] with 2 should be 4") - { - CHECK(4 == sparsePtr[2]); - } - - THEN("Operator++ and Operator-- should be opposite") - { - ++sparsePtr; - CHECK(2 == *sparsePtr); - auto old = sparsePtr++; - CHECK(2 == *old); - CHECK(4 == *sparsePtr); - - --sparsePtr; - CHECK(2 == *sparsePtr); - auto oldMinus = sparsePtr--; - CHECK(2 == *oldMinus); - CHECK(0 == *sparsePtr); - } - - THEN("Operator+ and operator-") - { - auto offsetTwo = sparsePtr + 2; - CHECK(4 == *offsetTwo); - - auto offsetZero = offsetTwo - 2; - CHECK(0 == *offsetZero); - - CHECK((offsetTwo - offsetZero) == 2); - } - } - } -} diff --git a/tests/Engine/Core/StackVectorTest.cpp b/tests/Engine/Core/StackVectorTest.cpp deleted file mode 100644 index e6d7afede..000000000 --- a/tests/Engine/Core/StackVectorTest.cpp +++ /dev/null @@ -1,350 +0,0 @@ -#include -#include -#include -#include -#include - -// This is a quick way to check that checks are valid -#define USE_STD_VECTOR 0 - -class DestructionCounter -{ - public: - DestructionCounter() : - m_counter(nullptr), - m_value(0) - { - } - - DestructionCounter(std::size_t* counter, int value) : - m_counter(counter), - m_value(value) - { - if (m_counter) - (*m_counter)++; - } - - DestructionCounter(const DestructionCounter& counter) : - m_counter(counter.m_counter), - m_value(counter.m_value) - { - if (m_counter) - (*m_counter)++; - } - - DestructionCounter(DestructionCounter&& counter) : - m_counter(counter.m_counter), - m_value(counter.m_value) - { - if (m_counter) - (*m_counter)++; - } - - ~DestructionCounter() - { - if (m_counter) - { - assert(*m_counter > 0); - (*m_counter)--; - } - } - - operator int() const - { - return m_value; - } - - DestructionCounter& operator=(const DestructionCounter& counter) - { - if (m_counter) - { - assert(*m_counter > 0); - (*m_counter)--; - } - - m_counter = counter.m_counter; - m_value = counter.m_value; - - if (m_counter) - (*m_counter)++; - - return *this; - } - - DestructionCounter& operator=(DestructionCounter&& counter) - { - if (this == &counter) - return *this; - - if (m_counter) - { - assert(*m_counter > 0); - (*m_counter)--; - } - - m_counter = counter.m_counter; - m_value = counter.m_value; - - if (m_counter) - (*m_counter)++; - - return *this; - } - - private: - std::size_t* m_counter; - int m_value; -}; - -SCENARIO("StackVector", "[CORE][STACKVECTOR]") -{ - GIVEN("A StackVector to contain multiple int") - { - std::size_t counter = 0; - { - volatile std::size_t capacity = 50; -#if USE_STD_VECTOR - std::vector vector; - vector.reserve(capacity); -#else - Nz::StackVector vector = NazaraStackVector(DestructionCounter, capacity); -#endif - - WHEN("At construction, the vector is empty but has capacity") - { - CHECK(vector.capacity() == capacity); - CHECK(vector.empty()); - CHECK(vector.size() == 0); -#if !USE_STD_VECTOR - CHECK(vector.max_size() == capacity); -#endif - } - - WHEN("Resizing it changes its size and create/destroy elements") - { - vector.resize(vector.capacity()); - CHECK(vector.size() == vector.capacity()); - CHECK(counter == 0); - vector.resize(0); - CHECK(vector.empty()); - CHECK(vector.size() == 0); - CHECK(counter == 0); - } - - WHEN("Resizing it allocates elements") - { - vector.resize(vector.capacity(), DestructionCounter(&counter, 0)); - CHECK(vector.size() == vector.capacity()); - CHECK(counter == capacity); - vector.resize(0); - CHECK(vector.empty()); - CHECK(vector.size() == 0); - CHECK(counter == 0); - } - - WHEN("Emplacing five elements, vector size increase accordingly") - { - for (std::size_t i = 0; i < 5; ++i) - { -#if USE_STD_VECTOR - vector.emplace_back(&counter, int(i)); -#else - CHECK(vector.emplace_back(&counter, int(i)) == int(i)); -#endif - } - - CHECK(!vector.empty()); - CHECK(vector.size() == 5); - - std::array expectedValues = { 0, 1, 2, 3, 4 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - WHEN("Pushing three elements, vector size increase accordingly") - { - for (std::size_t i = 0; i < 3; ++i) - { - DestructionCounter val(&counter, int(i)); -#if USE_STD_VECTOR - vector.push_back(val); -#else - CHECK(vector.push_back(val) == val); -#endif - } - - CHECK(!vector.empty()); - CHECK(vector.size() == 3); - { - std::array expectedValues = { 0, 1, 2 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - THEN("We resize to five") - { - vector.resize(5); - - CHECK(!vector.empty()); - CHECK(vector.size() == 5); - - std::array expectedValues = { 0, 1, 2, 0, 0 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - - AND_THEN("We resize it back to zero") - { - vector.resize(0); - - CHECK(vector.empty()); - CHECK(vector.size() == 0); - } - AND_THEN("We clear it") - { - vector.clear(); - - CHECK(vector.empty()); - CHECK(vector.size() == 0); - CHECK(counter == 0); - } - } - } - - WHEN("We generate its content will iota") - { - vector.resize(10); - for (std::size_t i = 0; i < vector.size(); ++i) - vector[i] = DestructionCounter(&counter, -5 + int(i)); - - { - std::array expectedValues = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4 }; - CHECK(vector.size() == expectedValues.size()); - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - AND_WHEN("We pop back some elements") - { - for (std::size_t i = 0; i < 5; ++i) - vector.pop_back(); - - std::array expectedValues = { -5, -4, -3, -2, -1 }; - CHECK(vector.size() == expectedValues.size()); - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - AND_WHEN("We erase elements at the beginning") - { - vector.erase(vector.begin()); - vector.erase(vector.begin()); - - std::array expectedValues = { -3, -2, -1, 0, 1, 2, 3, 4 }; - CHECK(vector.size() == expectedValues.size()); - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - AND_WHEN("We erase elements in the middle") - { - vector.erase(vector.begin() + 2); - vector.erase(vector.begin() + 2); - vector.erase(vector.begin() + 6); - - std::array expectedValues = { -5, -4, -1, 0, 1, 2, 4 }; - CHECK(vector.size() == expectedValues.size()); - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - AND_WHEN("We erase elements at the end") - { - vector.erase(vector.end() - 1); - vector.erase(vector.end() - 1); - - std::array expectedValues = { -5, -4, -3, -2, -1, 0, 1, 2 }; - CHECK(vector.size() == expectedValues.size()); - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - AND_WHEN("We erase a range") - { - vector.erase(vector.begin() + 2, vector.end() - 3); - - std::array expectedValues = { -5, -4, 2, 3, 4 }; - CHECK(vector.size() == expectedValues.size()); - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - AND_WHEN("We erase everything") - { - vector.erase(vector.begin(), vector.end()); - - CHECK(vector.empty()); - } - } - - WHEN("We generate its content using emplace") - { - for (std::size_t i = 0; i < 5; ++i) - CHECK(*vector.emplace(vector.end(), &counter, int(i)) == int(i)); - - CHECK(!vector.empty()); - CHECK(vector.size() == 5); - - std::array expectedValues = { 0, 1, 2, 3, 4 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - WHEN("We generate its content using emplace, in reverse order") - { - for (std::size_t i = 0; i < 5; ++i) - CHECK(*vector.emplace(vector.begin(), &counter, int(i)) == int(i)); - - CHECK(!vector.empty()); - CHECK(vector.size() == 5); - - std::array expectedValues = { 4, 3, 2, 1, 0 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - WHEN("We generate its content using emplace, at the middle") - { - for (std::size_t i = 0; i < 10; ++i) - CHECK(*vector.emplace(vector.begin() + i / 2, &counter, int(i)) == int(i)); - - CHECK(!vector.empty()); - CHECK(vector.size() == 10); - - std::array expectedValues = { 1, 3, 5, 7, 9, 8, 6, 4, 2, 0 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - WHEN("We generate its content using insert") - { - for (std::size_t i = 0; i < 5; ++i) - CHECK(*vector.insert(vector.end(), DestructionCounter(&counter, int(i))) == int(i)); - - CHECK(!vector.empty()); - CHECK(vector.size() == 5); - - std::array expectedValues = { 0, 1, 2, 3, 4 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - WHEN("We generate its content using insert, in reverse order") - { - for (std::size_t i = 0; i < 5; ++i) - CHECK(*vector.insert(vector.begin(), DestructionCounter(&counter, int(i))) == int(i)); - - CHECK(!vector.empty()); - CHECK(vector.size() == 5); - - std::array expectedValues = { 4, 3, 2, 1, 0 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - - WHEN("We generate its content using insert, at the middle") - { - for (std::size_t i = 0; i < 10; ++i) - CHECK(*vector.insert(vector.begin() + i / 2, DestructionCounter(&counter, int(i))) == int(i)); - - CHECK(!vector.empty()); - CHECK(vector.size() == 10); - - std::array expectedValues = { 1, 3, 5, 7, 9, 8, 6, 4, 2, 0 }; - CHECK(std::equal(vector.begin(), vector.end(), expectedValues.begin(), expectedValues.end())); - } - } - - CHECK(counter == 0); - } -} diff --git a/tests/Engine/Modules.hpp b/tests/Engine/Modules.hpp index 956adacba..7fce6d5db 100644 --- a/tests/Engine/Modules.hpp +++ b/tests/Engine/Modules.hpp @@ -4,5 +4,4 @@ #include #include #include -#include #include diff --git a/tests/Engine/Shader/AccessMemberTests.cpp b/tests/Engine/Shader/AccessMemberTests.cpp deleted file mode 100644 index 1ea8de661..000000000 --- a/tests/Engine/Shader/AccessMemberTests.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("structure member access", "[Shader]") -{ - SECTION("Nested member loading") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct innerStruct -{ - field: vec3[f32] -} - -struct outerStruct -{ - s: innerStruct -} - -external -{ - [set(0), binding(0)] ubo: uniform[outerStruct] -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - SECTION("Nested AccessMember") - { - auto ubo = Nz::ShaderBuilder::Identifier("ubo"); - auto firstAccess = Nz::ShaderBuilder::AccessMember(std::move(ubo), { "s" }); - auto secondAccess = Nz::ShaderBuilder::AccessMember(std::move(firstAccess), { "field" }); - - auto swizzle = Nz::ShaderBuilder::Swizzle(std::move(secondAccess), { 2u }); - auto varDecl = Nz::ShaderBuilder::DeclareVariable("result", Nz::ShaderAst::ExpressionType{ Nz::ShaderAst::PrimitiveType::Float32 }, std::move(swizzle)); - - shaderModule->rootNode->statements.push_back(Nz::ShaderBuilder::DeclareFunction(Nz::ShaderStageType::Vertex, "main", std::move(varDecl))); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float result = ubo.s.field.z; -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(vert)] -fn main() -{ - let result: f32 = ubo.s.field.z; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpAccessChain -OpLoad -OpCompositeExtract -OpStore -OpReturn -OpFunctionEnd)"); - } - - SECTION("AccessMember with multiples fields") - { - auto ubo = Nz::ShaderBuilder::Identifier("ubo"); - auto access = Nz::ShaderBuilder::AccessMember(std::move(ubo), { "s", "field" }); - - auto swizzle = Nz::ShaderBuilder::Swizzle(std::move(access), { 2u }); - auto varDecl = Nz::ShaderBuilder::DeclareVariable("result", Nz::ShaderAst::ExpressionType{ Nz::ShaderAst::PrimitiveType::Float32 }, std::move(swizzle)); - - shaderModule->rootNode->statements.push_back(Nz::ShaderBuilder::DeclareFunction(Nz::ShaderStageType::Vertex, "main", std::move(varDecl))); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float result = ubo.s.field.z; -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(vert)] -fn main() -{ - let result: f32 = ubo.s.field.z; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpAccessChain -OpLoad -OpCompositeExtract -OpStore -OpReturn -OpFunctionEnd)"); - } - } -} diff --git a/tests/Engine/Shader/AliasTests.cpp b/tests/Engine/Shader/AliasTests.cpp deleted file mode 100644 index d55ea0142..000000000 --- a/tests/Engine/Shader/AliasTests.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("aliases", "[Shader]") -{ - SECTION("Alias of structs") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct Data -{ - value: f32 -} - -alias ExtData = Data; - -external -{ - [binding(0)] extData: uniform[ExtData] -} - -struct Input -{ - value: f32 -} - -alias In = Input; - -struct Output -{ - [location(0)] value: f32 -} - -alias Out = Output; -alias FragOut = Out; - -[entry(frag)] -fn main(input: In) -> FragOut -{ - let output: Out; - output.value = extData.value * input.value; - return output; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - Input input_; - input_.value = _NzIn_value; - - Output output_; - output_.value = extData.value * input_.value; - - _NzOut_value = output_.value; - return; -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main(input: In) -> FragOut -{ - let output: Out; - output.value = extData.value * input.value; - return output; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpAccessChain -OpLoad -OpAccessChain -OpLoad -OpFMul -OpAccessChain -OpStore -OpLoad -OpCompositeExtract -OpStore -OpReturn -OpFunctionEnd)"); - } -} diff --git a/tests/Engine/Shader/BranchTests.cpp b/tests/Engine/Shader/BranchTests.cpp deleted file mode 100644 index e677d6d27..000000000 --- a/tests/Engine/Shader/BranchTests.cpp +++ /dev/null @@ -1,377 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("branching", "[Shader]") -{ - WHEN("using a simple branch") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > 0.0) - value = 1.0; - else - value = 0.0; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float value; - if (data.value > (0.000000)) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > (0.000000)) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpAccessChain -OpLoad -OpFOrdGreaterThanEqual -OpSelectionMerge -OpBranchConditional -OpLabel -OpStore -OpBranch -OpLabel -OpStore -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } - - WHEN("using a more complex branch") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > 42.0 || data.value <= 50.0 && data.value < 0.0) - value = 1.0; - else - value = 0.0; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float value; - if ((data.value > (42.000000)) || ((data.value <= (50.000000)) && (data.value < (0.000000)))) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let value: f32; - if ((data.value > (42.000000)) || ((data.value <= (50.000000)) && (data.value < (0.000000)))) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpAccessChain -OpLoad -OpFOrdGreaterThanEqual -OpAccessChain -OpLoad -OpFOrdLessThanEqual -OpAccessChain -OpLoad -OpFOrdLessThan -OpLogicalAnd -OpLogicalOr -OpSelectionMerge -OpBranchConditional -OpLabel -OpStore -OpBranch -OpLabel -OpStore -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } - - WHEN("discarding in a branch") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - if (data.value > 0.0) - discard; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - if (data.value > (0.000000)) - { - discard; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - if (data.value > (0.000000)) - { - discard; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpAccessChain -OpLoad -OpFOrdGreaterThanEqual -OpSelectionMerge -OpBranchConditional -OpLabel -OpKill -OpLabel -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } - - - WHEN("using a complex branch") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > 3.0) - value = 3.0; - else if (data.value > 2.0) - value = 2.0; - else if (data.value > 1.0) - value = 1.0; - else - value = 0.0; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float value; - if (data.value > (3.000000)) - { - value = 3.000000; - } - else if (data.value > (2.000000)) - { - value = 2.000000; - } - else if (data.value > (1.000000)) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > (3.000000)) - { - value = 3.000000; - } - else if (data.value > (2.000000)) - { - value = 2.000000; - } - else if (data.value > (1.000000)) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpAccessChain -OpLoad -OpFOrdGreaterThanEqual -OpSelectionMerge -OpBranchConditional -OpLabel -OpStore -OpBranch -OpLabel -OpAccessChain -OpLoad -OpFOrdGreaterThanEqual -OpSelectionMerge -OpBranchConditional -OpLabel -OpStore -OpBranch -OpLabel -OpAccessChain -OpLoad -OpFOrdGreaterThanEqual -OpSelectionMerge -OpBranchConditional -OpLabel -OpStore -OpBranch -OpLabel -OpStore -OpBranch -OpLabel -OpBranch -OpLabel -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } -} diff --git a/tests/Engine/Shader/ConstTests.cpp b/tests/Engine/Shader/ConstTests.cpp deleted file mode 100644 index d70833f1a..000000000 --- a/tests/Engine/Shader/ConstTests.cpp +++ /dev/null @@ -1,255 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void ExpectOutput(Nz::ShaderAst::Module& shaderModule, const Nz::ShaderAst::SanitizeVisitor::Options& options, std::string_view expectedOptimizedResult) -{ - Nz::ShaderAst::ModulePtr sanitizedShader; - sanitizedShader = SanitizeModule(shaderModule, options); - - ExpectNZSL(*sanitizedShader, expectedOptimizedResult); -} - -TEST_CASE("const", "[Shader]") -{ - WHEN("using const if") - { - std::string_view sourceCode = R"( -[nzsl_version("1.0")] -module; - -option UseInt: bool = false; - -[cond(UseInt)] -struct inputStruct -{ - value: i32 -} - -[cond(!UseInt)] -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - - const if (UseInt) - { - value = f32(data.value); - } - else - { - value = data.value; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule; - REQUIRE_NOTHROW(shaderModule = Nz::ShaderLang::Parse(sourceCode)); - - Nz::ShaderAst::SanitizeVisitor::Options options; - - WHEN("Enabling option") - { - options.optionValues[Nz::CRC32("UseInt")] = true; - - ExpectOutput(*shaderModule, options, R"( -struct inputStruct -{ - value: i32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - value = f32(data.value); -} -)"); - } - - WHEN("Disabling option") - { - options.optionValues[Nz::CRC32("UseInt")] = false; - - ExpectOutput(*shaderModule, options, R"( -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - value = data.value; -} -)"); - } - } - - WHEN("using [unroll] attribute on numerical for") - { - std::string_view sourceCode = R"( -[nzsl_version("1.0")] -module; - -const LightCount = 3; - -[layout(std140)] -struct Light -{ - color: vec4[f32] -} - -[layout(std140)] -struct LightData -{ - lights: array[Light, LightCount] -} - -external -{ - [set(0), binding(0)] data: uniform[LightData] -} - -[entry(frag)] -fn main() -{ - let color = (0.0).xxxx; - - [unroll] - for i in 0 -> 10 : 2 - { - color += data.lights[i].color; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule; - REQUIRE_NOTHROW(shaderModule = Nz::ShaderLang::Parse(sourceCode)); - - ExpectOutput(*shaderModule, {}, R"( -[entry(frag)] -fn main() -{ - let color: vec4[f32] = (0.000000).xxxx; - { - let i: i32 = 0; - color += data.lights[i].color; - } - - { - let i: i32 = 2; - color += data.lights[i].color; - } - - { - let i: i32 = 4; - color += data.lights[i].color; - } - - { - let i: i32 = 6; - color += data.lights[i].color; - } - - { - let i: i32 = 8; - color += data.lights[i].color; - } - -} -)"); - } - - WHEN("using [unroll] attribute on for-each") - { - std::string_view sourceCode = R"( -[nzsl_version("1.0")] -module; - -const LightCount = 3; - -[layout(std140)] -struct Light -{ - color: vec4[f32] -} - -[layout(std140)] -struct LightData -{ - lights: array[Light, LightCount] -} - -external -{ - [set(0), binding(0)] data: uniform[LightData] -} - -[entry(frag)] -fn main() -{ - let color = (0.0).xxxx; - - [unroll] - for light in data.lights - { - color += light.color; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule; - REQUIRE_NOTHROW(shaderModule = Nz::ShaderLang::Parse(sourceCode)); - - ExpectOutput(*shaderModule, {}, R"( -[entry(frag)] -fn main() -{ - let color: vec4[f32] = (0.000000).xxxx; - { - let light: Light = data.lights[0]; - color += light.color; - } - - { - let light: Light = data.lights[1]; - color += light.color; - } - - { - let light: Light = data.lights[2]; - color += light.color; - } - -} -)"); - } -} diff --git a/tests/Engine/Shader/ErrorsTest.cpp b/tests/Engine/Shader/ErrorsTest.cpp deleted file mode 100644 index 6e184ae3f..000000000 --- a/tests/Engine/Shader/ErrorsTest.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include -#include -#include - -TEST_CASE("errors", "[Shader]") -{ - SECTION("Checking lexer errors") - { - CHECK_THROWS_WITH(Nz::ShaderLang::Tokenize("1x42"), "(1,1 -> 4): LBadNumber error: bad number"); - CHECK_THROWS_WITH(Nz::ShaderLang::Tokenize("123456789876543210123456789"), "(1,1 -> 27): LNumberOutOfRange error: number is out of range"); - CHECK_THROWS_WITH(Nz::ShaderLang::Tokenize("\"Hello world"), "(1,1 -> 13): LUnfinishedString error: unfinished string"); - CHECK_THROWS_WITH(Nz::ShaderLang::Tokenize(R"("hello \p")"), "(1,1 -> 9): LUnrecognizedChar error: unrecognized character"); - CHECK_THROWS_WITH(Nz::ShaderLang::Tokenize("$"), "(1, 1): LUnrecognizedToken error: unrecognized token"); - } - - SECTION("Checking parser errors") - { - CHECK_THROWS_WITH(Nz::ShaderLang::Parse("nazara"), "(1,1 -> 6): PUnexpectedToken error: unexpected token Identifier"); - CHECK_THROWS_WITH(Nz::ShaderLang::Parse("module;"), "(1,1 -> 6): PMissingAttribute error: missing attribute nzsl_version"); - CHECK_THROWS_WITH(Nz::ShaderLang::Parse("[nzsl_version] module;"), "(1,2 -> 13): PAttributeMissingParameter error: attribute nzsl_version requires a parameter"); - CHECK_THROWS_WITH(Nz::ShaderLang::Parse("[nzsl_version(\"1.0\"), nzsl_version(\"1.0\")] module;"), "(1,23 -> 41): PAttributeMultipleUnique error: attribute nzsl_version can only be present once"); - CHECK_THROWS_WITH(Nz::ShaderLang::Parse("[nzsl_version(\"1.0\"), uuid(\"Nazara\")] module;"), "(1,23 -> 36): PInvalidUuid error: \"Nazara\" is not a valid UUID"); - } -} diff --git a/tests/Engine/Shader/FunctionsTests.cpp b/tests/Engine/Shader/FunctionsTests.cpp deleted file mode 100644 index 5da086c3e..000000000 --- a/tests/Engine/Shader/FunctionsTests.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("functions", "[Shader]") -{ - SECTION("Simple function call") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct FragOut -{ - [location(0)] value: f32 -} - -fn GetValue() -> f32 -{ - return 42.0; -} - -[entry(frag)] -fn main() -> FragOut -{ - let output: FragOut; - output.value = -GetValue(); - - return output; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -float GetValue() -{ - return 42.000000; -} - -/*************** Outputs ***************/ -layout(location = 0) out float _NzOut_value; - -void main() -{ - FragOut output_; - output_.value = -GetValue(); - - _NzOut_value = output_.value; - return; -} -)"); - - ExpectNZSL(*shaderModule, R"( -fn GetValue() -> f32 -{ - return 42.000000; -} - -[entry(frag)] -fn main() -> FragOut -{ - let output: FragOut; - output.value = -GetValue(); - return output; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpReturnValue -OpFunctionEnd -OpFunction -OpLabel -OpVariable -OpFunctionCall -OpFNegate -OpAccessChain -OpStore -OpLoad -OpCompositeExtract -OpStore -OpReturn -OpFunctionEnd)"); - } -} diff --git a/tests/Engine/Shader/IntrinsicTests.cpp b/tests/Engine/Shader/IntrinsicTests.cpp deleted file mode 100644 index 2052b1d3b..000000000 --- a/tests/Engine/Shader/IntrinsicTests.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("intrinsics", "[Shader]") -{ - WHEN("using intrinsics") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -external -{ - [set(0), binding(0)] tex: sampler2D[f32] -} - -[entry(frag)] -fn main() -{ - let f1 = 42.0; - let f2 = 1337.0; - let i1 = 42; - let i2 = 1337; - let uv = vec2[f32](0.0, 1.0); - let v1 = vec3[f32](0.0, 1.0, 2.0); - let v2 = vec3[f32](2.0, 1.0, 0.0); - - let crossResult = cross(v1, v2); - let dotResult = dot(v1, v2); - let expResult1 = exp(v1); - let expResult2 = exp(f1); - let lengthResult = length(v1); - let maxResult1 = max(f1, f2); - let maxResult2 = max(i1, i2); - let maxResult3 = max(v1, v2); - let minResult1 = min(f1, f2); - let minResult2 = min(i1, i2); - let minResult3 = min(v1, v2); - let normalizeResult = normalize(v1); - let powResult1 = pow(f1, f2); - let powResult2 = pow(v1, v2); - let reflectResult = reflect(v1, v2); - let sampleResult = tex.Sample(uv); -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float f1 = 42.000000; - float f2 = 1337.000000; - int i1 = 42; - int i2 = 1337; - vec2 uv = vec2(0.000000, 1.000000); - vec3 v1 = vec3(0.000000, 1.000000, 2.000000); - vec3 v2 = vec3(2.000000, 1.000000, 0.000000); - vec3 crossResult = cross(v1, v2); - float dotResult = dot(v1, v2); - vec3 expResult1 = exp(v1); - float expResult2 = exp(f1); - float lengthResult = length(v1); - float maxResult1 = max(f1, f2); - int maxResult2 = max(i1, i2); - vec3 maxResult3 = max(v1, v2); - float minResult1 = min(f1, f2); - int minResult2 = min(i1, i2); - vec3 minResult3 = min(v1, v2); - vec3 normalizeResult = normalize(v1); - float powResult1 = pow(f1, f2); - vec3 powResult2 = pow(v1, v2); - vec3 reflectResult = reflect(v1, v2); - vec4 sampleResult = texture(tex, uv); -} -)"); - - ExpectNZSL(*shaderModule, R"( -fn main() -{ - let f1: f32 = 42.000000; - let f2: f32 = 1337.000000; - let i1: i32 = 42; - let i2: i32 = 1337; - let uv: vec2[f32] = vec2[f32](0.000000, 1.000000); - let v1: vec3[f32] = vec3[f32](0.000000, 1.000000, 2.000000); - let v2: vec3[f32] = vec3[f32](2.000000, 1.000000, 0.000000); - let crossResult: vec3[f32] = cross(v1, v2); - let dotResult: f32 = dot(v1, v2); - let expResult1: vec3[f32] = exp(v1); - let expResult2: f32 = exp(f1); - let lengthResult: f32 = length(v1); - let maxResult1: f32 = max(f1, f2); - let maxResult2: i32 = max(i1, i2); - let maxResult3: vec3[f32] = max(v1, v2); - let minResult1: f32 = min(f1, f2); - let minResult2: i32 = min(i1, i2); - let minResult3: vec3[f32] = min(v1, v2); - let normalizeResult: vec3[f32] = normalize(v1); - let powResult1: f32 = pow(f1, f2); - let powResult2: vec3[f32] = pow(v1, v2); - let reflectResult: vec3[f32] = reflect(v1, v2); - let sampleResult: vec4[f32] = tex.Sample(uv); -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpVariable -OpStore -OpStore -OpStore -OpStore -OpCompositeConstruct -OpStore -OpCompositeConstruct -OpStore -OpCompositeConstruct -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpDot -OpStore -OpLoad -OpExtInst -OpStore -OpLoad -OpExtInst -OpStore -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpExtInst -OpStore -OpLoad -OpLoad -OpImageSampleImplicitLod -OpStore -OpReturn -OpFunctionEnd)"); - } - -} diff --git a/tests/Engine/Shader/LexerTests.cpp b/tests/Engine/Shader/LexerTests.cpp deleted file mode 100644 index 4c0909991..000000000 --- a/tests/Engine/Shader/LexerTests.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("lexer", "[Shader]") -{ - SECTION("Simple code") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let vec = vec4[f32](0.0, 1.0, 2.0, 3.0); - let i = 42; - let value = vec.xyz; -} -)"; - - std::vector tokens = Nz::ShaderLang::Tokenize(nzslSource); - CHECK(Nz::ShaderLang::ToString(tokens) == R"(OpenSquareBracket Identifier(nzsl_version) OpenParenthesis StringValue("1.0") ClosingParenthesis ClosingSquareBracket -Module Semicolon -OpenSquareBracket Identifier(entry) OpenParenthesis Identifier(frag) ClosingParenthesis ClosingSquareBracket -FunctionDeclaration Identifier(main) OpenParenthesis ClosingParenthesis -OpenCurlyBracket -Let Identifier(vec) Assign Identifier(vec4) OpenSquareBracket Identifier(f32) ClosingSquareBracket OpenParenthesis FloatingPointValue(0) Comma FloatingPointValue(1) Comma FloatingPointValue(2) Comma FloatingPointValue(3) ClosingParenthesis Semicolon -Let Identifier(i) Assign IntegerValue(42) Semicolon -Let Identifier(value) Assign Identifier(vec) Dot Identifier(xyz) Semicolon -ClosingCurlyBracket -EndOfStream)"); - } -} diff --git a/tests/Engine/Shader/LoopTests.cpp b/tests/Engine/Shader/LoopTests.cpp deleted file mode 100644 index 2e02259cb..000000000 --- a/tests/Engine/Shader/LoopTests.cpp +++ /dev/null @@ -1,347 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("loops", "[Shader]") -{ - WHEN("using a while") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value = 0.0; - let i = 0; - while (i < 10) - { - value += 0.1; - i += 1; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float value = 0.000000; - int i = 0; - while (i < (10)) - { - value += 0.100000; - i += 1; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let value: f32 = 0.000000; - let i: i32 = 0; - while (i < (10)) - { - value += 0.100000; - i += 1; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpStore -OpStore -OpBranch -OpLabel -OpLoad -OpSLessThan -OpLoopMerge -OpBranchConditional -OpLabel -OpLoad -OpFAdd -OpStore -OpLoad -OpIAdd -OpStore -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } - - WHEN("using a for range") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let x = 0; - for v in 0 -> 10 - { - x += v; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - int x = 0; - int v = 0; - int to = 10; - while (v < to) - { - x += v; - v += 1; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let x: i32 = 0; - for v in 0 -> 10 - { - x += v; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpVariable -OpStore -OpStore -OpStore -OpBranch -OpLabel -OpLoad -OpLoad -OpSLessThan -OpLoopMerge -OpBranchConditional -OpLabel -OpLoad -OpLoad -OpIAdd -OpStore -OpLoad -OpIAdd -OpStore -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } - - WHEN("using a for range with step") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let x = 0; - for v in 0 -> 10 : 2 - { - x += v; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - int x = 0; - int v = 0; - int to = 10; - int step = 2; - while (v < to) - { - x += v; - v += step; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let x: i32 = 0; - for v in 0 -> 10 : 2 - { - x += v; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpVariable -OpVariable -OpStore -OpStore -OpStore -OpStore -OpBranch -OpLabel -OpLoad -OpLoad -OpSLessThan -OpLoopMerge -OpBranchConditional -OpLabel -OpLoad -OpLoad -OpIAdd -OpStore -OpLoad -OpLoad -OpIAdd -OpStore -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } - - WHEN("using a for-each") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: array[f32, 10] -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let x = 0.0; - for v in data.value - { - x += v; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float x = 0.000000; - uint i = 0u; - while (i < (10u)) - { - float v = data.value[i]; - x += v; - i += 1u; - } - -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let x: f32 = 0.000000; - for v in data.value - { - x += v; - } - -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpVariable -OpStore -OpStore -OpBranch -OpLabel -OpLoad -OpULessThan -OpLoopMerge -OpBranchConditional -OpLabel -OpLoad -OpAccessChain -OpLoad -OpStore -OpLoad -OpLoad -OpFAdd -OpStore -OpLoad -OpIAdd -OpStore -OpBranch -OpLabel -OpReturn -OpFunctionEnd)"); - } -} diff --git a/tests/Engine/Shader/ModuleTests.cpp b/tests/Engine/Shader/ModuleTests.cpp deleted file mode 100644 index 4785165d0..000000000 --- a/tests/Engine/Shader/ModuleTests.cpp +++ /dev/null @@ -1,449 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("Modules", "[Shader]") -{ - WHEN("using a simple module") - { - // UUID are required here to have a stable output - std::string_view importedSource = R"( -[nzsl_version("1.0")] -[uuid("ad3aed6e-0619-4a26-b5ce-abc2ec0836c4")] -module SimpleModule; - -[layout(std140)] -struct Data -{ - value: f32 -} - -[export] -[layout(std140)] -struct Block -{ - data: Data -} - -[export] -fn GetDataValue(data: Data) -> f32 -{ - return data.value; -} - -struct Unused {} - -[export] -struct InputData -{ - value: f32 -} - -[export] -struct OutputData -{ - value: f32 -} -)"; - - std::string_view shaderSource = R"( -[nzsl_version("1.0")] -module; - -import SimpleModule; - -external -{ - [binding(0)] block: uniform[Block] -} - -[entry(frag)] -fn main(input: InputData) -> OutputData -{ - let output: OutputData; - output.value = GetDataValue(block.data) * input.value; - return output; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(shaderSource); - - auto directoryModuleResolver = std::make_shared(); - directoryModuleResolver->RegisterModule(importedSource); - - Nz::ShaderAst::SanitizeVisitor::Options sanitizeOpt; - sanitizeOpt.moduleResolver = directoryModuleResolver; - - shaderModule = SanitizeModule(*shaderModule, sanitizeOpt); - - ExpectGLSL(*shaderModule, R"( -// Module SimpleModule - -struct Data_181c45e9 -{ - float value; -}; - -struct Block_181c45e9 -{ - Data_181c45e9 data; -}; - -float GetDataValue_181c45e9(Data_181c45e9 data) -{ - return data.value; -} - -struct InputData_181c45e9 -{ - float value; -}; - -struct OutputData_181c45e9 -{ - float value; -}; - -// Main file - - -layout(std140) uniform _NzBinding_block -{ - Data_181c45e9 data; -} block; - - -/**************** Inputs ****************/ -in float _NzIn_value; - -/*************** Outputs ***************/ -out float _NzOut_value; - -void main() -{ - InputData_181c45e9 input_; - input_.value = _NzIn_value; - - OutputData_181c45e9 output_; - output_.value = (GetDataValue_181c45e9(block.data)) * input_.value; - - _NzOut_value = output_.value; - return; -} -)"); - - ExpectNZSL(*shaderModule, R"( -[nzsl_version("1.0")] -module; - -[nzsl_version("1.0")] -[uuid("ad3aed6e-0619-4a26-b5ce-abc2ec0836c4")] -module _181c45e9 -{ - [layout(std140)] - struct Data - { - value: f32 - } - - [layout(std140)] - struct Block - { - data: Data - } - - fn GetDataValue(data: Data) -> f32 - { - return data.value; - } - - struct InputData - { - value: f32 - } - - struct OutputData - { - value: f32 - } - -} -alias Block = _181c45e9.Block; - -alias GetDataValue = _181c45e9.GetDataValue; - -alias InputData = _181c45e9.InputData; - -alias OutputData = _181c45e9.OutputData; - -external -{ - [set(0), binding(0)] block: uniform[_181c45e9.Block] -} - -[entry(frag)] -fn main(input: InputData) -> OutputData -{ - let output: OutputData; - output.value = (GetDataValue(block.data)) * input.value; - return output; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpFunctionParameter -OpLabel -OpAccessChain -OpLoad -OpReturnValue -OpFunctionEnd -OpFunction -OpLabel -OpVariable -OpVariable -OpVariable -OpAccessChain -OpLoad -OpStore -OpFunctionCall -OpAccessChain -OpLoad -OpFMul -OpAccessChain -OpStore -OpLoad -OpReturn -OpFunctionEnd)"); - } - - WHEN("Using nested modules") - { - // UUID are required here to have a stable output - std::string_view dataModule = R"( -[nzsl_version("1.0")] -[uuid("ad3aed6e-0619-4a26-b5ce-abc2ec0836c4")] -module Modules.Data; - -fn dummy() {} - -[export] -[layout(std140)] -struct Data -{ - value: f32 -} -)"; - - std::string_view blockModule = R"( -[nzsl_version("1.0")] -[uuid("7a548506-89e6-4944-897f-4f695a8bca01")] -module Modules.Block; - -import Modules.Data; - -[export] -[layout(std140)] -struct Block -{ - data: Data -} - -struct Unused {} -)"; - - std::string_view inputOutputModule = R"( -[nzsl_version("1.0")] -[uuid("e66c6e98-fc37-4390-a7e1-c81508ff8e49")] -module Modules.InputOutput; - -[export] -struct InputData -{ - value: f32 -} - -[export] -struct OutputData -{ - value: f32 -} -)"; - - std::string_view shaderSource = R"( -[nzsl_version("1.0")] -module; - -import Modules.Block; -import Modules.InputOutput; - -external -{ - [binding(0)] block: uniform[Block] -} - -[entry(frag)] -fn main(input: InputData) -> OutputData -{ - let output: OutputData; - output.value = block.data.value * input.value; - return output; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(shaderSource); - - auto directoryModuleResolver = std::make_shared(); - directoryModuleResolver->RegisterModule(dataModule); - directoryModuleResolver->RegisterModule(blockModule); - directoryModuleResolver->RegisterModule(inputOutputModule); - - Nz::ShaderAst::SanitizeVisitor::Options sanitizeOpt; - sanitizeOpt.moduleResolver = directoryModuleResolver; - - shaderModule = SanitizeModule(*shaderModule, sanitizeOpt); - - ExpectGLSL(*shaderModule, R"( -// Module Modules.Data - -struct Data_181c45e9 -{ - float value; -}; - -// Module Modules.Block - - -struct Block_e528265d -{ - Data_181c45e9 data; -}; - -// Module Modules.InputOutput - -struct InputData_26cce136 -{ - float value; -}; - -struct OutputData_26cce136 -{ - float value; -}; - -// Main file - - - -layout(std140) uniform _NzBinding_block -{ - Data_181c45e9 data; -} block; - - -/**************** Inputs ****************/ -in float _NzIn_value; - -/*************** Outputs ***************/ -out float _NzOut_value; - -void main() -{ - InputData_26cce136 input_; - input_.value = _NzIn_value; - - OutputData_26cce136 output_; - output_.value = block.data.value * input_.value; - - _NzOut_value = output_.value; - return; -} -)"); - - ExpectNZSL(*shaderModule, R"( -[nzsl_version("1.0")] -module; - -[nzsl_version("1.0")] -[uuid("ad3aed6e-0619-4a26-b5ce-abc2ec0836c4")] -module _181c45e9 -{ - [layout(std140)] - struct Data - { - value: f32 - } - -} -[nzsl_version("1.0")] -[uuid("7a548506-89e6-4944-897f-4f695a8bca01")] -module _e528265d -{ - alias Data = _181c45e9.Data; - - [layout(std140)] - struct Block - { - data: Data - } - -} -[nzsl_version("1.0")] -[uuid("e66c6e98-fc37-4390-a7e1-c81508ff8e49")] -module _26cce136 -{ - struct InputData - { - value: f32 - } - - struct OutputData - { - value: f32 - } - -} -alias Block = _e528265d.Block; - -alias InputData = _26cce136.InputData; - -alias OutputData = _26cce136.OutputData; - -external -{ - [set(0), binding(0)] block: uniform[_e528265d.Block] -} - -[entry(frag)] -fn main(input: InputData) -> OutputData -{ - let output: OutputData; - output.value = block.data.value * input.value; - return output; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpAccessChain -OpLoad -OpAccessChain -OpLoad -OpFMul -OpAccessChain -OpStore -OpLoad -OpReturn -OpFunctionEnd)"); - } -} diff --git a/tests/Engine/Shader/OptimizationTests.cpp b/tests/Engine/Shader/OptimizationTests.cpp deleted file mode 100644 index 061e31fd1..000000000 --- a/tests/Engine/Shader/OptimizationTests.cpp +++ /dev/null @@ -1,373 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void PropagateConstantAndExpect(std::string_view sourceCode, std::string_view expectedOptimizedResult) -{ - Nz::ShaderAst::ModulePtr shaderModule; - REQUIRE_NOTHROW(shaderModule = Nz::ShaderLang::Parse(sourceCode)); - shaderModule = SanitizeModule(*shaderModule); - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::PropagateConstants(*shaderModule)); - - ExpectNZSL(*shaderModule, expectedOptimizedResult); -} - -void EliminateUnusedAndExpect(std::string_view sourceCode, std::string_view expectedOptimizedResult) -{ - Nz::ShaderAst::DependencyCheckerVisitor::Config depConfig; - depConfig.usedShaderStages = Nz::ShaderStageType_All; - - Nz::ShaderAst::ModulePtr shaderModule; - REQUIRE_NOTHROW(shaderModule = Nz::ShaderLang::Parse(sourceCode)); - shaderModule = SanitizeModule(*shaderModule); - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::EliminateUnusedPass(*shaderModule, depConfig)); - - ExpectNZSL(*shaderModule, expectedOptimizedResult); -} - -TEST_CASE("optimizations", "[Shader]") -{ - WHEN("propagating constants") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let output = 8.0 * (7.0 + 5.0) * 2.0 / 4.0 - 6.0; -} -)", R"( -[entry(frag)] -fn main() -{ - let output: f32 = 42.000000; -} -)"); - } - - WHEN("propagating vector constants") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let output = vec4[f32](8.0, 2.0, -7.0, 0.0) * (7.0 + 5.0) * 2.0 / 4.0; -} -)", R"( -[entry(frag)] -fn main() -{ - let output: vec4[f32] = vec4[f32](48.000000, 12.000000, -42.000000, 0.000000); -)"); - } - - WHEN("eliminating simple branch") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - if (5 + 3 < 2) - discard; -} -)", R"( -[entry(frag)] -fn main() -{ - -} -)"); - } - - WHEN("eliminating multiple branches") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let output = 0.0; - if (5 <= 3) - output = 5.0; - else if (4 <= 3) - output = 4.0; - else if (3 <= 3) - output = 3.0; - else if (2 <= 3) - output = 2.0; - else if (1 <= 3) - output = 1.0; - else - output = 0.0; -} -)", R"( -[entry(frag)] -fn main() -{ - let output: f32 = 0.000000; - output = 3.000000; -} -)"); - } - - - WHEN("eliminating multiple split branches") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let output = 0.0; - if (5 <= 3) - output = 5.0; - else - { - if (4 <= 3) - output = 4.0; - else - { - if (3 <= 3) - output = 3.0; - else - { - if (2 <= 3) - output = 2.0; - else - { - if (1 <= 3) - output = 1.0; - else - output = 0.0; - } - } - } - } -} -)", R"( -[entry(frag)] -fn main() -{ - let output: f32 = 0.000000; - output = 3.000000; -} -)"); - } - - WHEN("optimizing out scalar swizzle") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let value = vec3[f32](3.0, 0.0, 1.0).z; -} -)", R"( -[entry(frag)] -fn main() -{ - let value: f32 = 1.000000; -} -)"); - } - - WHEN("optimizing out scalar swizzle to vector") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let value = (42.0).xxxx; -} -)", R"( -[entry(frag)] -fn main() -{ - let value: vec4[f32] = vec4[f32](42.000000, 42.000000, 42.000000, 42.000000); -} -)"); - } - - WHEN("optimizing out vector swizzle") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let value = vec4[f32](3.0, 0.0, 1.0, 2.0).yzwx; -} -)", R"( -[entry(frag)] -fn main() -{ - let value: vec4[f32] = vec4[f32](0.000000, 1.000000, 2.000000, 3.000000); -} -)"); - } - - WHEN("optimizing out vector swizzle with repetition") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let value = vec4[f32](3.0, 0.0, 1.0, 2.0).zzxx; -} -)", R"( -[entry(frag)] -fn main() -{ - let value: vec4[f32] = vec4[f32](1.000000, 1.000000, 3.000000, 3.000000); -} -)"); - } - - WHEN("optimizing out complex swizzle") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let value = vec4[f32](0.0, 1.0, 2.0, 3.0).xyz.yz.y.x.xxxx; -} -)", R"( -[entry(frag)] -fn main() -{ - let value: vec4[f32] = vec4[f32](2.000000, 2.000000, 2.000000, 2.000000); -} -)"); - } - - WHEN("optimizing out complex swizzle on unknown value") - { - PropagateConstantAndExpect(R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: vec4[f32] -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value = data.value.xyz.yz.y.x.xxxx; -} -)", R"( -[entry(frag)] -fn main() -{ - let value: vec4[f32] = data.value.zzzz; -} -)"); - } - - WHEN("eliminating unused code") - { - EliminateUnusedAndExpect(R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: vec4[f32] -} - -struct notUsed -{ - value: vec4[f32] -} - -external -{ - [set(0), binding(0)] unusedData: uniform[notUsed], - [set(0), binding(1)] data: uniform[inputStruct] -} - -fn unusedFunction() -> vec4[f32] -{ - return unusedData.value; -} - -struct Output -{ - value: vec4[f32] -} - -[entry(frag)] -fn main() -> Output -{ - let unusedvalue = unusedFunction(); - - let output: Output; - output.value = data.value; - return output; -})", R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: vec4[f32] -} - -external -{ - [set(0), binding(1)] data: uniform[inputStruct] -} - -struct Output -{ - value: vec4[f32] -} - -[entry(frag)] -fn main() -> Output -{ - let output: Output; - output.value = data.value; - return output; -})"); - } -} diff --git a/tests/Engine/Shader/SanitizationsTests.cpp b/tests/Engine/Shader/SanitizationsTests.cpp deleted file mode 100644 index 7745107c3..000000000 --- a/tests/Engine/Shader/SanitizationsTests.cpp +++ /dev/null @@ -1,309 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("sanitizing", "[Shader]") -{ - WHEN("splitting branches") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > 3.0) - value = 3.0; - else if (data.value > 2.0) - value = 2.0; - else if (data.value > 1.0) - value = 1.0; - else - value = 0.0; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - - Nz::ShaderAst::SanitizeVisitor::Options options; - options.splitMultipleBranches = true; - - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, options)); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > (3.000000)) - { - value = 3.000000; - } - else - { - if (data.value > (2.000000)) - { - value = 2.000000; - } - else - { - if (data.value > (1.000000)) - { - value = 1.000000; - } - else - { - value = 0.000000; - } - - } - - } - -} -)"); - - } - - WHEN("reducing for-each to while") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: array[f32, 10] -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let x = 0.0; - for v in data.value - { - x += v; - } -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - - Nz::ShaderAst::SanitizeVisitor::Options options; - options.reduceLoopsToWhile = true; - - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, options)); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let x: f32 = 0.000000; - let i: u32 = 0; - while (i < (10)) - { - let v: f32 = data.value[i]; - x += v; - i += 1; - } - -} -)"); - - } - - WHEN("removing matrix casts") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -fn testMat2ToMat2(input: mat2[f32]) -> mat2[f32] -{ - return mat2[f32](input); -} - -fn testMat2ToMat3(input: mat2[f32]) -> mat3[f32] -{ - return mat3[f32](input); -} - -fn testMat2ToMat4(input: mat2[f32]) -> mat4[f32] -{ - return mat4[f32](input); -} - -fn testMat3ToMat2(input: mat3[f32]) -> mat2[f32] -{ - return mat2[f32](input); -} - -fn testMat3ToMat3(input: mat3[f32]) -> mat3[f32] -{ - return mat3[f32](input); -} - -fn testMat3ToMat4(input: mat3[f32]) -> mat4[f32] -{ - return mat4[f32](input); -} - -fn testMat4ToMat2(input: mat4[f32]) -> mat2[f32] -{ - return mat2[f32](input); -} - -fn testMat4ToMat3(input: mat4[f32]) -> mat3[f32] -{ - return mat3[f32](input); -} - -fn testMat4ToMat4(input: mat4[f32]) -> mat4[f32] -{ - return mat4[f32](input); -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - - Nz::ShaderAst::SanitizeVisitor::Options options; - options.removeMatrixCast = true; - - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, options)); - - ExpectNZSL(*shaderModule, R"( -fn testMat2ToMat2(input: mat2[f32]) -> mat2[f32] -{ - return input; -} - -fn testMat2ToMat3(input: mat2[f32]) -> mat3[f32] -{ - let temp: mat3[f32]; - temp[0] = vec3[f32](input[0], 0.000000); - temp[1] = vec3[f32](input[1], 0.000000); - temp[2] = vec3[f32](input[2], 1.000000); - return temp; -} - -fn testMat2ToMat4(input: mat2[f32]) -> mat4[f32] -{ - let temp: mat4[f32]; - temp[0] = vec4[f32](input[0], 0.000000, 0.000000); - temp[1] = vec4[f32](input[1], 0.000000, 0.000000); - temp[2] = vec4[f32](input[2], 1.000000, 0.000000); - temp[3] = vec4[f32](input[3], 0.000000, 1.000000); - return temp; -} - -fn testMat3ToMat2(input: mat3[f32]) -> mat2[f32] -{ - let temp: mat2[f32]; - temp[0] = input[0].xy; - temp[1] = input[1].xy; - return temp; -} - -fn testMat3ToMat3(input: mat3[f32]) -> mat3[f32] -{ - return input; -} - -fn testMat3ToMat4(input: mat3[f32]) -> mat4[f32] -{ - let temp: mat4[f32]; - temp[0] = vec4[f32](input[0], 0.000000); - temp[1] = vec4[f32](input[1], 0.000000); - temp[2] = vec4[f32](input[2], 0.000000); - temp[3] = vec4[f32](input[3], 1.000000); - return temp; -} - -fn testMat4ToMat2(input: mat4[f32]) -> mat2[f32] -{ - let temp: mat2[f32]; - temp[0] = input[0].xy; - temp[1] = input[1].xy; - return temp; -} - -fn testMat4ToMat3(input: mat4[f32]) -> mat3[f32] -{ - let temp: mat3[f32]; - temp[0] = input[0].xyz; - temp[1] = input[1].xyz; - temp[2] = input[2].xyz; - return temp; -} - -fn testMat4ToMat4(input: mat4[f32]) -> mat4[f32] -{ - return input; -} -)"); - - } - - WHEN("removing aliases") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -alias Input = inputStruct; -alias In = Input; - -external -{ - [set(0), binding(0)] data: uniform[In] -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - - Nz::ShaderAst::SanitizeVisitor::Options options; - options.removeAliases = true; - - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*shaderModule, options)); - - ExpectNZSL(*shaderModule, R"( -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} -)"); - - } -} diff --git a/tests/Engine/Shader/SerializationsTests.cpp b/tests/Engine/Shader/SerializationsTests.cpp deleted file mode 100644 index 5b9370873..000000000 --- a/tests/Engine/Shader/SerializationsTests.cpp +++ /dev/null @@ -1,201 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void ParseSerializeUnserialize(std::string_view sourceCode, bool sanitize) -{ - Nz::ShaderAst::ModulePtr shaderModule; - REQUIRE_NOTHROW(shaderModule = Nz::ShaderLang::Parse(sourceCode)); - - if (sanitize) - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*shaderModule)); - - Nz::ByteArray serializedModule; - REQUIRE_NOTHROW(serializedModule = Nz::ShaderAst::SerializeShader(shaderModule)); - - Nz::ByteStream byteStream(&serializedModule); - Nz::ShaderAst::ModulePtr unserializedShader; - REQUIRE_NOTHROW(unserializedShader = Nz::ShaderAst::UnserializeShader(byteStream)); - - CHECK(Nz::ShaderAst::Compare(*shaderModule, *unserializedShader)); -} - -void ParseSerializeUnserialize(std::string_view sourceCode) -{ - ParseSerializeUnserialize(sourceCode, false); - ParseSerializeUnserialize(sourceCode, true); -} - -TEST_CASE("serialization", "[Shader]") -{ - WHEN("serializing and unserializing a simple shader") - { - ParseSerializeUnserialize(R"( -[nzsl_version("1.0")] -module; - -struct Data -{ - value: f32 -} - -struct Output -{ - [location(0)] value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[Data] -} - -[entry(frag)] -fn main() -> Output -{ - let output: Output; - output.value = data.value; - - return output; -} -)"); - } - - WHEN("serializing and unserializing branches") - { - ParseSerializeUnserialize(R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - if (data.value > 3.0) - value = 3.0; - else if (data.value > 2.0) - value = 2.0; - else if (data.value > 1.0) - value = 1.0; - else - value = 0.0; -} -)"); - } - - WHEN("serializing and unserializing consts") - { - ParseSerializeUnserialize(R"( -[nzsl_version("1.0")] -module; - -option UseInt: bool = false; - -[cond(UseInt)] -struct inputStruct -{ - value: i32 -} - -[cond(!UseInt)] -struct inputStruct -{ - value: f32 -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value: f32; - - const if (UseInt) - { - value = f32(data.value); - } - else - { - value = data.value; - } -} -)"); - } - - WHEN("serializing and unserializing loops") - { - ParseSerializeUnserialize(R"( -[nzsl_version("1.0")] -module; - -struct inputStruct -{ - value: array[f32, 10] -} - -external -{ - [set(0), binding(0)] data: uniform[inputStruct] -} - -[entry(frag)] -fn main() -{ - let value = 0.0; - let i = 0; - while (i < 10) - { - value += 0.1; - i += 1; - } - - let x = 0; - for v in 0 -> 10 - { - x += v; - } - - let x = 0.0; - for v in data.value - { - x += v; - } -} -)"); - } - - WHEN("serializing and unserializing swizzles") - { - ParseSerializeUnserialize(R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let vec = vec4[f32](0.0, 1.0, 2.0, 3.0); - vec.wyxz.bra.ts.x = 0.0; - vec.zyxw.ar.xy.yx = vec2[f32](1.0, 0.0); -} -)"); - } -} diff --git a/tests/Engine/Shader/ShaderUtils.cpp b/tests/Engine/Shader/ShaderUtils.cpp deleted file mode 100644 index 32f72d43c..000000000 --- a/tests/Engine/Shader/ShaderUtils.cpp +++ /dev/null @@ -1,302 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace -{ - // Use OpenGL default minimal values (from https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glGet.xhtml, https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGet.xhtml and https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/) - const TBuiltInResource s_minResources = { - 8, //< maxLights - 6, //< maxClipPlanes - 32, //< maxTextureUnits - 32, //< maxTextureCoords - 16, //< maxVertexAttribs - 1024, //< maxVertexUniformComponents - 60, //< maxVaryingFloats - 16, //< maxVertexTextureImageUnits - 32, //< maxCombinedTextureImageUnits - 16, //< maxTextureImageUnits - 896, //< maxFragmentUniformComponents - 4, //< maxDrawBuffers - 256, //< maxVertexUniformVectors - 15, //< maxVaryingVectors - 224, //< maxFragmentUniformVectors - 256, //< maxVertexOutputVectors - 224, //< maxFragmentInputVectors - -8, //< minProgramTexelOffset - 7, //< maxProgramTexelOffset - 8, //< maxClipDistances - 0xFFFF, //< maxComputeWorkGroupCountX - 0xFFFF, //< maxComputeWorkGroupCountY - 0xFFFF, //< maxComputeWorkGroupCountZ - 1024, //< maxComputeWorkGroupSizeX - 1024, //< maxComputeWorkGroupSizeY - 64, //< maxComputeWorkGroupSizeZ - 1024, //< maxComputeUniformComponents - 16, //< maxComputeTextureImageUnits - 8, //< maxComputeImageUniforms - 8, //< maxComputeAtomicCounters - 1, //< maxComputeAtomicCounterBuffers - 60, //< maxVaryingComponents - 64, //< maxVertexOutputComponents - 64, //< maxGeometryInputComponents - 128, //< maxGeometryOutputComponents - 128, //< maxFragmentInputComponents - 8, //< maxImageUnits - 8, //< maxCombinedImageUnitsAndFragmentOutputs - 8, //< maxCombinedShaderOutputResources - 0, //< maxImageSamples - 0, //< maxVertexImageUniforms - 0, //< maxTessControlImageUniforms - 0, //< maxTessEvaluationImageUniforms - 0, //< maxGeometryImageUniforms - 8, //< maxFragmentImageUniforms - 8, //< maxCombinedImageUniforms - 16, //< maxGeometryTextureImageUnits - 256, //< maxGeometryOutputVertices - 1024, //< maxGeometryTotalOutputComponents - 1024, //< maxGeometryUniformComponents - 64, //< maxGeometryVaryingComponents - 128, //< maxTessControlInputComponents - 128, //< maxTessControlOutputComponents - 16, //< maxTessControlTextureImageUnits - 1024, //< maxTessControlUniformComponents - 4096, //< maxTessControlTotalOutputComponents - 128, //< maxTessEvaluationInputComponents - 128, //< maxTessEvaluationOutputComponents - 16, //< maxTessEvaluationTextureImageUnits - 1024, //< maxTessEvaluationUniformComponents - 120, //< maxTessPatchComponents - 32, //< maxPatchVertices - 64, //< maxTessGenLevel - 16, //< maxViewports - 0, //< maxVertexAtomicCounters - 0, //< maxTessControlAtomicCounters - 0, //< maxTessEvaluationAtomicCounters - 0, //< maxGeometryAtomicCounters - 8, //< maxFragmentAtomicCounters - 8, //< maxCombinedAtomicCounters - 1, //< maxAtomicCounterBindings - 0, //< maxVertexAtomicCounterBuffers - 0, //< maxTessControlAtomicCounterBuffers - 0, //< maxTessEvaluationAtomicCounterBuffers - 0, //< maxGeometryAtomicCounterBuffers - 1, //< maxFragmentAtomicCounterBuffers - 1, //< maxCombinedAtomicCounterBuffers - 16384, //< maxAtomicCounterBufferSize - 4, //< maxTransformFeedbackBuffers - 64, //< maxTransformFeedbackInterleavedComponents - 8, //< maxCullDistances - 8, //< maxCombinedClipAndCullDistances - 4, //< maxSamples - 256, //< maxMeshOutputVerticesNV - 512, //< maxMeshOutputPrimitivesNV - 32, //< maxMeshWorkGroupSizeX_NV - 1, //< maxMeshWorkGroupSizeY_NV - 1, //< maxMeshWorkGroupSizeZ_NV - 32, //< maxTaskWorkGroupSizeX_NV - 1, //< maxTaskWorkGroupSizeY_NV - 1, //< maxTaskWorkGroupSizeZ_NV - 4, //< maxMeshViewCountNV - 1, //< maxDualSourceDrawBuffersEXT - { //< limits - true, //< nonInductiveForLoops - true, //< whileLoops - true, //< doWhileLoops - true, //< generalUniformIndexing - true, //< generalAttributeMatrixVectorIndexing - true, //< generalVaryingIndexing - true, //< generalSamplerIndexing - true, //< generalVariableIndexing - true, //< generalConstantMatrixVectorIndexing - } - }; -} - -void ExpectGLSL(const Nz::ShaderAst::Module& shaderModule, std::string_view expectedOutput) -{ - expectedOutput = Nz::Trim(expectedOutput); - - SECTION("Generating GLSL") - { - Nz::ShaderAst::ModulePtr sanitizedModule; - WHEN("Sanitizing a second time") - { - CHECK_NOTHROW(sanitizedModule = Nz::ShaderAst::Sanitize(shaderModule)); - } - const Nz::ShaderAst::Module& targetModule = (sanitizedModule) ? *sanitizedModule : shaderModule; - - // Retrieve entry-point to get shader type - std::optional entryShaderStage; - - Nz::ShaderAst::AstReflect::Callbacks callbacks; - callbacks.onEntryPointDeclaration = [&](Nz::ShaderStageType stageType, const std::string& functionName) - { - INFO("multiple entry points found! (" << functionName << ")"); - REQUIRE((!entryShaderStage.has_value() || stageType == entryShaderStage)); - - entryShaderStage = stageType; - }; - - Nz::ShaderAst::AstReflect reflectVisitor; - reflectVisitor.Reflect(*targetModule.rootNode, callbacks); - - { - INFO("no entry point found"); - REQUIRE(entryShaderStage.has_value()); - } - - Nz::GlslWriter writer; - std::string output = writer.Generate(entryShaderStage, targetModule); - - WHEN("Validating expected code") - { - INFO("full GLSL output:\n" << output << "\nexcepted output:\n" << expectedOutput); - REQUIRE(output.find(expectedOutput) != std::string::npos); - } - - WHEN("Validating full GLSL code (using glslang)") - { - EShLanguage stage = EShLangVertex; - switch (*entryShaderStage) - { - case Nz::ShaderStageType::Fragment: - stage = EShLangFragment; - break; - - case Nz::ShaderStageType::Vertex: - stage = EShLangVertex; - break; - } - - glslang::TShader glslangShader(stage); - glslangShader.setEnvInput(glslang::EShSourceGlsl, stage, glslang::EShClientOpenGL, 300); - glslangShader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); - glslangShader.setEnvTarget(glslang::EShTargetNone, static_cast(0)); - glslangShader.setEntryPoint("main"); - - const char* source = output.c_str(); - glslangShader.setStrings(&source, 1); - - if (!glslangShader.parse(&s_minResources, 100, false, static_cast(EShMsgDefault | EShMsgKeepUncalled))) - { - INFO("full GLSL output:\n" << output << "\nerror:\n" << glslangShader.getInfoLog()); - REQUIRE(false); - } - } - } -} - -void ExpectNZSL(const Nz::ShaderAst::Module& shaderModule, std::string_view expectedOutput) -{ - expectedOutput = Nz::Trim(expectedOutput); - - SECTION("Generating NZSL") - { - Nz::ShaderAst::ModulePtr sanitizedModule; - WHEN("Sanitizing a second time") - { - CHECK_NOTHROW(sanitizedModule = Nz::ShaderAst::Sanitize(shaderModule)); - } - const Nz::ShaderAst::Module& targetModule = (sanitizedModule) ? *sanitizedModule : shaderModule; - - Nz::LangWriter writer; - std::string output = writer.Generate(targetModule); - - WHEN("Validating expected code") - { - INFO("full NZSL output:\n" << output << "\nexcepted output:\n" << expectedOutput); - REQUIRE(output.find(expectedOutput) != std::string::npos); - } - - WHEN("Validating full NZSL code (by recompiling it)") - { - // validate NZSL by recompiling it - REQUIRE_NOTHROW(Nz::ShaderLang::Parse(output)); - } - } -} - -void ExpectSPIRV(const Nz::ShaderAst::Module& shaderModule, std::string_view expectedOutput, bool outputParameter) -{ - expectedOutput = Nz::Trim(expectedOutput); - - SECTION("Generating SPIRV") - { - Nz::ShaderAst::ModulePtr sanitizedModule; - WHEN("Sanitizing a second time") - { - CHECK_NOTHROW(sanitizedModule = Nz::ShaderAst::Sanitize(shaderModule)); - } - const Nz::ShaderAst::Module& targetModule = (sanitizedModule) ? *sanitizedModule : shaderModule; - - Nz::SpirvWriter writer; - Nz::SpirvPrinter printer; - - Nz::SpirvPrinter::Settings settings; - settings.printHeader = false; - settings.printParameters = outputParameter; - - auto spirv = writer.Generate(targetModule); - std::string output = printer.Print(spirv.data(), spirv.size(), settings); - - WHEN("Validating expected code") - { - INFO("full SPIRV output:\n" << output << "\nexcepted output:\n" << expectedOutput); - REQUIRE(output.find(expectedOutput) != std::string::npos); - } - - WHEN("Validating full SPIRV code (using libspirv)") - { - // validate SPIRV with libspirv - spvtools::SpirvTools spirvTools(spv_target_env::SPV_ENV_VULKAN_1_0); - spirvTools.SetMessageConsumer([&](spv_message_level_t /*level*/, const char* /*source*/, const spv_position_t& /*position*/, const char* message) - { - std::string fullSpirv; - if (!spirvTools.Disassemble(spirv, &fullSpirv)) - fullSpirv = ""; - - UNSCOPED_INFO(fullSpirv + "\n" + message); - }); - - REQUIRE(spirvTools.Validate(spirv)); - } - } -} - -Nz::ShaderAst::ModulePtr SanitizeModule(const Nz::ShaderAst::Module& module) -{ - Nz::ShaderAst::SanitizeVisitor::Options defaultOptions; - return SanitizeModule(module, defaultOptions); -} - -Nz::ShaderAst::ModulePtr SanitizeModule(const Nz::ShaderAst::Module& module, const Nz::ShaderAst::SanitizeVisitor::Options& options) -{ - Nz::ShaderAst::ModulePtr shaderModule; - WHEN("We sanitize the shader") - { - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(module, options)); - } - - WHEN("We output NZSL and try to parse it again") - { - Nz::LangWriter langWriter; - std::string outputCode = langWriter.Generate((shaderModule) ? *shaderModule : module); - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*Nz::ShaderLang::Parse(outputCode), options)); - } - - // Ensure sanitization - if (!shaderModule) - REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(module, options)); - - return shaderModule; -} diff --git a/tests/Engine/Shader/ShaderUtils.hpp b/tests/Engine/Shader/ShaderUtils.hpp deleted file mode 100644 index 1958b3daa..000000000 --- a/tests/Engine/Shader/ShaderUtils.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#ifndef NAZARA_UNITTESTS_SHADER_SHADERUTILS_HPP -#define NAZARA_UNITTESTS_SHADER_SHADERUTILS_HPP - -#include -#include -#include - -void ExpectGLSL(const Nz::ShaderAst::Module& shader, std::string_view expectedOutput); -void ExpectNZSL(const Nz::ShaderAst::Module& shader, std::string_view expectedOutput); -void ExpectSPIRV(const Nz::ShaderAst::Module& shader, std::string_view expectedOutput, bool outputParameter = false); - -Nz::ShaderAst::ModulePtr SanitizeModule(const Nz::ShaderAst::Module& module); -Nz::ShaderAst::ModulePtr SanitizeModule(const Nz::ShaderAst::Module& module, const Nz::ShaderAst::SanitizeVisitor::Options& options); - -#endif diff --git a/tests/Engine/Shader/SwizzleTests.cpp b/tests/Engine/Shader/SwizzleTests.cpp deleted file mode 100644 index d2ff3f367..000000000 --- a/tests/Engine/Shader/SwizzleTests.cpp +++ /dev/null @@ -1,317 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -TEST_CASE("swizzle", "[Shader]") -{ - SECTION("Simple swizzle") - { - WHEN("reading") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let vec = vec4[f32](0.0, 1.0, 2.0, 3.0); - let value = vec.xyz; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - vec4 vec = vec4(0.000000, 1.000000, 2.000000, 3.000000); - vec3 value = vec.xyz; -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let vec: vec4[f32] = vec4[f32](0.000000, 1.000000, 2.000000, 3.000000); - let value: vec3[f32] = vec.xyz; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpCompositeConstruct -OpStore -OpLoad -OpVectorShuffle -OpStore -OpReturn -OpFunctionEnd)"); - } - - WHEN("writing") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let vec = vec4[f32](0.0, 0.0, 0.0, 0.0); - vec.yzw = vec3[f32](1.0, 2.0, 3.0); -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - vec4 vec = vec4(0.000000, 0.000000, 0.000000, 0.000000); - vec.yzw = vec3(1.000000, 2.000000, 3.000000); -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let vec: vec4[f32] = vec4[f32](0.000000, 0.000000, 0.000000, 0.000000); - vec.yzw = vec3[f32](1.000000, 2.000000, 3.000000); -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpCompositeConstruct -OpStore -OpCompositeConstruct -OpLoad -OpVectorShuffle -OpStore -OpReturn -OpFunctionEnd)"); - } - } - - SECTION("Scalar swizzle") - { - GIVEN("a variable") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let value = 42.0; - let vec = value.xxx; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float value = 42.000000; - vec3 vec = vec3(value, value, value); -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let value: f32 = 42.000000; - let vec: vec3[f32] = value.xxx; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpStore -OpLoad -OpCompositeConstruct -OpStore -OpReturn -OpFunctionEnd)"); - } - - GIVEN("a function value") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let v = max(2.0, 1.0).xxx; - let v2 = min(2.0, 1.0).xxx; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - float cachedResult = max(2.000000, 1.000000); - vec3 v = vec3(cachedResult, cachedResult, cachedResult); - float cachedResult_2 = min(2.000000, 1.000000); - vec3 v2 = vec3(cachedResult_2, cachedResult_2, cachedResult_2); -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let v: vec3[f32] = (max(2.000000, 1.000000)).xxx; - let v2: vec3[f32] = (min(2.000000, 1.000000)).xxx; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpExtInst -OpCompositeConstruct -OpStore -OpExtInst -OpCompositeConstruct -OpStore -OpReturn -OpFunctionEnd)"); - } - } - - SECTION("Complex swizzle") - { - WHEN("reading") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let vec = vec4[f32](0.0, 1.0, 2.0, 3.0); - let value = vec.xyz.yz.y.x.xxxx; -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - vec4 vec = vec4(0.000000, 1.000000, 2.000000, 3.000000); - vec4 value = vec4(vec.xyz.yz.y, vec.xyz.yz.y, vec.xyz.yz.y, vec.xyz.yz.y); -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let vec: vec4[f32] = vec4[f32](0.000000, 1.000000, 2.000000, 3.000000); - let value: vec4[f32] = vec.xyz.yz.y.x.xxxx; -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpVariable -OpCompositeConstruct -OpStore -OpLoad -OpVectorShuffle -OpVectorShuffle -OpCompositeExtract -OpCompositeConstruct -OpStore -OpReturn -OpFunctionEnd)"); - } - - WHEN("writing") - { - std::string_view nzslSource = R"( -[nzsl_version("1.0")] -module; - -[entry(frag)] -fn main() -{ - let vec = vec4[f32](0.0, 1.0, 2.0, 3.0); - vec.wyxz.bra.ts.x = 0.0; - vec.zyxw.ar.xy.yx = vec2[f32](1.0, 0.0); -} -)"; - - Nz::ShaderAst::ModulePtr shaderModule = Nz::ShaderLang::Parse(nzslSource); - shaderModule = SanitizeModule(*shaderModule); - - ExpectGLSL(*shaderModule, R"( -void main() -{ - vec4 vec = vec4(0.000000, 1.000000, 2.000000, 3.000000); - vec.wyxz.zxw.yx.x = 0.000000; - vec.zyxw.wx.xy.yx = vec2(1.000000, 0.000000); -} -)"); - - ExpectNZSL(*shaderModule, R"( -[entry(frag)] -fn main() -{ - let vec: vec4[f32] = vec4[f32](0.000000, 1.000000, 2.000000, 3.000000); - vec.wyxz.zxw.yx.x = 0.000000; - vec.zyxw.wx.xy.yx = vec2[f32](1.000000, 0.000000); -} -)"); - - ExpectSPIRV(*shaderModule, R"( -OpFunction -OpLabel -OpVariable -OpCompositeConstruct -OpStore -OpAccessChain -OpStore -OpCompositeConstruct -OpLoad -OpVectorShuffle -OpStore -OpReturn -OpFunctionEnd)"); - } - } -} diff --git a/tests/main.cpp b/tests/main.cpp index 4184253a2..70e676213 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -7,20 +7,11 @@ #include #include #include -#include #include -#include int main(int argc, char* argv[]) { - Nz::Modules nazaza; + Nz::Modules nazaza; - if (!glslang::InitializeProcess()) - return EXIT_FAILURE; - - int result = Catch::Session().run(argc, argv); - - glslang::FinalizeProcess(); - - return result; + return Catch::Session().run(argc, argv); } diff --git a/tests/xmake.lua b/tests/xmake.lua index 1d8e6a80e..f47155914 100644 --- a/tests/xmake.lua +++ b/tests/xmake.lua @@ -11,14 +11,14 @@ if has_config("tests") then add_defines("CATCH_CONFIG_NO_POSIX_SIGNALS") end - add_requires("catch2", "glslang", "spirv-tools") + add_requires("catch2") -- Common config set_group("Tests") set_kind("binary") - add_deps("NazaraAudio", "NazaraCore", "NazaraNetwork", "NazaraPhysics2D", "NazaraShader") - add_packages("catch2", "entt", "glslang", "spirv-tools") + add_deps("NazaraAudio", "NazaraCore", "NazaraNetwork", "NazaraPhysics2D") + add_packages("catch2", "entt") add_headerfiles("Engine/**.hpp") add_files("resources.cpp") add_files("Engine/**.cpp") diff --git a/thirdparty/include/SpirV/GLSL.std.450.h b/thirdparty/include/SpirV/GLSL.std.450.h deleted file mode 100644 index 54cc00e9a..000000000 --- a/thirdparty/include/SpirV/GLSL.std.450.h +++ /dev/null @@ -1,131 +0,0 @@ -/* -** Copyright (c) 2014-2016 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a copy -** of this software and/or associated documentation files (the "Materials"), -** to deal in the Materials without restriction, including without limitation -** the rights to use, copy, modify, merge, publish, distribute, sublicense, -** and/or sell copies of the Materials, and to permit persons to whom the -** Materials are 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 Materials. -** -** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS -** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND -** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ -** -** THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS -** IN THE MATERIALS. -*/ - -#ifndef GLSLstd450_H -#define GLSLstd450_H - -static const int GLSLstd450Version = 100; -static const int GLSLstd450Revision = 3; - -enum GLSLstd450 { - GLSLstd450Bad = 0, // Don't use - - GLSLstd450Round = 1, - GLSLstd450RoundEven = 2, - GLSLstd450Trunc = 3, - GLSLstd450FAbs = 4, - GLSLstd450SAbs = 5, - GLSLstd450FSign = 6, - GLSLstd450SSign = 7, - GLSLstd450Floor = 8, - GLSLstd450Ceil = 9, - GLSLstd450Fract = 10, - - GLSLstd450Radians = 11, - GLSLstd450Degrees = 12, - GLSLstd450Sin = 13, - GLSLstd450Cos = 14, - GLSLstd450Tan = 15, - GLSLstd450Asin = 16, - GLSLstd450Acos = 17, - GLSLstd450Atan = 18, - GLSLstd450Sinh = 19, - GLSLstd450Cosh = 20, - GLSLstd450Tanh = 21, - GLSLstd450Asinh = 22, - GLSLstd450Acosh = 23, - GLSLstd450Atanh = 24, - GLSLstd450Atan2 = 25, - - GLSLstd450Pow = 26, - GLSLstd450Exp = 27, - GLSLstd450Log = 28, - GLSLstd450Exp2 = 29, - GLSLstd450Log2 = 30, - GLSLstd450Sqrt = 31, - GLSLstd450InverseSqrt = 32, - - GLSLstd450Determinant = 33, - GLSLstd450MatrixInverse = 34, - - GLSLstd450Modf = 35, // second operand needs an OpVariable to write to - GLSLstd450ModfStruct = 36, // no OpVariable operand - GLSLstd450FMin = 37, - GLSLstd450UMin = 38, - GLSLstd450SMin = 39, - GLSLstd450FMax = 40, - GLSLstd450UMax = 41, - GLSLstd450SMax = 42, - GLSLstd450FClamp = 43, - GLSLstd450UClamp = 44, - GLSLstd450SClamp = 45, - GLSLstd450FMix = 46, - GLSLstd450IMix = 47, // Reserved - GLSLstd450Step = 48, - GLSLstd450SmoothStep = 49, - - GLSLstd450Fma = 50, - GLSLstd450Frexp = 51, // second operand needs an OpVariable to write to - GLSLstd450FrexpStruct = 52, // no OpVariable operand - GLSLstd450Ldexp = 53, - - GLSLstd450PackSnorm4x8 = 54, - GLSLstd450PackUnorm4x8 = 55, - GLSLstd450PackSnorm2x16 = 56, - GLSLstd450PackUnorm2x16 = 57, - GLSLstd450PackHalf2x16 = 58, - GLSLstd450PackDouble2x32 = 59, - GLSLstd450UnpackSnorm2x16 = 60, - GLSLstd450UnpackUnorm2x16 = 61, - GLSLstd450UnpackHalf2x16 = 62, - GLSLstd450UnpackSnorm4x8 = 63, - GLSLstd450UnpackUnorm4x8 = 64, - GLSLstd450UnpackDouble2x32 = 65, - - GLSLstd450Length = 66, - GLSLstd450Distance = 67, - GLSLstd450Cross = 68, - GLSLstd450Normalize = 69, - GLSLstd450FaceForward = 70, - GLSLstd450Reflect = 71, - GLSLstd450Refract = 72, - - GLSLstd450FindILsb = 73, - GLSLstd450FindSMsb = 74, - GLSLstd450FindUMsb = 75, - - GLSLstd450InterpolateAtCentroid = 76, - GLSLstd450InterpolateAtSample = 77, - GLSLstd450InterpolateAtOffset = 78, - - GLSLstd450NMin = 79, - GLSLstd450NMax = 80, - GLSLstd450NClamp = 81, - - GLSLstd450Count -}; - -#endif // #ifndef GLSLstd450_H diff --git a/thirdparty/include/tsl/ordered_hash.h b/thirdparty/include/tsl/ordered_hash.h deleted file mode 100644 index 5fbbfcb01..000000000 --- a/thirdparty/include/tsl/ordered_hash.h +++ /dev/null @@ -1,1628 +0,0 @@ -/** - * MIT License - * - * Copyright (c) 2017 Thibaut Goetghebuer-Planchon - * - * 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. - */ -#ifndef TSL_ORDERED_HASH_H -#define TSL_ORDERED_HASH_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -/** - * Macros for compatibility with GCC 4.8 - */ -#if (defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 9)) -# define TSL_OH_NO_CONTAINER_ERASE_CONST_ITERATOR -# define TSL_OH_NO_CONTAINER_EMPLACE_CONST_ITERATOR -#endif - -/** - * Only activate tsl_oh_assert if TSL_DEBUG is defined. - * This way we avoid the performance hit when NDEBUG is not defined with assert as tsl_oh_assert is used a lot - * (people usually compile with "-O3" and not "-O3 -DNDEBUG"). - */ -#ifdef TSL_DEBUG -# define tsl_oh_assert(expr) assert(expr) -#else -# define tsl_oh_assert(expr) (static_cast(0)) -#endif - -/** - * If exceptions are enabled, throw the exception passed in parameter, otherwise call std::terminate. - */ -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (defined (_MSC_VER) && defined (_CPPUNWIND))) && !defined(TSL_NO_EXCEPTIONS) -# define TSL_OH_THROW_OR_TERMINATE(ex, msg) throw ex(msg) -#else -# define TSL_OH_NO_EXCEPTIONS -# ifdef NDEBUG -# define TSL_OH_THROW_OR_TERMINATE(ex, msg) std::terminate() -# else -# include -# define TSL_OH_THROW_OR_TERMINATE(ex, msg) do { std::cerr << msg << std::endl; std::terminate(); } while(0) -# endif -#endif - - -namespace tsl { - -namespace detail_ordered_hash { - -template -struct make_void { - using type = void; -}; - -template -struct has_is_transparent: std::false_type { -}; - -template -struct has_is_transparent::type>: std::true_type { -}; - - -template -struct is_vector: std::false_type { -}; - -template -struct is_vector>::value - >::type>: std::true_type { -}; - -// Only available in C++17, we need to be compatible with C++11 -template -const T& clamp( const T& v, const T& lo, const T& hi) { - return std::min(hi, std::max(lo, v)); -} - -template -static T numeric_cast(U value, const char* error_message = "numeric_cast() failed.") { - T ret = static_cast(value); - if(static_cast(ret) != value) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, error_message); - } - - const bool is_same_signedness = (std::is_unsigned::value && std::is_unsigned::value) || - (std::is_signed::value && std::is_signed::value); - if(!is_same_signedness && (ret < T{}) != (value < U{})) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, error_message); - } - - return ret; -} - - -/** - * Fixed size type used to represent size_type values on serialization. Need to be big enough - * to represent a std::size_t on 32 and 64 bits platforms, and must be the same size on both platforms. - */ -using slz_size_type = std::uint64_t; -static_assert(std::numeric_limits::max() >= std::numeric_limits::max(), - "slz_size_type must be >= std::size_t"); - -template -static T deserialize_value(Deserializer& deserializer) { - // MSVC < 2017 is not conformant, circumvent the problem by removing the template keyword -#if defined (_MSC_VER) && _MSC_VER < 1910 - return deserializer.Deserializer::operator()(); -#else - return deserializer.Deserializer::template operator()(); -#endif -} - - -/** - * Each bucket entry stores an index which is the index in m_values corresponding to the bucket's value - * and a hash (which may be truncated to 32 bits depending on IndexType) corresponding to the hash of the value. - * - * The size of IndexType limits the size of the hash table to std::numeric_limits::max() - 1 elements (-1 due to - * a reserved value used to mark a bucket as empty). - */ -template -class bucket_entry { - static_assert(std::is_unsigned::value, "IndexType must be an unsigned value."); - static_assert(std::numeric_limits::max() <= std::numeric_limits::max(), - "std::numeric_limits::max() must be <= std::numeric_limits::max()."); - -public: - using index_type = IndexType; - using truncated_hash_type = typename std::conditional::max() <= - std::numeric_limits::max(), - std::uint_least32_t, - std::size_t>::type; - - bucket_entry() noexcept: m_index(EMPTY_MARKER_INDEX), m_hash(0) { - } - - bool empty() const noexcept { - return m_index == EMPTY_MARKER_INDEX; - } - - void clear() noexcept { - m_index = EMPTY_MARKER_INDEX; - } - - index_type index() const noexcept { - tsl_oh_assert(!empty()); - return m_index; - } - - index_type& index_ref() noexcept { - tsl_oh_assert(!empty()); - return m_index; - } - - void set_index(index_type index) noexcept { - tsl_oh_assert(index <= max_size()); - - m_index = index; - } - - truncated_hash_type truncated_hash() const noexcept { - tsl_oh_assert(!empty()); - return m_hash; - } - - truncated_hash_type& truncated_hash_ref() noexcept { - tsl_oh_assert(!empty()); - return m_hash; - } - - void set_hash(std::size_t hash) noexcept { - m_hash = truncate_hash(hash); - } - - template - void serialize(Serializer& serializer) const { - const slz_size_type index = m_index; - serializer(index); - - const slz_size_type hash = m_hash; - serializer(hash); - } - - template - static bucket_entry deserialize(Deserializer& deserializer) { - const slz_size_type index = deserialize_value(deserializer); - const slz_size_type hash = deserialize_value(deserializer); - - bucket_entry bentry; - bentry.m_index = numeric_cast(index, "Deserialized index is too big."); - bentry.m_hash = numeric_cast(hash, "Deserialized hash is too big."); - - return bentry; - } - - - - static truncated_hash_type truncate_hash(std::size_t hash) noexcept { - return truncated_hash_type(hash); - } - - static std::size_t max_size() noexcept { - return static_cast(std::numeric_limits::max()) - NB_RESERVED_INDEXES; - } - -private: - static const index_type EMPTY_MARKER_INDEX = std::numeric_limits::max(); - static const std::size_t NB_RESERVED_INDEXES = 1; - - index_type m_index; - truncated_hash_type m_hash; -}; - - - -/** - * Internal common class used by ordered_map and ordered_set. - * - * ValueType is what will be stored by ordered_hash (usually std::pair for map and Key for set). - * - * KeySelect should be a FunctionObject which takes a ValueType in parameter and return a reference to the key. - * - * ValueSelect should be a FunctionObject which takes a ValueType in parameter and return a reference to the value. - * ValueSelect should be void if there is no value (in set for example). - * - * ValueTypeContainer is the container which will be used to store ValueType values. - * Usually a std::deque or std::vector. - * - * - * - * The ordered_hash structure is a hash table which preserves the order of insertion of the elements. - * To do so, it stores the values in the ValueTypeContainer (m_values) using emplace_back at each - * insertion of a new element. Another structure (m_buckets of type std::vector) will - * serve as buckets array for the hash table part. Each bucket stores an index which corresponds to - * the index in m_values where the bucket's value is and the (truncated) hash of this value. An index - * is used instead of a pointer to the value to reduce the size of each bucket entry. - * - * To resolve collisions in the buckets array, the structures use robin hood linear probing with - * backward shift deletion. - */ -template -class ordered_hash: private Hash, private KeyEqual { -private: - template - using has_mapped_type = typename std::integral_constant::value>; - - static_assert(std::is_same::value, - "ValueTypeContainer::value_type != ValueType. " - "Check that the ValueTypeContainer has 'Key' as type for a set or 'std::pair' as type for a map."); - - static_assert(std::is_same::value, - "ValueTypeContainer::allocator_type != Allocator. " - "Check that the allocator for ValueTypeContainer is the same as Allocator."); - - static_assert(std::is_same::value, - "Allocator::value_type != ValueType. " - "Check that the allocator has 'Key' as type for a set or 'std::pair' as type for a map."); - - -public: - template - class ordered_iterator; - - using key_type = typename KeySelect::key_type; - using value_type = ValueType; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - using hasher = Hash; - using key_equal = KeyEqual; - using allocator_type = Allocator; - using reference = value_type&; - using const_reference = const value_type&; - using pointer = value_type*; - using const_pointer = const value_type*; - using iterator = ordered_iterator; - using const_iterator = ordered_iterator; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - - using values_container_type = ValueTypeContainer; - -public: - template - class ordered_iterator { - friend class ordered_hash; - - private: - using iterator = typename std::conditional::type; - - - ordered_iterator(iterator it) noexcept: m_iterator(it) { - } - - public: - using iterator_category = std::random_access_iterator_tag; - using value_type = const typename ordered_hash::value_type; - using difference_type = typename iterator::difference_type; - using reference = value_type&; - using pointer = value_type*; - - - ordered_iterator() noexcept { - } - - // Copy constructor from iterator to const_iterator. - template::type* = nullptr> - ordered_iterator(const ordered_iterator& other) noexcept: m_iterator(other.m_iterator) { - } - - ordered_iterator(const ordered_iterator& other) = default; - ordered_iterator(ordered_iterator&& other) = default; - ordered_iterator& operator=(const ordered_iterator& other) = default; - ordered_iterator& operator=(ordered_iterator&& other) = default; - - const typename ordered_hash::key_type& key() const { - return KeySelect()(*m_iterator); - } - - template::value && IsConst>::type* = nullptr> - const typename U::value_type& value() const { - return U()(*m_iterator); - } - - template::value && !IsConst>::type* = nullptr> - typename U::value_type& value() { - return U()(*m_iterator); - } - - reference operator*() const { return *m_iterator; } - pointer operator->() const { return m_iterator.operator->(); } - - ordered_iterator& operator++() { ++m_iterator; return *this; } - ordered_iterator& operator--() { --m_iterator; return *this; } - - ordered_iterator operator++(int) { ordered_iterator tmp(*this); ++(*this); return tmp; } - ordered_iterator operator--(int) { ordered_iterator tmp(*this); --(*this); return tmp; } - - reference operator[](difference_type n) const { return m_iterator[n]; } - - ordered_iterator& operator+=(difference_type n) { m_iterator += n; return *this; } - ordered_iterator& operator-=(difference_type n) { m_iterator -= n; return *this; } - - ordered_iterator operator+(difference_type n) { ordered_iterator tmp(*this); tmp += n; return tmp; } - ordered_iterator operator-(difference_type n) { ordered_iterator tmp(*this); tmp -= n; return tmp; } - - friend bool operator==(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator == rhs.m_iterator; - } - - friend bool operator!=(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator != rhs.m_iterator; - } - - friend bool operator<(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator < rhs.m_iterator; - } - - friend bool operator>(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator > rhs.m_iterator; - } - - friend bool operator<=(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator <= rhs.m_iterator; - } - - friend bool operator>=(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator >= rhs.m_iterator; - } - - friend ordered_iterator operator+(difference_type n, const ordered_iterator& it) { - return n + it.m_iterator; - } - - friend difference_type operator-(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator - rhs.m_iterator; - } - - private: - iterator m_iterator; - }; - - -private: - using bucket_entry = tsl::detail_ordered_hash::bucket_entry; - - using buckets_container_allocator = typename - std::allocator_traits::template rebind_alloc; - - using buckets_container_type = std::vector; - - - using truncated_hash_type = typename bucket_entry::truncated_hash_type; - using index_type = typename bucket_entry::index_type; - -public: - ordered_hash(size_type bucket_count, - const Hash& hash, - const KeyEqual& equal, - const Allocator& alloc, - float max_load_factor): Hash(hash), - KeyEqual(equal), - m_buckets_data(alloc), - m_buckets(static_empty_bucket_ptr()), - m_hash_mask(0), - m_values(alloc), - m_grow_on_next_insert(false) - { - if(bucket_count > max_bucket_count()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maximum size."); - } - - if(bucket_count > 0) { - bucket_count = round_up_to_power_of_two(bucket_count); - - m_buckets_data.resize(bucket_count); - m_buckets = m_buckets_data.data(), - m_hash_mask = bucket_count - 1; - } - - this->max_load_factor(max_load_factor); - } - - ordered_hash(const ordered_hash& other): Hash(other), - KeyEqual(other), - m_buckets_data(other.m_buckets_data), - m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data()), - m_hash_mask(other.m_hash_mask), - m_values(other.m_values), - m_load_threshold(other.m_load_threshold), - m_max_load_factor(other.m_max_load_factor), - m_grow_on_next_insert(other.m_grow_on_next_insert) - { - } - - ordered_hash(ordered_hash&& other) noexcept(std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value) - : Hash(std::move(static_cast(other))), - KeyEqual(std::move(static_cast(other))), - m_buckets_data(std::move(other.m_buckets_data)), - m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data()), - m_hash_mask(other.m_hash_mask), - m_values(std::move(other.m_values)), - m_load_threshold(other.m_load_threshold), - m_max_load_factor(other.m_max_load_factor), - m_grow_on_next_insert(other.m_grow_on_next_insert) - { - other.m_buckets_data.clear(); - other.m_buckets = static_empty_bucket_ptr(); - other.m_hash_mask = 0; - other.m_values.clear(); - other.m_load_threshold = 0; - other.m_grow_on_next_insert = false; - } - - ordered_hash& operator=(const ordered_hash& other) { - if(&other != this) { - Hash::operator=(other); - KeyEqual::operator=(other); - - m_buckets_data = other.m_buckets_data; - m_buckets = m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data(); - - m_hash_mask = other.m_hash_mask; - m_values = other.m_values; - m_load_threshold = other.m_load_threshold; - m_max_load_factor = other.m_max_load_factor; - m_grow_on_next_insert = other.m_grow_on_next_insert; - } - - return *this; - } - - ordered_hash& operator=(ordered_hash&& other) { - other.swap(*this); - other.clear(); - - return *this; - } - - allocator_type get_allocator() const { - return m_values.get_allocator(); - } - - - /* - * Iterators - */ - iterator begin() noexcept { - return iterator(m_values.begin()); - } - - const_iterator begin() const noexcept { - return cbegin(); - } - - const_iterator cbegin() const noexcept { - return const_iterator(m_values.cbegin()); - } - - iterator end() noexcept { - return iterator(m_values.end()); - } - - const_iterator end() const noexcept { - return cend(); - } - - const_iterator cend() const noexcept { - return const_iterator(m_values.cend()); - } - - - reverse_iterator rbegin() noexcept { - return reverse_iterator(m_values.end()); - } - - const_reverse_iterator rbegin() const noexcept { - return rcbegin(); - } - - const_reverse_iterator rcbegin() const noexcept { - return const_reverse_iterator(m_values.cend()); - } - - reverse_iterator rend() noexcept { - return reverse_iterator(m_values.begin()); - } - - const_reverse_iterator rend() const noexcept { - return rcend(); - } - - const_reverse_iterator rcend() const noexcept { - return const_reverse_iterator(m_values.cbegin()); - } - - - /* - * Capacity - */ - bool empty() const noexcept { - return m_values.empty(); - } - - size_type size() const noexcept { - return m_values.size(); - } - - size_type max_size() const noexcept { - return std::min(bucket_entry::max_size(), m_values.max_size()); - } - - - /* - * Modifiers - */ - void clear() noexcept { - for(auto& bucket: m_buckets_data) { - bucket.clear(); - } - - m_values.clear(); - m_grow_on_next_insert = false; - } - - template - std::pair insert(P&& value) { - return insert_impl(KeySelect()(value), std::forward

(value)); - } - - template - iterator insert_hint(const_iterator hint, P&& value) { - if(hint != cend() && compare_keys(KeySelect()(*hint), KeySelect()(value))) { - return mutable_iterator(hint); - } - - return insert(std::forward

(value)).first; - } - - template - void insert(InputIt first, InputIt last) { - if(std::is_base_of::iterator_category>::value) - { - const auto nb_elements_insert = std::distance(first, last); - const size_type nb_free_buckets = m_load_threshold - size(); - tsl_oh_assert(m_load_threshold >= size()); - - if(nb_elements_insert > 0 && nb_free_buckets < size_type(nb_elements_insert)) { - reserve(size() + size_type(nb_elements_insert)); - } - } - - for(; first != last; ++first) { - insert(*first); - } - } - - - - template - std::pair insert_or_assign(K&& key, M&& value) { - auto it = try_emplace(std::forward(key), std::forward(value)); - if(!it.second) { - it.first.value() = std::forward(value); - } - - return it; - } - - template - iterator insert_or_assign(const_iterator hint, K&& key, M&& obj) { - if(hint != cend() && compare_keys(KeySelect()(*hint), key)) { - auto it = mutable_iterator(hint); - it.value() = std::forward(obj); - - return it; - } - - return insert_or_assign(std::forward(key), std::forward(obj)).first; - } - - - - template - std::pair emplace(Args&&... args) { - return insert(value_type(std::forward(args)...)); - } - - template - iterator emplace_hint(const_iterator hint, Args&&... args) { - return insert_hint(hint, value_type(std::forward(args)...)); - } - - - - template - std::pair try_emplace(K&& key, Args&&... value_args) { - return insert_impl(key, std::piecewise_construct, - std::forward_as_tuple(std::forward(key)), - std::forward_as_tuple(std::forward(value_args)...)); - } - - template - iterator try_emplace_hint(const_iterator hint, K&& key, Args&&... args) { - if(hint != cend() && compare_keys(KeySelect()(*hint), key)) { - return mutable_iterator(hint); - } - - return try_emplace(std::forward(key), std::forward(args)...).first; - } - - - - /** - * Here to avoid `template size_type erase(const K& key)` being used when - * we use an `iterator` instead of a `const_iterator`. - */ - iterator erase(iterator pos) { - return erase(const_iterator(pos)); - } - - iterator erase(const_iterator pos) { - tsl_oh_assert(pos != cend()); - - const std::size_t index_erase = iterator_to_index(pos); - - auto it_bucket = find_key(pos.key(), hash_key(pos.key())); - tsl_oh_assert(it_bucket != m_buckets_data.end()); - - erase_value_from_bucket(it_bucket); - - /* - * One element was removed from m_values, due to the left shift the next element - * is now at the position of the previous element (or end if none). - */ - return begin() + index_erase; - } - - iterator erase(const_iterator first, const_iterator last) { - if(first == last) { - return mutable_iterator(first); - } - - tsl_oh_assert(std::distance(first, last) > 0); - const std::size_t start_index = iterator_to_index(first); - const std::size_t nb_values = std::size_t(std::distance(first, last)); - const std::size_t end_index = start_index + nb_values; - - // Delete all values -#ifdef TSL_OH_NO_CONTAINER_ERASE_CONST_ITERATOR - auto next_it = m_values.erase(mutable_iterator(first).m_iterator, mutable_iterator(last).m_iterator); -#else - auto next_it = m_values.erase(first.m_iterator, last.m_iterator); -#endif - - /* - * Mark the buckets corresponding to the values as empty and do a backward shift. - * - * Also, the erase operation on m_values has shifted all the values on the right of last.m_iterator. - * Adapt the indexes for these values. - */ - std::size_t ibucket = 0; - while(ibucket < m_buckets_data.size()) { - if(m_buckets[ibucket].empty()) { - ibucket++; - } - else if(m_buckets[ibucket].index() >= start_index && m_buckets[ibucket].index() < end_index) { - m_buckets[ibucket].clear(); - backward_shift(ibucket); - // Don't increment ibucket, backward_shift may have replaced current bucket. - } - else if(m_buckets[ibucket].index() >= end_index) { - m_buckets[ibucket].set_index(index_type(m_buckets[ibucket].index() - nb_values)); - ibucket++; - } - else { - ibucket++; - } - } - - return iterator(next_it); - } - - - template - size_type erase(const K& key) { - return erase(key, hash_key(key)); - } - - template - size_type erase(const K& key, std::size_t hash) { - return erase_impl(key, hash); - } - - void swap(ordered_hash& other) { - using std::swap; - - swap(static_cast(*this), static_cast(other)); - swap(static_cast(*this), static_cast(other)); - swap(m_buckets_data, other.m_buckets_data); - swap(m_buckets, other.m_buckets); - swap(m_hash_mask, other.m_hash_mask); - swap(m_values, other.m_values); - swap(m_load_threshold, other.m_load_threshold); - swap(m_max_load_factor, other.m_max_load_factor); - swap(m_grow_on_next_insert, other.m_grow_on_next_insert); - } - - - - - /* - * Lookup - */ - template::value>::type* = nullptr> - typename U::value_type& at(const K& key) { - return at(key, hash_key(key)); - } - - template::value>::type* = nullptr> - typename U::value_type& at(const K& key, std::size_t hash) { - return const_cast(static_cast(this)->at(key, hash)); - } - - template::value>::type* = nullptr> - const typename U::value_type& at(const K& key) const { - return at(key, hash_key(key)); - } - - template::value>::type* = nullptr> - const typename U::value_type& at(const K& key, std::size_t hash) const { - auto it = find(key, hash); - if(it != end()) { - return it.value(); - } - else { - TSL_OH_THROW_OR_TERMINATE(std::out_of_range, "Couldn't find the key."); - } - } - - - template::value>::type* = nullptr> - typename U::value_type& operator[](K&& key) { - return try_emplace(std::forward(key)).first.value(); - } - - - template - size_type count(const K& key) const { - return count(key, hash_key(key)); - } - - template - size_type count(const K& key, std::size_t hash) const { - if(find(key, hash) == cend()) { - return 0; - } - else { - return 1; - } - } - - template - iterator find(const K& key) { - return find(key, hash_key(key)); - } - - template - iterator find(const K& key, std::size_t hash) { - auto it_bucket = find_key(key, hash); - return (it_bucket != m_buckets_data.end())?iterator(m_values.begin() + it_bucket->index()):end(); - } - - template - const_iterator find(const K& key) const { - return find(key, hash_key(key)); - } - - template - const_iterator find(const K& key, std::size_t hash) const { - auto it_bucket = find_key(key, hash); - return (it_bucket != m_buckets_data.cend())?const_iterator(m_values.begin() + it_bucket->index()):end(); - } - - - template - bool contains(const K& key) const { - return contains(key, hash_key(key)); - } - - template - bool contains(const K& key, std::size_t hash) const { - return find(key, hash) != cend(); - } - - - template - std::pair equal_range(const K& key) { - return equal_range(key, hash_key(key)); - } - - template - std::pair equal_range(const K& key, std::size_t hash) { - iterator it = find(key, hash); - return std::make_pair(it, (it == end())?it:std::next(it)); - } - - template - std::pair equal_range(const K& key) const { - return equal_range(key, hash_key(key)); - } - - template - std::pair equal_range(const K& key, std::size_t hash) const { - const_iterator it = find(key, hash); - return std::make_pair(it, (it == cend())?it:std::next(it)); - } - - - /* - * Bucket interface - */ - size_type bucket_count() const { - return m_buckets_data.size(); - } - - size_type max_bucket_count() const { - return m_buckets_data.max_size(); - } - - /* - * Hash policy - */ - float load_factor() const { - if(bucket_count() == 0) { - return 0; - } - - return float(size())/float(bucket_count()); - } - - float max_load_factor() const { - return m_max_load_factor; - } - - void max_load_factor(float ml) { - m_max_load_factor = clamp(ml, float(MAX_LOAD_FACTOR__MINIMUM), - float(MAX_LOAD_FACTOR__MAXIMUM)); - - m_max_load_factor = ml; - m_load_threshold = size_type(float(bucket_count())*m_max_load_factor); - } - - void rehash(size_type count) { - count = std::max(count, size_type(std::ceil(float(size())/max_load_factor()))); - rehash_impl(count); - } - - void reserve(size_type count) { - reserve_space_for_values(count); - - count = size_type(std::ceil(float(count)/max_load_factor())); - rehash(count); - } - - - /* - * Observers - */ - hasher hash_function() const { - return static_cast(*this); - } - - key_equal key_eq() const { - return static_cast(*this); - } - - - /* - * Other - */ - iterator mutable_iterator(const_iterator pos) { - return iterator(m_values.begin() + iterator_to_index(pos)); - } - - iterator nth(size_type index) { - tsl_oh_assert(index <= size()); - return iterator(m_values.begin() + index); - } - - const_iterator nth(size_type index) const { - tsl_oh_assert(index <= size()); - return const_iterator(m_values.cbegin() + index); - } - - const_reference front() const { - tsl_oh_assert(!empty()); - return m_values.front(); - } - - const_reference back() const { - tsl_oh_assert(!empty()); - return m_values.back(); - } - - const values_container_type& values_container() const noexcept { - return m_values; - } - - template::value>::type* = nullptr> - const typename values_container_type::value_type* data() const noexcept { - return m_values.data(); - } - - template::value>::type* = nullptr> - size_type capacity() const noexcept { - return m_values.capacity(); - } - - void shrink_to_fit() { - m_values.shrink_to_fit(); - } - - - template - std::pair insert_at_position(const_iterator pos, P&& value) { - return insert_at_position_impl(pos.m_iterator, KeySelect()(value), std::forward

(value)); - } - - template - std::pair emplace_at_position(const_iterator pos, Args&&... args) { - return insert_at_position(pos, value_type(std::forward(args)...)); - } - - template - std::pair try_emplace_at_position(const_iterator pos, K&& key, Args&&... value_args) { - return insert_at_position_impl(pos.m_iterator, key, - std::piecewise_construct, - std::forward_as_tuple(std::forward(key)), - std::forward_as_tuple(std::forward(value_args)...)); - } - - - void pop_back() { - tsl_oh_assert(!empty()); - erase(std::prev(end())); - } - - - /** - * Here to avoid `template size_type unordered_erase(const K& key)` being used when - * we use a iterator instead of a const_iterator. - */ - iterator unordered_erase(iterator pos) { - return unordered_erase(const_iterator(pos)); - } - - iterator unordered_erase(const_iterator pos) { - const std::size_t index_erase = iterator_to_index(pos); - unordered_erase(pos.key()); - - /* - * One element was deleted, index_erase now points to the next element as the elements after - * the deleted value were shifted to the left in m_values (will be end() if we deleted the last element). - */ - return begin() + index_erase; - } - - template - size_type unordered_erase(const K& key) { - return unordered_erase(key, hash_key(key)); - } - - template - size_type unordered_erase(const K& key, std::size_t hash) { - auto it_bucket_key = find_key(key, hash); - if(it_bucket_key == m_buckets_data.end()) { - return 0; - } - - /** - * If we are not erasing the last element in m_values, we swap - * the element we are erasing with the last element. We then would - * just have to do a pop_back() in m_values. - */ - if(!compare_keys(key, KeySelect()(back()))) { - auto it_bucket_last_elem = find_key(KeySelect()(back()), hash_key(KeySelect()(back()))); - tsl_oh_assert(it_bucket_last_elem != m_buckets_data.end()); - tsl_oh_assert(it_bucket_last_elem->index() == m_values.size() - 1); - - using std::swap; - swap(m_values[it_bucket_key->index()], m_values[it_bucket_last_elem->index()]); - swap(it_bucket_key->index_ref(), it_bucket_last_elem->index_ref()); - } - - erase_value_from_bucket(it_bucket_key); - - return 1; - } - - template - void serialize(Serializer& serializer) const { - serialize_impl(serializer); - } - - template - void deserialize(Deserializer& deserializer, bool hash_compatible) { - deserialize_impl(deserializer, hash_compatible); - } - - friend bool operator==(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values == rhs.m_values; - } - - friend bool operator!=(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values != rhs.m_values; - } - - friend bool operator<(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values < rhs.m_values; - } - - friend bool operator<=(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values <= rhs.m_values; - } - - friend bool operator>(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values > rhs.m_values; - } - - friend bool operator>=(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values >= rhs.m_values; - } - - -private: - template - std::size_t hash_key(const K& key) const { - return Hash::operator()(key); - } - - template - bool compare_keys(const K1& key1, const K2& key2) const { - return KeyEqual::operator()(key1, key2); - } - - template - typename buckets_container_type::iterator find_key(const K& key, std::size_t hash) { - auto it = static_cast(this)->find_key(key, hash); - return m_buckets_data.begin() + std::distance(m_buckets_data.cbegin(), it); - } - - /** - * Return bucket which has the key 'key' or m_buckets_data.end() if none. - * - * From the bucket_for_hash, search for the value until we either find an empty bucket - * or a bucket which has a value with a distance from its ideal bucket longer - * than the probe length for the value we are looking for. - */ - template - typename buckets_container_type::const_iterator find_key(const K& key, std::size_t hash) const { - for(std::size_t ibucket = bucket_for_hash(hash), dist_from_ideal_bucket = 0; ; - ibucket = next_bucket(ibucket), dist_from_ideal_bucket++) - { - if(m_buckets[ibucket].empty()) { - return m_buckets_data.end(); - } - else if(m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) && - compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) - { - return m_buckets_data.begin() + ibucket; - } - else if(dist_from_ideal_bucket > distance_from_ideal_bucket(ibucket)) { - return m_buckets_data.end(); - } - } - } - - void rehash_impl(size_type bucket_count) { - tsl_oh_assert(bucket_count >= size_type(std::ceil(float(size())/max_load_factor()))); - - if(bucket_count > max_bucket_count()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maximum size."); - } - - if(bucket_count > 0) { - bucket_count = round_up_to_power_of_two(bucket_count); - } - - if(bucket_count == this->bucket_count()) { - return; - } - - - buckets_container_type old_buckets(bucket_count); - m_buckets_data.swap(old_buckets); - m_buckets = m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data(); - // Everything should be noexcept from here. - - m_hash_mask = (bucket_count > 0)?(bucket_count - 1):0; - this->max_load_factor(m_max_load_factor); - m_grow_on_next_insert = false; - - - - for(const bucket_entry& old_bucket: old_buckets) { - if(old_bucket.empty()) { - continue; - } - - truncated_hash_type insert_hash = old_bucket.truncated_hash(); - index_type insert_index = old_bucket.index(); - - for(std::size_t ibucket = bucket_for_hash(insert_hash), dist_from_ideal_bucket = 0; ; - ibucket = next_bucket(ibucket), dist_from_ideal_bucket++) - { - if(m_buckets[ibucket].empty()) { - m_buckets[ibucket].set_index(insert_index); - m_buckets[ibucket].set_hash(insert_hash); - break; - } - - const std::size_t distance = distance_from_ideal_bucket(ibucket); - if(dist_from_ideal_bucket > distance) { - std::swap(insert_index, m_buckets[ibucket].index_ref()); - std::swap(insert_hash, m_buckets[ibucket].truncated_hash_ref()); - dist_from_ideal_bucket = distance; - } - } - } - } - - template::value>::type* = nullptr> - void reserve_space_for_values(size_type count) { - m_values.reserve(count); - } - - template::value>::type* = nullptr> - void reserve_space_for_values(size_type /*count*/) { - } - - /** - * Swap the empty bucket with the values on its right until we cross another empty bucket - * or if the other bucket has a distance_from_ideal_bucket == 0. - */ - void backward_shift(std::size_t empty_ibucket) noexcept { - tsl_oh_assert(m_buckets[empty_ibucket].empty()); - - std::size_t previous_ibucket = empty_ibucket; - for(std::size_t current_ibucket = next_bucket(previous_ibucket); - !m_buckets[current_ibucket].empty() && distance_from_ideal_bucket(current_ibucket) > 0; - previous_ibucket = current_ibucket, current_ibucket = next_bucket(current_ibucket)) - { - std::swap(m_buckets[current_ibucket], m_buckets[previous_ibucket]); - } - } - - void erase_value_from_bucket(typename buckets_container_type::iterator it_bucket) { - tsl_oh_assert(it_bucket != m_buckets_data.end() && !it_bucket->empty()); - - m_values.erase(m_values.begin() + it_bucket->index()); - - /* - * m_values.erase shifted all the values on the right of the erased value, - * shift the indexes by -1 in the buckets array for these values. - */ - if(it_bucket->index() != m_values.size()) { - shift_indexes_in_buckets(it_bucket->index(), -1); - } - - // Mark the bucket as empty and do a backward shift of the values on the right - it_bucket->clear(); - backward_shift(std::size_t(std::distance(m_buckets_data.begin(), it_bucket))); - } - - /** - * Go through each value from [from_ivalue, m_values.size()) in m_values and for each - * bucket corresponding to the value, shift the index by delta. - * - * delta must be equal to 1 or -1. - */ - void shift_indexes_in_buckets(index_type from_ivalue, int delta) noexcept { - tsl_oh_assert(delta == 1 || delta == -1); - - for(std::size_t ivalue = from_ivalue; ivalue < m_values.size(); ivalue++) { - // All the values in m_values have been shifted by delta. Find the bucket corresponding - // to the value m_values[ivalue] - const index_type old_index = static_cast(ivalue - delta); - - std::size_t ibucket = bucket_for_hash(hash_key(KeySelect()(m_values[ivalue]))); - while(m_buckets[ibucket].index() != old_index) { - ibucket = next_bucket(ibucket); - } - - m_buckets[ibucket].set_index(index_type(ivalue)); - } - } - - template - size_type erase_impl(const K& key, std::size_t hash) { - auto it_bucket = find_key(key, hash); - if(it_bucket != m_buckets_data.end()) { - erase_value_from_bucket(it_bucket); - - return 1; - } - else { - return 0; - } - } - - /** - * Insert the element at the end. - */ - template - std::pair insert_impl(const K& key, Args&&... value_type_args) { - const std::size_t hash = hash_key(key); - - std::size_t ibucket = bucket_for_hash(hash); - std::size_t dist_from_ideal_bucket = 0; - - while(!m_buckets[ibucket].empty() && dist_from_ideal_bucket <= distance_from_ideal_bucket(ibucket)) { - if(m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) && - compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) - { - return std::make_pair(begin() + m_buckets[ibucket].index(), false); - } - - ibucket = next_bucket(ibucket); - dist_from_ideal_bucket++; - } - - if(size() >= max_size()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "We reached the maximum size for the hash table."); - } - - - if(grow_on_high_load()) { - ibucket = bucket_for_hash(hash); - dist_from_ideal_bucket = 0; - } - - - m_values.emplace_back(std::forward(value_type_args)...); - insert_index(ibucket, dist_from_ideal_bucket, - index_type(m_values.size() - 1), bucket_entry::truncate_hash(hash)); - - - return std::make_pair(std::prev(end()), true); - } - - /** - * Insert the element before insert_position. - */ - template - std::pair insert_at_position_impl(typename values_container_type::const_iterator insert_position, - const K& key, Args&&... value_type_args) - { - const std::size_t hash = hash_key(key); - - std::size_t ibucket = bucket_for_hash(hash); - std::size_t dist_from_ideal_bucket = 0; - - while(!m_buckets[ibucket].empty() && dist_from_ideal_bucket <= distance_from_ideal_bucket(ibucket)) { - if(m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) && - compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) - { - return std::make_pair(begin() + m_buckets[ibucket].index(), false); - } - - ibucket = next_bucket(ibucket); - dist_from_ideal_bucket++; - } - - if(size() >= max_size()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "We reached the maximum size for the hash table."); - } - - - if(grow_on_high_load()) { - ibucket = bucket_for_hash(hash); - dist_from_ideal_bucket = 0; - } - - - const index_type index_insert_position = index_type(std::distance(m_values.cbegin(), insert_position)); - -#ifdef TSL_OH_NO_CONTAINER_EMPLACE_CONST_ITERATOR - m_values.emplace(m_values.begin() + std::distance(m_values.cbegin(), insert_position), std::forward(value_type_args)...); -#else - m_values.emplace(insert_position, std::forward(value_type_args)...); -#endif - - insert_index(ibucket, dist_from_ideal_bucket, - index_insert_position, bucket_entry::truncate_hash(hash)); - - /* - * The insertion didn't happend at the end of the m_values container, - * we need to shift the indexes in m_buckets_data. - */ - if(index_insert_position != m_values.size() - 1) { - shift_indexes_in_buckets(index_insert_position + 1, 1); - } - - return std::make_pair(iterator(m_values.begin() + index_insert_position), true); - } - - void insert_index(std::size_t ibucket, std::size_t dist_from_ideal_bucket, - index_type index_insert, truncated_hash_type hash_insert) noexcept - { - while(!m_buckets[ibucket].empty()) { - const std::size_t distance = distance_from_ideal_bucket(ibucket); - if(dist_from_ideal_bucket > distance) { - std::swap(index_insert, m_buckets[ibucket].index_ref()); - std::swap(hash_insert, m_buckets[ibucket].truncated_hash_ref()); - - dist_from_ideal_bucket = distance; - } - - - ibucket = next_bucket(ibucket); - dist_from_ideal_bucket++; - - - if(dist_from_ideal_bucket > REHASH_ON_HIGH_NB_PROBES__NPROBES && !m_grow_on_next_insert && - load_factor() >= REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR) - { - // We don't want to grow the map now as we need this method to be noexcept. - // Do it on next insert. - m_grow_on_next_insert = true; - } - } - - - m_buckets[ibucket].set_index(index_insert); - m_buckets[ibucket].set_hash(hash_insert); - } - - std::size_t distance_from_ideal_bucket(std::size_t ibucket) const noexcept { - const std::size_t ideal_bucket = bucket_for_hash(m_buckets[ibucket].truncated_hash()); - - if(ibucket >= ideal_bucket) { - return ibucket - ideal_bucket; - } - // If the bucket is smaller than the ideal bucket for the value, there was a wrapping at the end of the - // bucket array due to the modulo. - else { - return (bucket_count() + ibucket) - ideal_bucket; - } - } - - std::size_t next_bucket(std::size_t index) const noexcept { - tsl_oh_assert(index < m_buckets_data.size()); - - index++; - return (index < m_buckets_data.size())?index:0; - } - - std::size_t bucket_for_hash(std::size_t hash) const noexcept { - return hash & m_hash_mask; - } - - std::size_t iterator_to_index(const_iterator it) const noexcept { - const auto dist = std::distance(cbegin(), it); - tsl_oh_assert(dist >= 0); - - return std::size_t(dist); - } - - /** - * Return true if the map has been rehashed. - */ - bool grow_on_high_load() { - if(m_grow_on_next_insert || size() >= m_load_threshold) { - rehash_impl(std::max(size_type(1), bucket_count() * 2)); - m_grow_on_next_insert = false; - - return true; - } - else { - return false; - } - } - - template - void serialize_impl(Serializer& serializer) const { - const slz_size_type version = SERIALIZATION_PROTOCOL_VERSION; - serializer(version); - - const slz_size_type nb_elements = m_values.size(); - serializer(nb_elements); - - const slz_size_type bucket_count = m_buckets_data.size(); - serializer(bucket_count); - - const float max_load_factor = m_max_load_factor; - serializer(max_load_factor); - - - for(const value_type& value: m_values) { - serializer(value); - } - - for(const bucket_entry& bucket: m_buckets_data) { - bucket.serialize(serializer); - } - } - - template - void deserialize_impl(Deserializer& deserializer, bool hash_compatible) { - tsl_oh_assert(m_buckets_data.empty()); // Current hash table must be empty - - const slz_size_type version = deserialize_value(deserializer); - // For now we only have one version of the serialization protocol. - // If it doesn't match there is a problem with the file. - if(version != SERIALIZATION_PROTOCOL_VERSION) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, "Can't deserialize the ordered_map/set. " - "The protocol version header is invalid."); - } - - const slz_size_type nb_elements = deserialize_value(deserializer); - const slz_size_type bucket_count_ds = deserialize_value(deserializer); - const float max_load_factor = deserialize_value(deserializer); - - if(max_load_factor < MAX_LOAD_FACTOR__MINIMUM || max_load_factor > MAX_LOAD_FACTOR__MAXIMUM) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, "Invalid max_load_factor. Check that the serializer " - "and deserializer support floats correctly as they " - "can be converted implicitly to ints."); - } - - - this->max_load_factor(max_load_factor); - - if(bucket_count_ds == 0) { - tsl_oh_assert(nb_elements == 0); - return; - } - - - if(!hash_compatible) { - reserve(numeric_cast(nb_elements, "Deserialized nb_elements is too big.")); - for(slz_size_type el = 0; el < nb_elements; el++) { - insert(deserialize_value(deserializer)); - } - } - else { - m_buckets_data.reserve(numeric_cast(bucket_count_ds, "Deserialized bucket_count is too big.")); - m_buckets = m_buckets_data.data(), - m_hash_mask = m_buckets_data.capacity() - 1; - - reserve_space_for_values(numeric_cast(nb_elements, "Deserialized nb_elements is too big.")); - for(slz_size_type el = 0; el < nb_elements; el++) { - m_values.push_back(deserialize_value(deserializer)); - } - - for(slz_size_type b = 0; b < bucket_count_ds; b++) { - m_buckets_data.push_back(bucket_entry::deserialize(deserializer)); - } - } - } - - static std::size_t round_up_to_power_of_two(std::size_t value) { - if(is_power_of_two(value)) { - return value; - } - - if(value == 0) { - return 1; - } - - --value; - for(std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) { - value |= value >> i; - } - - return value + 1; - } - - static constexpr bool is_power_of_two(std::size_t value) { - return value != 0 && (value & (value - 1)) == 0; - } - - -public: - static const size_type DEFAULT_INIT_BUCKETS_SIZE = 0; - static constexpr float DEFAULT_MAX_LOAD_FACTOR = 0.75f; - -private: - static constexpr float MAX_LOAD_FACTOR__MINIMUM = 0.1f; - static constexpr float MAX_LOAD_FACTOR__MAXIMUM = 0.95f; - - static const size_type REHASH_ON_HIGH_NB_PROBES__NPROBES = 128; - static constexpr float REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR = 0.15f; - - /** - * Protocol version currenlty used for serialization. - */ - static const slz_size_type SERIALIZATION_PROTOCOL_VERSION = 1; - - /** - * Return an always valid pointer to an static empty bucket_entry with last_bucket() == true. - */ - bucket_entry* static_empty_bucket_ptr() { - static bucket_entry empty_bucket; - return &empty_bucket; - } - -private: - buckets_container_type m_buckets_data; - - /** - * Points to m_buckets_data.data() if !m_buckets_data.empty() otherwise points to static_empty_bucket_ptr. - * This variable is useful to avoid the cost of checking if m_buckets_data is empty when trying - * to find an element. - * - * TODO Remove m_buckets_data and only use a pointer+size instead of a pointer+vector to save some space in the ordered_hash object. - */ - bucket_entry* m_buckets; - - size_type m_hash_mask; - - values_container_type m_values; - - size_type m_load_threshold; - float m_max_load_factor; - - bool m_grow_on_next_insert; -}; - - -} // end namespace detail_ordered_hash - -} // end namespace tsl - -#endif diff --git a/thirdparty/include/tsl/ordered_map.h b/thirdparty/include/tsl/ordered_map.h deleted file mode 100644 index 1a20ccae0..000000000 --- a/thirdparty/include/tsl/ordered_map.h +++ /dev/null @@ -1,863 +0,0 @@ -/** - * MIT License - * - * Copyright (c) 2017 Thibaut Goetghebuer-Planchon - * - * 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. - */ -#ifndef TSL_ORDERED_MAP_H -#define TSL_ORDERED_MAP_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ordered_hash.h" - - -namespace tsl { - - -/** - * Implementation of an hash map using open addressing with robin hood with backshift delete to resolve collisions. - * - * The particularity of this hash map is that it remembers the order in which the elements were added and - * provide a way to access the structure which stores these values through the 'values_container()' method. - * The used container is defined by ValueTypeContainer, by default a std::deque is used (grows faster) but - * a std::vector may be used. In this case the map provides a 'data()' method which give a direct access - * to the memory used to store the values (which can be useful to communicate with C API's). - * - * The Key and T must be copy constructible and/or move constructible. To use `unordered_erase` they both - * must be swappable. - * - * The behaviour of the hash map is undefined if the destructor of Key or T throws an exception. - * - * By default the maximum size of a map is limited to 2^32 - 1 values, if needed this can be changed through - * the IndexType template parameter. Using an `uint64_t` will raise this limit to 2^64 - 1 values but each - * bucket will use 16 bytes instead of 8 bytes in addition to the space needed to store the values. - * - * Iterators invalidation: - * - clear, operator=, reserve, rehash: always invalidate the iterators (also invalidate end()). - * - insert, emplace, emplace_hint, operator[]: when a std::vector is used as ValueTypeContainer - * and if size() < capacity(), only end(). - * Otherwise all the iterators are invalidated if an insert occurs. - * - erase, unordered_erase: when a std::vector is used as ValueTypeContainer invalidate the iterator of - * the erased element and all the ones after the erased element (including end()). - * Otherwise all the iterators are invalidated if an erase occurs. - */ -template, - class KeyEqual = std::equal_to, - class Allocator = std::allocator>, - class ValueTypeContainer = std::deque, Allocator>, - class IndexType = std::uint_least32_t> -class ordered_map { -private: - template - using has_is_transparent = tsl::detail_ordered_hash::has_is_transparent; - - class KeySelect { - public: - using key_type = Key; - - const key_type& operator()(const std::pair& key_value) const noexcept { - return key_value.first; - } - - key_type& operator()(std::pair& key_value) noexcept { - return key_value.first; - } - }; - - class ValueSelect { - public: - using value_type = T; - - const value_type& operator()(const std::pair& key_value) const noexcept { - return key_value.second; - } - - value_type& operator()(std::pair& key_value) noexcept { - return key_value.second; - } - }; - - using ht = detail_ordered_hash::ordered_hash, KeySelect, ValueSelect, - Hash, KeyEqual, Allocator, ValueTypeContainer, IndexType>; - -public: - using key_type = typename ht::key_type; - using mapped_type = T; - using value_type = typename ht::value_type; - using size_type = typename ht::size_type; - using difference_type = typename ht::difference_type; - using hasher = typename ht::hasher; - using key_equal = typename ht::key_equal; - using allocator_type = typename ht::allocator_type; - using reference = typename ht::reference; - using const_reference = typename ht::const_reference; - using pointer = typename ht::pointer; - using const_pointer = typename ht::const_pointer; - using iterator = typename ht::iterator; - using const_iterator = typename ht::const_iterator; - using reverse_iterator = typename ht::reverse_iterator; - using const_reverse_iterator = typename ht::const_reverse_iterator; - - using values_container_type = typename ht::values_container_type; - - - /* - * Constructors - */ - ordered_map(): ordered_map(ht::DEFAULT_INIT_BUCKETS_SIZE) { - } - - explicit ordered_map(size_type bucket_count, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): - m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR) - { - } - - ordered_map(size_type bucket_count, - const Allocator& alloc): ordered_map(bucket_count, Hash(), KeyEqual(), alloc) - { - } - - ordered_map(size_type bucket_count, - const Hash& hash, - const Allocator& alloc): ordered_map(bucket_count, hash, KeyEqual(), alloc) - { - } - - explicit ordered_map(const Allocator& alloc): ordered_map(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) { - } - - template - ordered_map(InputIt first, InputIt last, - size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): ordered_map(bucket_count, hash, equal, alloc) - { - insert(first, last); - } - - template - ordered_map(InputIt first, InputIt last, - size_type bucket_count, - const Allocator& alloc): ordered_map(first, last, bucket_count, Hash(), KeyEqual(), alloc) - { - } - - template - ordered_map(InputIt first, InputIt last, - size_type bucket_count, - const Hash& hash, - const Allocator& alloc): ordered_map(first, last, bucket_count, hash, KeyEqual(), alloc) - { - } - - ordered_map(std::initializer_list init, - size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): - ordered_map(init.begin(), init.end(), bucket_count, hash, equal, alloc) - { - } - - ordered_map(std::initializer_list init, - size_type bucket_count, - const Allocator& alloc): - ordered_map(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc) - { - } - - ordered_map(std::initializer_list init, - size_type bucket_count, - const Hash& hash, - const Allocator& alloc): - ordered_map(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc) - { - } - - - ordered_map& operator=(std::initializer_list ilist) { - m_ht.clear(); - - m_ht.reserve(ilist.size()); - m_ht.insert(ilist.begin(), ilist.end()); - - return *this; - } - - allocator_type get_allocator() const { return m_ht.get_allocator(); } - - - - /* - * Iterators - */ - iterator begin() noexcept { return m_ht.begin(); } - const_iterator begin() const noexcept { return m_ht.begin(); } - const_iterator cbegin() const noexcept { return m_ht.cbegin(); } - - iterator end() noexcept { return m_ht.end(); } - const_iterator end() const noexcept { return m_ht.end(); } - const_iterator cend() const noexcept { return m_ht.cend(); } - - reverse_iterator rbegin() noexcept { return m_ht.rbegin(); } - const_reverse_iterator rbegin() const noexcept { return m_ht.rbegin(); } - const_reverse_iterator rcbegin() const noexcept { return m_ht.rcbegin(); } - - reverse_iterator rend() noexcept { return m_ht.rend(); } - const_reverse_iterator rend() const noexcept { return m_ht.rend(); } - const_reverse_iterator rcend() const noexcept { return m_ht.rcend(); } - - - /* - * Capacity - */ - bool empty() const noexcept { return m_ht.empty(); } - size_type size() const noexcept { return m_ht.size(); } - size_type max_size() const noexcept { return m_ht.max_size(); } - - /* - * Modifiers - */ - void clear() noexcept { m_ht.clear(); } - - - - std::pair insert(const value_type& value) { return m_ht.insert(value); } - - template::value>::type* = nullptr> - std::pair insert(P&& value) { return m_ht.emplace(std::forward

(value)); } - - std::pair insert(value_type&& value) { return m_ht.insert(std::move(value)); } - - - iterator insert(const_iterator hint, const value_type& value) { - return m_ht.insert_hint(hint, value); - } - - template::value>::type* = nullptr> - iterator insert(const_iterator hint, P&& value) { - return m_ht.emplace_hint(hint, std::forward

(value)); - } - - iterator insert(const_iterator hint, value_type&& value) { - return m_ht.insert_hint(hint, std::move(value)); - } - - - template - void insert(InputIt first, InputIt last) { m_ht.insert(first, last); } - void insert(std::initializer_list ilist) { m_ht.insert(ilist.begin(), ilist.end()); } - - - - - template - std::pair insert_or_assign(const key_type& k, M&& obj) { - return m_ht.insert_or_assign(k, std::forward(obj)); - } - - template - std::pair insert_or_assign(key_type&& k, M&& obj) { - return m_ht.insert_or_assign(std::move(k), std::forward(obj)); - } - - - template - iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj) { - return m_ht.insert_or_assign(hint, k, std::forward(obj)); - } - - template - iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj) { - return m_ht.insert_or_assign(hint, std::move(k), std::forward(obj)); - } - - /** - * Due to the way elements are stored, emplace will need to move or copy the key-value once. - * The method is equivalent to insert(value_type(std::forward(args)...)); - * - * Mainly here for compatibility with the std::unordered_map interface. - */ - template - std::pair emplace(Args&&... args) { return m_ht.emplace(std::forward(args)...); } - - /** - * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once. - * The method is equivalent to insert(hint, value_type(std::forward(args)...)); - * - * Mainly here for compatibility with the std::unordered_map interface. - */ - template - iterator emplace_hint(const_iterator hint, Args&&... args) { - return m_ht.emplace_hint(hint, std::forward(args)...); - } - - - - - template - std::pair try_emplace(const key_type& k, Args&&... args) { - return m_ht.try_emplace(k, std::forward(args)...); - } - - template - std::pair try_emplace(key_type&& k, Args&&... args) { - return m_ht.try_emplace(std::move(k), std::forward(args)...); - } - - template - iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) { - return m_ht.try_emplace_hint(hint, k, std::forward(args)...); - } - - template - iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) { - return m_ht.try_emplace_hint(hint, std::move(k), std::forward(args)...); - } - - - - - /** - * When erasing an element, the insert order will be preserved and no holes will be present in the container - * returned by 'values_container()'. - * - * The method is in O(n), if the order is not important 'unordered_erase(...)' method is faster with an O(1) - * average complexity. - */ - iterator erase(iterator pos) { return m_ht.erase(pos); } - - /** - * @copydoc erase(iterator pos) - */ - iterator erase(const_iterator pos) { return m_ht.erase(pos); } - - /** - * @copydoc erase(iterator pos) - */ - iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); } - - /** - * @copydoc erase(iterator pos) - */ - size_type erase(const key_type& key) { return m_ht.erase(key); } - - /** - * @copydoc erase(iterator pos) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup to the value if you already have the hash. - */ - size_type erase(const key_type& key, std::size_t precalculated_hash) { - return m_ht.erase(key, precalculated_hash); - } - - /** - * @copydoc erase(iterator pos) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type erase(const K& key) { return m_ht.erase(key); } - - /** - * @copydoc erase(const key_type& key, std::size_t precalculated_hash) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type erase(const K& key, std::size_t precalculated_hash) { - return m_ht.erase(key, precalculated_hash); - } - - - - void swap(ordered_map& other) { other.m_ht.swap(m_ht); } - - /* - * Lookup - */ - T& at(const Key& key) { return m_ht.at(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - T& at(const Key& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); } - - - const T& at(const Key& key) const { return m_ht.at(key); } - - /** - * @copydoc at(const Key& key, std::size_t precalculated_hash) - */ - const T& at(const Key& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); } - - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - T& at(const K& key) { return m_ht.at(key); } - - /** - * @copydoc at(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - T& at(const K& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); } - - /** - * @copydoc at(const K& key) - */ - template::value>::type* = nullptr> - const T& at(const K& key) const { return m_ht.at(key); } - - /** - * @copydoc at(const K& key, std::size_t precalculated_hash) - */ - template::value>::type* = nullptr> - const T& at(const K& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); } - - - - T& operator[](const Key& key) { return m_ht[key]; } - T& operator[](Key&& key) { return m_ht[std::move(key)]; } - - - - size_type count(const Key& key) const { return m_ht.count(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - size_type count(const Key& key, std::size_t precalculated_hash) const { - return m_ht.count(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type count(const K& key) const { return m_ht.count(key); } - - /** - * @copydoc count(const K& key) const - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - size_type count(const K& key, std::size_t precalculated_hash) const { - return m_ht.count(key, precalculated_hash); - } - - - - iterator find(const Key& key) { return m_ht.find(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } - - const_iterator find(const Key& key) const { return m_ht.find(key); } - - /** - * @copydoc find(const Key& key, std::size_t precalculated_hash) - */ - const_iterator find(const Key& key, std::size_t precalculated_hash) const { - return m_ht.find(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - iterator find(const K& key) { return m_ht.find(key); } - - /** - * @copydoc find(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } - - /** - * @copydoc find(const K& key) - */ - template::value>::type* = nullptr> - const_iterator find(const K& key) const { return m_ht.find(key); } - - /** - * @copydoc find(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - const_iterator find(const K& key, std::size_t precalculated_hash) const { - return m_ht.find(key, precalculated_hash); - } - - - - bool contains(const Key& key) const { return m_ht.contains(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - bool contains(const Key& key, std::size_t precalculated_hash) const { - return m_ht.contains(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - bool contains(const K& key) const { return m_ht.contains(key); } - - /** - * @copydoc contains(const K& key) const - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - bool contains(const K& key, std::size_t precalculated_hash) const { - return m_ht.contains(key, precalculated_hash); - } - - - - std::pair equal_range(const Key& key) { return m_ht.equal_range(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - std::pair equal_range(const Key& key, std::size_t precalculated_hash) { - return m_ht.equal_range(key, precalculated_hash); - } - - std::pair equal_range(const Key& key) const { return m_ht.equal_range(key); } - - /** - * @copydoc equal_range(const Key& key, std::size_t precalculated_hash) - */ - std::pair equal_range(const Key& key, std::size_t precalculated_hash) const { - return m_ht.equal_range(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key) { return m_ht.equal_range(key); } - - /** - * @copydoc equal_range(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key, std::size_t precalculated_hash) { - return m_ht.equal_range(key, precalculated_hash); - } - - /** - * @copydoc equal_range(const K& key) - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key) const { return m_ht.equal_range(key); } - - /** - * @copydoc equal_range(const K& key, std::size_t precalculated_hash) - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key, std::size_t precalculated_hash) const { - return m_ht.equal_range(key, precalculated_hash); - } - - - - /* - * Bucket interface - */ - size_type bucket_count() const { return m_ht.bucket_count(); } - size_type max_bucket_count() const { return m_ht.max_bucket_count(); } - - - /* - * Hash policy - */ - float load_factor() const { return m_ht.load_factor(); } - float max_load_factor() const { return m_ht.max_load_factor(); } - void max_load_factor(float ml) { m_ht.max_load_factor(ml); } - - void rehash(size_type count) { m_ht.rehash(count); } - void reserve(size_type count) { m_ht.reserve(count); } - - - /* - * Observers - */ - hasher hash_function() const { return m_ht.hash_function(); } - key_equal key_eq() const { return m_ht.key_eq(); } - - - - /* - * Other - */ - - /** - * Convert a const_iterator to an iterator. - */ - iterator mutable_iterator(const_iterator pos) { - return m_ht.mutable_iterator(pos); - } - - /** - * Requires index <= size(). - * - * Return an iterator to the element at index. Return end() if index == size(). - */ - iterator nth(size_type index) { return m_ht.nth(index); } - - /** - * @copydoc nth(size_type index) - */ - const_iterator nth(size_type index) const { return m_ht.nth(index); } - - - /** - * Return const_reference to the first element. Requires the container to not be empty. - */ - const_reference front() const { return m_ht.front(); } - - /** - * Return const_reference to the last element. Requires the container to not be empty. - */ - const_reference back() const { return m_ht.back(); } - - - /** - * Only available if ValueTypeContainer is a std::vector. Same as calling 'values_container().data()'. - */ - template::value>::type* = nullptr> - const typename values_container_type::value_type* data() const noexcept { return m_ht.data(); } - - /** - * Return the container in which the values are stored. The values are in the same order as the insertion order - * and are contiguous in the structure, no holes (size() == values_container().size()). - */ - const values_container_type& values_container() const noexcept { return m_ht.values_container(); } - - template::value>::type* = nullptr> - size_type capacity() const noexcept { return m_ht.capacity(); } - - void shrink_to_fit() { m_ht.shrink_to_fit(); } - - - - /** - * Insert the value before pos shifting all the elements on the right of pos (including pos) one position - * to the right. - * - * Amortized linear time-complexity in the distance between pos and end(). - */ - std::pair insert_at_position(const_iterator pos, const value_type& value) { - return m_ht.insert_at_position(pos, value); - } - - /** - * @copydoc insert_at_position(const_iterator pos, const value_type& value) - */ - std::pair insert_at_position(const_iterator pos, value_type&& value) { - return m_ht.insert_at_position(pos, std::move(value)); - } - - /** - * @copydoc insert_at_position(const_iterator pos, const value_type& value) - * - * Same as insert_at_position(pos, value_type(std::forward(args)...), mainly - * here for coherence. - */ - template - std::pair emplace_at_position(const_iterator pos, Args&&... args) { - return m_ht.emplace_at_position(pos, std::forward(args)...); - } - - /** - * @copydoc insert_at_position(const_iterator pos, const value_type& value) - */ - template - std::pair try_emplace_at_position(const_iterator pos, const key_type& k, Args&&... args) { - return m_ht.try_emplace_at_position(pos, k, std::forward(args)...); - } - - /** - * @copydoc insert_at_position(const_iterator pos, const value_type& value) - */ - template - std::pair try_emplace_at_position(const_iterator pos, key_type&& k, Args&&... args) { - return m_ht.try_emplace_at_position(pos, std::move(k), std::forward(args)...); - } - - - - void pop_back() { m_ht.pop_back(); } - - /** - * Faster erase operation with an O(1) average complexity but it doesn't preserve the insertion order. - * - * If an erasure occurs, the last element of the map will take the place of the erased element. - */ - iterator unordered_erase(iterator pos) { return m_ht.unordered_erase(pos); } - - /** - * @copydoc unordered_erase(iterator pos) - */ - iterator unordered_erase(const_iterator pos) { return m_ht.unordered_erase(pos); } - - /** - * @copydoc unordered_erase(iterator pos) - */ - size_type unordered_erase(const key_type& key) { return m_ht.unordered_erase(key); } - - /** - * @copydoc unordered_erase(iterator pos) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - size_type unordered_erase(const key_type& key, std::size_t precalculated_hash) { - return m_ht.unordered_erase(key, precalculated_hash); - } - - /** - * @copydoc unordered_erase(iterator pos) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type unordered_erase(const K& key) { return m_ht.unordered_erase(key); } - - /** - * @copydoc unordered_erase(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - size_type unordered_erase(const K& key, std::size_t precalculated_hash) { - return m_ht.unordered_erase(key, precalculated_hash); - } - - /** - * Serialize the map through the `serializer` parameter. - * - * The `serializer` parameter must be a function object that supports the following call: - * - `template void operator()(const U& value);` where the types `std::uint64_t`, `float` and `std::pair` must be supported for U. - * - * The implementation leaves binary compatibility (endianness, IEEE 754 for floats, ...) of the types it serializes - * in the hands of the `Serializer` function object if compatibility is required. - */ - template - void serialize(Serializer& serializer) const { - m_ht.serialize(serializer); - } - - /** - * Deserialize a previously serialized map through the `deserializer` parameter. - * - * The `deserializer` parameter must be a function object that supports the following calls: - * - `template U operator()();` where the types `std::uint64_t`, `float` and `std::pair` must be supported for U. - * - * If the deserialized hash map type is hash compatible with the serialized map, the deserialization process can be - * sped up by setting `hash_compatible` to true. To be hash compatible, the Hash and KeyEqual must behave the same way - * than the ones used on the serialized map. The `std::size_t` must also be of the same size as the one on the platform used - * to serialize the map, the same apply for `IndexType`. If these criteria are not met, the behaviour is undefined with - * `hash_compatible` sets to true. - * - * The behaviour is undefined if the type `Key` and `T` of the `ordered_map` are not the same as the - * types used during serialization. - * - * The implementation leaves binary compatibility (endianness, IEEE 754 for floats, size of int, ...) of the types it - * deserializes in the hands of the `Deserializer` function object if compatibility is required. - */ - template - static ordered_map deserialize(Deserializer& deserializer, bool hash_compatible = false) { - ordered_map map(0); - map.m_ht.deserialize(deserializer, hash_compatible); - - return map; - } - - - - friend bool operator==(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht == rhs.m_ht; } - friend bool operator!=(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht != rhs.m_ht; } - friend bool operator<(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht < rhs.m_ht; } - friend bool operator<=(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht <= rhs.m_ht; } - friend bool operator>(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht > rhs.m_ht; } - friend bool operator>=(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht >= rhs.m_ht; } - - friend void swap(ordered_map& lhs, ordered_map& rhs) { lhs.swap(rhs); } - -private: - ht m_ht; -}; - -} // end namespace tsl - -#endif diff --git a/thirdparty/include/tsl/ordered_set.h b/thirdparty/include/tsl/ordered_set.h deleted file mode 100644 index 90a99eee3..000000000 --- a/thirdparty/include/tsl/ordered_set.h +++ /dev/null @@ -1,718 +0,0 @@ -/** - * MIT License - * - * Copyright (c) 2017 Thibaut Goetghebuer-Planchon - * - * 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. - */ -#ifndef TSL_ORDERED_SET_H -#define TSL_ORDERED_SET_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ordered_hash.h" - - -namespace tsl { - - -/** - * Implementation of an hash set using open addressing with robin hood with backshift delete to resolve collisions. - * - * The particularity of this hash set is that it remembers the order in which the elements were added and - * provide a way to access the structure which stores these values through the 'values_container()' method. - * The used container is defined by ValueTypeContainer, by default a std::deque is used (grows faster) but - * a std::vector may be used. In this case the set provides a 'data()' method which give a direct access - * to the memory used to store the values (which can be useful to communicate with C API's). - * - * The Key must be copy constructible and/or move constructible. To use `unordered_erase` it also must be swappable. - * - * The behaviour of the hash set is undefined if the destructor of Key throws an exception. - * - * By default the maximum size of a set is limited to 2^32 - 1 values, if needed this can be changed through - * the IndexType template parameter. Using an `uint64_t` will raise this limit to 2^64 - 1 values but each - * bucket will use 16 bytes instead of 8 bytes in addition to the space needed to store the values. - * - * Iterators invalidation: - * - clear, operator=, reserve, rehash: always invalidate the iterators (also invalidate end()). - * - insert, emplace, emplace_hint, operator[]: when a std::vector is used as ValueTypeContainer - * and if size() < capacity(), only end(). - * Otherwise all the iterators are invalidated if an insert occurs. - * - erase, unordered_erase: when a std::vector is used as ValueTypeContainer invalidate the iterator of - * the erased element and all the ones after the erased element (including end()). - * Otherwise all the iterators are invalidated if an erase occurs. - */ -template, - class KeyEqual = std::equal_to, - class Allocator = std::allocator, - class ValueTypeContainer = std::deque, - class IndexType = std::uint_least32_t> -class ordered_set { -private: - template - using has_is_transparent = tsl::detail_ordered_hash::has_is_transparent; - - class KeySelect { - public: - using key_type = Key; - - const key_type& operator()(const Key& key) const noexcept { - return key; - } - - key_type& operator()(Key& key) noexcept { - return key; - } - }; - - using ht = detail_ordered_hash::ordered_hash; - -public: - using key_type = typename ht::key_type; - using value_type = typename ht::value_type; - using size_type = typename ht::size_type; - using difference_type = typename ht::difference_type; - using hasher = typename ht::hasher; - using key_equal = typename ht::key_equal; - using allocator_type = typename ht::allocator_type; - using reference = typename ht::reference; - using const_reference = typename ht::const_reference; - using pointer = typename ht::pointer; - using const_pointer = typename ht::const_pointer; - using iterator = typename ht::iterator; - using const_iterator = typename ht::const_iterator; - using reverse_iterator = typename ht::reverse_iterator; - using const_reverse_iterator = typename ht::const_reverse_iterator; - - using values_container_type = typename ht::values_container_type; - - - /* - * Constructors - */ - ordered_set(): ordered_set(ht::DEFAULT_INIT_BUCKETS_SIZE) { - } - - explicit ordered_set(size_type bucket_count, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): - m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR) - { - } - - ordered_set(size_type bucket_count, - const Allocator& alloc): ordered_set(bucket_count, Hash(), KeyEqual(), alloc) - { - } - - ordered_set(size_type bucket_count, - const Hash& hash, - const Allocator& alloc): ordered_set(bucket_count, hash, KeyEqual(), alloc) - { - } - - explicit ordered_set(const Allocator& alloc): ordered_set(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) { - } - - template - ordered_set(InputIt first, InputIt last, - size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): ordered_set(bucket_count, hash, equal, alloc) - { - insert(first, last); - } - - template - ordered_set(InputIt first, InputIt last, - size_type bucket_count, - const Allocator& alloc): ordered_set(first, last, bucket_count, Hash(), KeyEqual(), alloc) - { - } - - template - ordered_set(InputIt first, InputIt last, - size_type bucket_count, - const Hash& hash, - const Allocator& alloc): ordered_set(first, last, bucket_count, hash, KeyEqual(), alloc) - { - } - - ordered_set(std::initializer_list init, - size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): - ordered_set(init.begin(), init.end(), bucket_count, hash, equal, alloc) - { - } - - ordered_set(std::initializer_list init, - size_type bucket_count, - const Allocator& alloc): - ordered_set(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc) - { - } - - ordered_set(std::initializer_list init, - size_type bucket_count, - const Hash& hash, - const Allocator& alloc): - ordered_set(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc) - { - } - - - ordered_set& operator=(std::initializer_list ilist) { - m_ht.clear(); - - m_ht.reserve(ilist.size()); - m_ht.insert(ilist.begin(), ilist.end()); - - return *this; - } - - allocator_type get_allocator() const { return m_ht.get_allocator(); } - - - /* - * Iterators - */ - iterator begin() noexcept { return m_ht.begin(); } - const_iterator begin() const noexcept { return m_ht.begin(); } - const_iterator cbegin() const noexcept { return m_ht.cbegin(); } - - iterator end() noexcept { return m_ht.end(); } - const_iterator end() const noexcept { return m_ht.end(); } - const_iterator cend() const noexcept { return m_ht.cend(); } - - reverse_iterator rbegin() noexcept { return m_ht.rbegin(); } - const_reverse_iterator rbegin() const noexcept { return m_ht.rbegin(); } - const_reverse_iterator rcbegin() const noexcept { return m_ht.rcbegin(); } - - reverse_iterator rend() noexcept { return m_ht.rend(); } - const_reverse_iterator rend() const noexcept { return m_ht.rend(); } - const_reverse_iterator rcend() const noexcept { return m_ht.rcend(); } - - - /* - * Capacity - */ - bool empty() const noexcept { return m_ht.empty(); } - size_type size() const noexcept { return m_ht.size(); } - size_type max_size() const noexcept { return m_ht.max_size(); } - - /* - * Modifiers - */ - void clear() noexcept { m_ht.clear(); } - - - - std::pair insert(const value_type& value) { return m_ht.insert(value); } - std::pair insert(value_type&& value) { return m_ht.insert(std::move(value)); } - - iterator insert(const_iterator hint, const value_type& value) { - return m_ht.insert_hint(hint, value); - } - - iterator insert(const_iterator hint, value_type&& value) { - return m_ht.insert_hint(hint, std::move(value)); - } - - template - void insert(InputIt first, InputIt last) { m_ht.insert(first, last); } - void insert(std::initializer_list ilist) { m_ht.insert(ilist.begin(), ilist.end()); } - - - - /** - * Due to the way elements are stored, emplace will need to move or copy the key-value once. - * The method is equivalent to insert(value_type(std::forward(args)...)); - * - * Mainly here for compatibility with the std::unordered_map interface. - */ - template - std::pair emplace(Args&&... args) { return m_ht.emplace(std::forward(args)...); } - - /** - * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once. - * The method is equivalent to insert(hint, value_type(std::forward(args)...)); - * - * Mainly here for compatibility with the std::unordered_map interface. - */ - template - iterator emplace_hint(const_iterator hint, Args&&... args) { - return m_ht.emplace_hint(hint, std::forward(args)...); - } - - /** - * When erasing an element, the insert order will be preserved and no holes will be present in the container - * returned by 'values_container()'. - * - * The method is in O(n), if the order is not important 'unordered_erase(...)' method is faster with an O(1) - * average complexity. - */ - iterator erase(iterator pos) { return m_ht.erase(pos); } - - /** - * @copydoc erase(iterator pos) - */ - iterator erase(const_iterator pos) { return m_ht.erase(pos); } - - /** - * @copydoc erase(iterator pos) - */ - iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); } - - /** - * @copydoc erase(iterator pos) - */ - size_type erase(const key_type& key) { return m_ht.erase(key); } - - /** - * @copydoc erase(iterator pos) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup to the value if you already have the hash. - */ - size_type erase(const key_type& key, std::size_t precalculated_hash) { - return m_ht.erase(key, precalculated_hash); - } - - /** - * @copydoc erase(iterator pos) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type erase(const K& key) { return m_ht.erase(key); } - - /** - * @copydoc erase(const key_type& key, std::size_t precalculated_hash) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type erase(const K& key, std::size_t precalculated_hash) { - return m_ht.erase(key, precalculated_hash); - } - - - - void swap(ordered_set& other) { other.m_ht.swap(m_ht); } - - /* - * Lookup - */ - size_type count(const Key& key) const { return m_ht.count(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - size_type count(const Key& key, std::size_t precalculated_hash) const { - return m_ht.count(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type count(const K& key) const { return m_ht.count(key); } - - /** - * @copydoc count(const K& key) const - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - size_type count(const K& key, std::size_t precalculated_hash) const { - return m_ht.count(key, precalculated_hash); - } - - - - - iterator find(const Key& key) { return m_ht.find(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } - - const_iterator find(const Key& key) const { return m_ht.find(key); } - - /** - * @copydoc find(const Key& key, std::size_t precalculated_hash) - */ - const_iterator find(const Key& key, std::size_t precalculated_hash) const { - return m_ht.find(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - iterator find(const K& key) { return m_ht.find(key); } - - /** - * @copydoc find(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } - - /** - * @copydoc find(const K& key) - */ - template::value>::type* = nullptr> - const_iterator find(const K& key) const { return m_ht.find(key); } - - /** - * @copydoc find(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - const_iterator find(const K& key, std::size_t precalculated_hash) const { - return m_ht.find(key, precalculated_hash); - } - - - - bool contains(const Key& key) const { return m_ht.contains(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - bool contains(const Key& key, std::size_t precalculated_hash) const { - return m_ht.contains(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - bool contains(const K& key) const { return m_ht.contains(key); } - - /** - * @copydoc contains(const K& key) const - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - bool contains(const K& key, std::size_t precalculated_hash) const { - return m_ht.contains(key, precalculated_hash); - } - - - - std::pair equal_range(const Key& key) { return m_ht.equal_range(key); } - - /** - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - std::pair equal_range(const Key& key, std::size_t precalculated_hash) { - return m_ht.equal_range(key, precalculated_hash); - } - - std::pair equal_range(const Key& key) const { return m_ht.equal_range(key); } - - /** - * @copydoc equal_range(const Key& key, std::size_t precalculated_hash) - */ - std::pair equal_range(const Key& key, std::size_t precalculated_hash) const { - return m_ht.equal_range(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key) { return m_ht.equal_range(key); } - - /** - * @copydoc equal_range(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key, std::size_t precalculated_hash) { - return m_ht.equal_range(key, precalculated_hash); - } - - /** - * @copydoc equal_range(const K& key) - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key) const { return m_ht.equal_range(key); } - - /** - * @copydoc equal_range(const K& key, std::size_t precalculated_hash) - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key, std::size_t precalculated_hash) const { - return m_ht.equal_range(key, precalculated_hash); - } - - - /* - * Bucket interface - */ - size_type bucket_count() const { return m_ht.bucket_count(); } - size_type max_bucket_count() const { return m_ht.max_bucket_count(); } - - - /* - * Hash policy - */ - float load_factor() const { return m_ht.load_factor(); } - float max_load_factor() const { return m_ht.max_load_factor(); } - void max_load_factor(float ml) { m_ht.max_load_factor(ml); } - - void rehash(size_type count) { m_ht.rehash(count); } - void reserve(size_type count) { m_ht.reserve(count); } - - - /* - * Observers - */ - hasher hash_function() const { return m_ht.hash_function(); } - key_equal key_eq() const { return m_ht.key_eq(); } - - - /* - * Other - */ - - /** - * Convert a const_iterator to an iterator. - */ - iterator mutable_iterator(const_iterator pos) { - return m_ht.mutable_iterator(pos); - } - - /** - * Requires index <= size(). - * - * Return an iterator to the element at index. Return end() if index == size(). - */ - iterator nth(size_type index) { return m_ht.nth(index); } - - /** - * @copydoc nth(size_type index) - */ - const_iterator nth(size_type index) const { return m_ht.nth(index); } - - - /** - * Return const_reference to the first element. Requires the container to not be empty. - */ - const_reference front() const { return m_ht.front(); } - - /** - * Return const_reference to the last element. Requires the container to not be empty. - */ - const_reference back() const { return m_ht.back(); } - - - /** - * Only available if ValueTypeContainer is a std::vector. Same as calling 'values_container().data()'. - */ - template::value>::type* = nullptr> - const typename values_container_type::value_type* data() const noexcept { return m_ht.data(); } - - /** - * Return the container in which the values are stored. The values are in the same order as the insertion order - * and are contiguous in the structure, no holes (size() == values_container().size()). - */ - const values_container_type& values_container() const noexcept { return m_ht.values_container(); } - - template::value>::type* = nullptr> - size_type capacity() const noexcept { return m_ht.capacity(); } - - void shrink_to_fit() { m_ht.shrink_to_fit(); } - - - - /** - * Insert the value before pos shifting all the elements on the right of pos (including pos) one position - * to the right. - * - * Amortized linear time-complexity in the distance between pos and end(). - */ - std::pair insert_at_position(const_iterator pos, const value_type& value) { - return m_ht.insert_at_position(pos, value); - } - - /** - * @copydoc insert_at_position(const_iterator pos, const value_type& value) - */ - std::pair insert_at_position(const_iterator pos, value_type&& value) { - return m_ht.insert_at_position(pos, std::move(value)); - } - - /** - * @copydoc insert_at_position(const_iterator pos, const value_type& value) - * - * Same as insert_at_position(pos, value_type(std::forward(args)...), mainly - * here for coherence. - */ - template - std::pair emplace_at_position(const_iterator pos, Args&&... args) { - return m_ht.emplace_at_position(pos, std::forward(args)...); - } - - - - void pop_back() { m_ht.pop_back(); } - - /** - * Faster erase operation with an O(1) average complexity but it doesn't preserve the insertion order. - * - * If an erasure occurs, the last element of the map will take the place of the erased element. - */ - iterator unordered_erase(iterator pos) { return m_ht.unordered_erase(pos); } - - /** - * @copydoc unordered_erase(iterator pos) - */ - iterator unordered_erase(const_iterator pos) { return m_ht.unordered_erase(pos); } - - /** - * @copydoc unordered_erase(iterator pos) - */ - size_type unordered_erase(const key_type& key) { return m_ht.unordered_erase(key); } - - /** - * @copydoc unordered_erase(iterator pos) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - size_type unordered_erase(const key_type& key, std::size_t precalculated_hash) { - return m_ht.unordered_erase(key, precalculated_hash); - } - - /** - * @copydoc unordered_erase(iterator pos) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type unordered_erase(const K& key) { return m_ht.unordered_erase(key); } - - /** - * @copydoc unordered_erase(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - size_type unordered_erase(const K& key, std::size_t precalculated_hash) { - return m_ht.unordered_erase(key, precalculated_hash); - } - - /** - * Serialize the set through the `serializer` parameter. - * - * The `serializer` parameter must be a function object that supports the following call: - * - `void operator()(const U& value);` where the types `std::uint64_t`, `float` and `Key` must be supported for U. - * - * The implementation leaves binary compatibility (endianness, IEEE 754 for floats, ...) of the types it serializes - * in the hands of the `Serializer` function object if compatibility is required. - */ - template - void serialize(Serializer& serializer) const { - m_ht.serialize(serializer); - } - - /** - * Deserialize a previously serialized set through the `deserializer` parameter. - * - * The `deserializer` parameter must be a function object that supports the following calls: - * - `template U operator()();` where the types `std::uint64_t`, `float` and `Key` must be supported for U. - * - * If the deserialized hash set type is hash compatible with the serialized set, the deserialization process can be - * sped up by setting `hash_compatible` to true. To be hash compatible, the Hash and KeyEqual must behave the same way - * than the ones used on the serialized map. The `std::size_t` must also be of the same size as the one on the platform used - * to serialize the map, the same apply for `IndexType`. If these criteria are not met, the behaviour is undefined with - * `hash_compatible` sets to true. - * - * The behaviour is undefined if the type `Key` of the `ordered_set` is not the same as the - * type used during serialization. - * - * The implementation leaves binary compatibility (endianness, IEEE 754 for floats, size of int, ...) of the types it - * deserializes in the hands of the `Deserializer` function object if compatibility is required. - */ - template - static ordered_set deserialize(Deserializer& deserializer, bool hash_compatible = false) { - ordered_set set(0); - set.m_ht.deserialize(deserializer, hash_compatible); - - return set; - } - - - - friend bool operator==(const ordered_set& lhs, const ordered_set& rhs) { return lhs.m_ht == rhs.m_ht; } - friend bool operator!=(const ordered_set& lhs, const ordered_set& rhs) { return lhs.m_ht != rhs.m_ht; } - friend bool operator<(const ordered_set& lhs, const ordered_set& rhs) { return lhs.m_ht < rhs.m_ht; } - friend bool operator<=(const ordered_set& lhs, const ordered_set& rhs) { return lhs.m_ht <= rhs.m_ht; } - friend bool operator>(const ordered_set& lhs, const ordered_set& rhs) { return lhs.m_ht > rhs.m_ht; } - friend bool operator>=(const ordered_set& lhs, const ordered_set& rhs) { return lhs.m_ht >= rhs.m_ht; } - - friend void swap(ordered_set& lhs, ordered_set& rhs) { lhs.swap(rhs); } - -private: - ht m_ht; -}; - -} // end namespace tsl - -#endif diff --git a/tools/nzslc.lua b/tools/nzslc.lua deleted file mode 100644 index 7350725d4..000000000 --- a/tools/nzslc.lua +++ /dev/null @@ -1,18 +0,0 @@ -add_requires("cxxopts") - -target("NazaraShaderCompiler") - set_group("Tools") - set_kind("binary") - set_basename("nzslc") - add_rpathdirs("$ORIGIN") - - add_deps("NazaraShader") - add_packages("cxxopts", "fmt") - - if has_config("unitybuild") then - add_rules("c++.unity_build") - end - - add_includedirs("../src") - add_headerfiles("../src/ShaderCompiler/**.hpp", "../src/ShaderCompiler/**.inl") - add_files("../src/ShaderCompiler/**.cpp") diff --git a/tools/shadernodes.lua b/tools/shadernodes.lua index 0208f5eb1..f92726ab8 100644 --- a/tools/shadernodes.lua +++ b/tools/shadernodes.lua @@ -103,7 +103,8 @@ if has_config("shadernodes") then set_kind("binary") add_rules("qt5.moc") - add_deps("NazaraShader") + add_deps("NazaraCore") + add_packages("nzsl") add_packages("nodeeditor") add_packages("qt5core", "qt5gui", "qt5widgets") if not is_plat("windows") then diff --git a/xmake.lua b/xmake.lua index 14eb4fe93..399185d1c 100644 --- a/xmake.lua +++ b/xmake.lua @@ -17,7 +17,8 @@ local modules = { elseif is_plat("linux") then add_syslinks("dl", "pthread", "uuid") end - end + end, + PublicPackages = { "nazarautils" } }, Graphics = { Deps = {"NazaraRenderer"}, @@ -77,19 +78,12 @@ local modules = { end }, Renderer = { - Deps = {"NazaraPlatform", "NazaraShader"} - }, - Shader = { - Deps = {"NazaraCore"}, - Packages = {"efsw", "fmt", "frozen"}, - Custom = function() - -- Set precise floating-points models to ensure shader optimization leads to correct results - set_fpmodels("precise") - end + Deps = {"NazaraPlatform"}, + PublicPackages = { "nazarautils", "nzsl" } }, Utility = { Deps = {"NazaraCore"}, - Packages = {"entt", "freetype", "frozen", "stb"} + Packages = {"entt", "freetype", "frozen", "ordered_map", "stb"} }, VulkanRenderer = { Deps = {"NazaraRenderer"}, @@ -145,12 +139,15 @@ option_end() set_project("NazaraEngine") set_xmakever("2.6.3") -add_requires("chipmunk2d", "dr_wav", "efsw", "entt >=3.9", "fmt", "frozen", "kiwisolver", "libflac", "libsdl", "minimp3", "stb") +add_requires("chipmunk2d", "dr_wav", "efsw", "entt >=3.9", "fmt", "frozen", "kiwisolver", "libflac", "libsdl", "minimp3", "ordered_map", "stb") add_requires("freetype", { configs = { bzip2 = true, png = true, woff2 = true, zlib = true, debug = is_mode("debug") } }) add_requires("libvorbis", { configs = { with_vorbisenc = false } }) add_requires("openal-soft", { configs = { shared = true }}) add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux +add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") +add_requires("nazarautils", "nzsl", { debug = is_mode("debug") }) + if is_plat("macosx") then add_requires("libx11") end @@ -220,6 +217,12 @@ for name, module in pairs(modules) do add_packages(table.unpack(module.Packages)) end + if module.PublicPackages then + for _, pkg in ipairs(module.PublicPackages) do + add_packages(pkg, { public = true }) + end + end + if module.Custom then module.Custom() end @@ -235,6 +238,7 @@ for name, module in pairs(modules) do add_defines("NAZARA_BUILD") add_defines("NAZARA_" .. name:upper() .. "_BUILD") + add_defines("NAZARA_UTILS_WINDOWS_NT6=1") if is_mode("debug") then add_defines("NAZARA_" .. name:upper() .. "_DEBUG") diff --git a/xmake/actions/checkfiles.lua b/xmake/actions/checkfiles.lua index 1c4830a1b..d0ce28904 100644 --- a/xmake/actions/checkfiles.lua +++ b/xmake/actions/checkfiles.lua @@ -486,6 +486,8 @@ on_run(function () order = 1 -- top engine includes elseif inclusions[i].path == "Nazara/" .. debugIncludeModule .. "/Debug.hpp" then order = 6 -- debug include + elseif inclusions[i].path:match("^Nazara/Utils/") then + order = 2.1 -- NazaraUtils elseif inclusions[i].path:match("^Nazara/") then order = 2 -- engine includes elseif IsSystemHeader(inclusions[i].path) then diff --git a/xmake/actions/compile_shaders.lua b/xmake/actions/compile_shaders.lua new file mode 100644 index 000000000..3b179f69f --- /dev/null +++ b/xmake/actions/compile_shaders.lua @@ -0,0 +1,27 @@ +task("compile-shaders") + + set_menu({ + -- Settings menu usage + usage = "xmake compile-shaders [options]", + description = "Compile engine shaders" + }) + + on_run(function () + import("core.project.project") + local nzsl = path.join(project.required_package("nzsl"):installdir(), "bin", "nzslc") + + local envs + if is_plat("mingw") then + local mingw = toolchain.load("mingw") + if mingw and mingw:check() then + envs = mingw:runenvs() + end + end + + print("Compiling shaders...") + for _, filepath in pairs(os.files("src/Nazara/*/Resources/**.nzsl")) do + print(" - Compiling " .. filepath) + local argv = {"--compile=nzslb", "--partial", "--header-file", filepath } + os.execv(nzsl, argv, { envs = envs }) + end + end) diff --git a/xmake/actions/compileshaders.lua b/xmake/actions/compileshaders.lua deleted file mode 100644 index f4a90bba0..000000000 --- a/xmake/actions/compileshaders.lua +++ /dev/null @@ -1,21 +0,0 @@ -task("compile-shaders") - - set_menu({ - -- Settings menu usage - usage = "xmake compile-shaders [options]", - description = "Compile engine shaders" - }) - - on_run(function () - import("core.project.task") - - print("Compiling NZSLC...") - task.run("build", {target = "NazaraShaderCompiler"}) - - print("Compiling shaders...") - for _, filepath in pairs(os.files("src/Nazara/*/Resources/**.nzsl")) do - print(" - Compiling " .. filepath) - local argv = {"--compile", "--partial", "--header-file", path.join("..", "..", filepath) } - task.run("run", {target = "NazaraShaderCompiler", arguments = argv}) - end - end) \ No newline at end of file diff --git a/xmake/actions/generateheaders.lua b/xmake/actions/generateheaders.lua index fb96cda86..9213d6c3c 100644 --- a/xmake/actions/generateheaders.lua +++ b/xmake/actions/generateheaders.lua @@ -74,8 +74,6 @@ on_run(function () paths["Core"].Excludes["ECS.hpp"] = true paths["OpenGLRenderer"].Excludes["Wrapper.hpp"] = true - paths["Shader"].Excludes["ShaderLangErrorList.hpp"] = true - paths["Shader"].Excludes["ShaderLangTokenList.hpp"] = true paths["VulkanRenderer"].Excludes["Wrapper.hpp"] = true -- OpenGL renderer wrapper diff --git a/xmake/actions/spirv.lua b/xmake/actions/spirv.lua index 109138327..d1b9adaa9 100644 --- a/xmake/actions/spirv.lua +++ b/xmake/actions/spirv.lua @@ -84,8 +84,8 @@ on_run(function() #define NAZARA_SHADER_SPIRVDATA_HPP #include -#include -#include +#include +#include namespace Nz { @@ -226,11 +226,11 @@ headerFile:write([[ // this file was automatically generated and should not be edited -#include +#include #include #include #include -#include +#include namespace Nz { diff --git a/xmake/rules/compile_shaders.lua b/xmake/rules/compile_shaders.lua index b03014be1..3230c6e62 100644 --- a/xmake/rules/compile_shaders.lua +++ b/xmake/rules/compile_shaders.lua @@ -1,28 +1,17 @@ -- Compile shaders to includables headers rule("compile_shaders") on_load(function (target) - target:add("deps", "NazaraShaderCompiler") - target:set("policy", "build.across_targets_in_parallel", false) + target:add("packages", "nzsl") end) - -- temporary fix - before_build("mingw", function (target) - local mingw = target:toolchain("mingw") - local bindir = mingw:bindir() - local targetdir = target:targetdir() - if bindir then - os.trycp(path.join(bindir, "libgcc_s_seh-1.dll"), targetdir) - os.trycp(path.join(bindir, "libstdc++-6.dll"), targetdir) - os.trycp(path.join(bindir, "libwinpthread-1.dll"), targetdir) - end - end) - before_buildcmd_file(function (target, batchcmds, shaderfile, opt) - local nzslc = target:dep("NazaraShaderCompiler") + import("core.tool.toolchain") + + local nzsl = path.join(target:pkg("nzsl"):installdir(), "bin", "nzslc") -- add commands batchcmds:show_progress(opt.progress, "${color.build.object}compiling shader %s", shaderfile) - local argv = {"--compile", "--partial", "--header-file"} + local argv = {"--compile=nzslb", "--partial", "--header-file"} -- handle --log-format local kind = target:data("plugin.project.kind") or "" @@ -32,7 +21,15 @@ rule("compile_shaders") table.insert(argv, shaderfile) - batchcmds:vrunv(nzslc:targetfile(), argv, { curdir = "." }) + local envs + if is_plat("mingw") then + local mingw = toolchain.load("mingw") + if mingw and mingw:check() then + envs = mingw:runenvs() + end + end + + batchcmds:vrunv(nzsl, argv, { curdir = ".", envs = envs }) local outputFile = path.join(path.directory(shaderfile), path.basename(shaderfile) .. ".nzslb.h")