From 99fbedab02891d5d55007b54c1a8010e8f074771 Mon Sep 17 00:00:00 2001 From: Baplar Date: Sat, 12 Apr 2025 01:11:47 +0200 Subject: [PATCH] Client-side post-processing - Snapdragon Game Super Resolution --- .github/screenshot-script.txt | 11 ++ .gitignore | 1 + assets/licenses/SGSR | 32 ++++ client/configuration.cpp | 40 ++++- client/configuration.h | 14 ++ client/scenes/lobby.h | 2 + client/scenes/lobby_gui.cpp | 111 ++++++++++++- client/scenes/stream.cpp | 13 +- client/scenes/stream_reprojection.cpp | 76 +++++++-- client/shaders/reprojection.glsl | 22 +-- client/shaders/reprojection_sgsr.frag.glsl | 179 +++++++++++++++++++++ 11 files changed, 468 insertions(+), 33 deletions(-) create mode 100644 assets/licenses/SGSR create mode 100644 client/shaders/reprojection_sgsr.frag.glsl diff --git a/.github/screenshot-script.txt b/.github/screenshot-script.txt index bc0c8c1c..c92bb887 100644 --- a/.github/screenshot-script.txt +++ b/.github/screenshot-script.txt @@ -82,6 +82,17 @@ set right rotation 0.4 0 0 0.9 sleep 1 exec grim -g "0,0 2560x1440" ${LANG}/screenshot-04-settings.png +# Post-processing +set right direction -1.95 1.45 -1 +sleep 1 +set right trigger_value 1 +sleep 1 +set right trigger_value 0 +sleep 1 +set right rotation 0.4 0 0 0.9 +sleep 1 +exec grim -g "0,0 2560x1440" ${LANG}/screenshot-07-post-processing.png + # About set right direction -2.4 0.45 -1 sleep 1 diff --git a/.gitignore b/.gitignore index c52ec680..b2fae216 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .cache/ .gradle/ _deps/ +.idea/ build/ build-*/ diff --git a/assets/licenses/SGSR b/assets/licenses/SGSR new file mode 100644 index 00000000..9055a3a0 --- /dev/null +++ b/assets/licenses/SGSR @@ -0,0 +1,32 @@ +Snapdragon™ Game Super Resolution +Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved. + +https://github.com/SnapdragonStudios/snapdragon-gsr + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +SPDX-License-Identifier: BSD-3-Clause diff --git a/client/configuration.cpp b/client/configuration.cpp index cfa8b436..bbfe0839 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -18,12 +18,10 @@ */ #include "configuration.h" - #include "application.h" -#include "hardware.h" + #include #include -#include #ifdef __ANDROID__ #include "android/permissions.h" @@ -188,6 +186,9 @@ configuration::configuration(xr::system & system) if (auto val = root["resolution_scale"]; val.is_double()) resolution_scale = val.get_double(); + if (auto val = root["sgsr"]; val.is_object()) + parse_sgsr_options(val.get_object()); + if (auto val = root["passthrough_enabled"]; val.is_bool()) passthrough_enabled = val.get_bool(); @@ -215,16 +216,47 @@ configuration::configuration(xr::system & system) preferred_refresh_rate.reset(); minimum_refresh_rate.reset(); resolution_scale = 1.4; + sgsr = {}; show_performance_metrics = false; passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color; } } +void configuration::parse_sgsr_options(simdjson::simdjson_result sgsr_root) +{ + sgsr = {}; + if (auto val = sgsr_root["enabled"]; val.is_bool()) + sgsr.enabled = val.get_bool(); + + if (auto val = sgsr_root["upscaling_factor"]; val.is_double()) + sgsr.upscaling_factor = val.get_double(); + + if (auto val = sgsr_root["use_edge_direction"]; val.is_bool()) + sgsr.use_edge_direction = val.get_bool(); + + if (auto val = sgsr_root["edge_threshold"]; val.is_double()) + sgsr.edge_threshold = val.get_double(); + + if (auto val = sgsr_root["edge_sharpness"]; val.is_double()) + sgsr.edge_sharpness = val.get_double(); +} + static std::ostream & operator<<(std::ostream & stream, feature f) { return stream << "\"" << magic_enum::enum_name(f) << "\""; } +static std::ostream & write_sgsr(std::ofstream & stream, const configuration::sgsr_settings & sgsr) +{ + stream << "{\"enabled\":" << std::boolalpha << sgsr.enabled; + stream << ",\"upscaling_factor\":" << sgsr.upscaling_factor; + stream << ",\"use_edge_direction\":" << std::boolalpha << sgsr.use_edge_direction; + stream << ",\"edge_threshold\":" << sgsr.edge_threshold; + stream << ",\"edge_sharpness\":" << sgsr.edge_sharpness; + stream << "}"; + return stream; +} + void configuration::save() { std::lock_guard lock(mutex); @@ -260,6 +292,8 @@ void configuration::save() if (minimum_refresh_rate) json << ",\"minimum_refresh_rate\":" << *minimum_refresh_rate; json << ",\"resolution_scale\":" << resolution_scale; + json << ",\"sgsr\":"; + write_sgsr(json, sgsr); json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled; json << ",\"mic_unprocessed_audio\":" << std::boolalpha << mic_unprocessed_audio; for (auto & [key, value]: features) diff --git a/client/configuration.h b/client/configuration.h index 43e34db4..03a61808 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace xr @@ -53,6 +54,17 @@ public: bool passthrough_enabled = false; bool mic_unprocessed_audio = false; + // Snapdragon Game Super Resolution + struct sgsr_settings + { + bool enabled = false; + float upscaling_factor = 1.5; + bool use_edge_direction = true; + float edge_threshold = 4.0; + float edge_sharpness = 2.0; + }; + sgsr_settings sgsr{}; + std::string virtual_keyboard_layout = "QWERTY"; bool check_feature(feature f) const; @@ -62,6 +74,8 @@ private: mutable std::mutex mutex; std::map features; + void parse_sgsr_options(simdjson::simdjson_result root); + public: configuration(xr::system &); diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index c5fd1878..284e0d55 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -118,6 +118,7 @@ class lobby : public scene_impl { server_list, settings, + post_processing, #if WIVRN_CLIENT_DEBUG_MENU debug, #endif @@ -148,6 +149,7 @@ class lobby : public scene_impl void gui_server_list(); void gui_new_server(); void gui_settings(); + void gui_post_processing(); void gui_debug(); void gui_about(); void gui_licenses(); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index fd576e00..647326f8 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -145,8 +145,16 @@ void scenes::lobby::tooltip(std::string_view text) const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true); const ImVec2 size = {text_size.x + style.WindowPadding.x * 2.0f, text_size.y + style.WindowPadding.y * 2.0f}; pos.x = std::min(pos.x, viewport->Pos.x + viewport->Size.x - size.x / 2); + ImVec2 pivot = {0.5, 1}; - ImGui::SetNextWindowPos(pos, ImGuiCond_Always, {0.5, 1}); + // Move tooltip below the item if it overflows on the top + if (pos.y - size.y <= viewport->Pos.y) + { + pos.y = ImGui::GetItemRectMax().y + constants::style::tooltip_distance; + pivot.y = 0; + } + + ImGui::SetNextWindowPos(pos, ImGuiCond_Always, pivot); if (ImGui::BeginTooltip()) { ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff); @@ -635,7 +643,13 @@ void scenes::lobby::gui_settings() const auto width = stream_view.recommendedImageRectWidth; const auto height = stream_view.recommendedImageRectHeight; auto intScale = int(current * 100); - if (ImGui::SliderInt(_S("Resolution scale"), &intScale, 50, 350, fmt::format(_F("%d%% - {}x{} per eye"), int(width * current), int(height * current)).c_str())) + const auto slider = ImGui::SliderInt( + _("Resolution scale").append("##resolution_scale").c_str(), + &intScale, + 50, + 350, + fmt::format(_F("%d%% - {}x{} per eye"), int(width * current), int(height * current)).c_str()); + if (slider) { config.resolution_scale = intScale * 0.01; config.save(); @@ -785,6 +799,90 @@ void scenes::lobby::gui_settings() } } +void scenes::lobby::gui_post_processing() +{ + auto & config = application::get_config(); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20, 20)); + + { + // SGSR + { + if (ImGui::Checkbox(_S("Enable Snapdragon Game Super Resolution"), &config.sgsr.enabled)) + { + config.save(); + } + vibrate_on_hover(); + if (ImGui::IsItemHovered()) + { + tooltip(_("Client-side upscaling and sharpening, adds a performance cost on the headset")); + } + } + + { + ImGui::BeginDisabled(not config.sgsr.enabled); + ImGui::Indent(); + { + const auto current = config.sgsr.upscaling_factor; + const auto width = stream_view.recommendedImageRectWidth * config.resolution_scale; + const auto height = stream_view.recommendedImageRectHeight * config.resolution_scale; + auto intScale = int(current * 100); + const auto slider = ImGui::SliderInt( + _("Upscaling factor").append("##upscaling_factor").c_str(), + &intScale, + 100, + 200, + fmt::format(_F("%d%% - {}x{} per eye"), int(width * current), int(height * current)).c_str()); + if (slider) + { + config.sgsr.upscaling_factor = intScale * 0.01; + config.save(); + } + vibrate_on_hover(); + if (width * current > stream_view.maxImageRectWidth or height * current > stream_view.maxImageRectHeight) + { + ImGui::TextColored(ImColor(0xf9, 0x73, 0x06) /*orange*/, ICON_FA_TRIANGLE_EXCLAMATION); + ImGui::SameLine(); + ImGui::Text("%s", fmt::format(_F("Resolution larger than {}x{} may not be supported by the headset"), stream_view.maxImageRectWidth, stream_view.maxImageRectHeight).c_str()); + } + } + { + if (ImGui::Checkbox(_S("Use edge direction"), &config.sgsr.use_edge_direction)) + { + config.save(); + } + vibrate_on_hover(); + if (ImGui::IsItemHovered()) + tooltip(_("Adds an additional performance cost")); + } + { + const float current = config.sgsr.edge_threshold; + int intScale = int(current); + if (ImGui::SliderInt(_S("Edge threshold"), &intScale, 1, 16, "%d.0")) + { + config.sgsr.edge_threshold = float(intScale); + config.save(); + } + vibrate_on_hover(); + if (ImGui::IsItemHovered()) + tooltip(fmt::format(_F("Recommended: {:.1f}"), 4.0)); + } + { + if (ImGui::SliderFloat(_S("Edge sharpness"), &config.sgsr.edge_sharpness, 1.0, 2.0, "%.2f")) + { + config.save(); + } + vibrate_on_hover(); + if (ImGui::IsItemHovered()) + tooltip(fmt::format(_F("Recommended: {:.1f}"), 2.0)); + } + ImGui::Unindent(); + ImGui::EndDisabled(); + } + } + ImGui::PopStyleVar(); +} + #if WIVRN_CLIENT_DEBUG_MENU void scenes::lobby::gui_debug() { @@ -867,7 +965,7 @@ void scenes::lobby::gui_licenses() ImGui::Text("%s", _("Licenses").c_str()); ImGui::PopFont(); - const auto components = {"WiVRn", "FontAwesome", "openxr-loader", "simdjson"}; + const auto components = {"WiVRn", "FontAwesome", "openxr-loader", "simdjson", "SGSR"}; if (not license) { selected_item = *components.begin(); @@ -1450,6 +1548,10 @@ std::vector> scenes::lobby::draw_gui(XrTi gui_settings(); break; + case tab::post_processing: + gui_post_processing(); + break; + #if WIVRN_CLIENT_DEBUG_MENU case tab::debug: gui_debug(); @@ -1494,6 +1596,9 @@ std::vector> scenes::lobby::draw_gui(XrTi RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), ¤t_tab, tab::settings, {TabWidth, 0}); vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_WAND_MAGIC_SPARKLES " " + _("Post-processing"), ¤t_tab, tab::post_processing, {TabWidth, 0}); + vibrate_on_hover(); + #if WIVRN_CLIENT_DEBUG_MENU RadioButtonWithoutCheckBox(ICON_FA_BUG_SLASH " " + _("Debug"), ¤t_tab, tab::debug, {TabWidth, 0}); vibrate_on_hover(); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 99f041c5..66906355 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -1148,8 +1148,17 @@ void scenes::stream::setup_reprojection_swapchain() const uint32_t video_width = video_stream_description->width / view_count; const uint32_t video_height = video_stream_description->height; - const uint32_t swapchain_width = video_width / video_stream_description->foveation[0].x.scale; - const uint32_t swapchain_height = video_height / video_stream_description->foveation[0].y.scale; + uint32_t swapchain_width = video_width / video_stream_description->foveation[0].x.scale; + uint32_t swapchain_height = video_height / video_stream_description->foveation[0].y.scale; + + const configuration::sgsr_settings sgsr = application::get_config().sgsr; + if (sgsr.enabled) + { + const float upscaling_factor = sgsr.upscaling_factor; + spdlog::info("Using SGSR with an upscale factor of {}", upscaling_factor); + swapchain_width *= upscaling_factor; + swapchain_height *= upscaling_factor; + } auto views = system.view_configuration_views(viewconfig); diff --git a/client/scenes/stream_reprojection.cpp b/client/scenes/stream_reprojection.cpp index eac0cdb9..563b7ea2 100644 --- a/client/scenes/stream_reprojection.cpp +++ b/client/scenes/stream_reprojection.cpp @@ -45,6 +45,13 @@ struct uniform const int nb_reprojection_vertices = 128; +struct SgsrSpecializationConstants +{ + VkBool32 use_edge_direction; + float edge_threshold; + float edge_sharpness; +}; + stream_reprojection::stream_reprojection( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, @@ -238,23 +245,17 @@ stream_reprojection::stream_reprojection( renderpass = vk::raii::RenderPass(device, renderpass_info.get()); - // Create graphics pipeline + // Vertex shader vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert"); - vk::raii::ShaderModule fragment_shader = load_shader(device, "reprojection.frag"); - vk::PipelineLayoutCreateInfo pipeline_layout_info; - pipeline_layout_info.setSetLayouts(*descriptor_set_layout); - - layout = vk::raii::PipelineLayout(device, pipeline_layout_info); - - int specialization_constants[] = { + int vertex_specialization_constants[] = { foveation_parameters[0].x.scale < 1, foveation_parameters[0].y.scale < 1, nb_reprojection_vertices, nb_reprojection_vertices, }; - std::array specialization_constants_desc{ + std::array vertex_specialization_constants_desc{ vk::SpecializationMapEntry{ .constantID = 0, .offset = 0, @@ -277,10 +278,57 @@ stream_reprojection::stream_reprojection( }, }; - vk::SpecializationInfo specialization_info; + vk::SpecializationInfo vertex_specialization_info; + vertex_specialization_info.setMapEntries(vertex_specialization_constants_desc); + vertex_specialization_info.setData(vertex_specialization_constants); - specialization_info.setMapEntries(specialization_constants_desc); - specialization_info.setData(specialization_constants); + // Fragment shader + std::string fragment_shader_name = "reprojection.frag"; + + vk::SpecializationInfo fragment_specialization_info; + SgsrSpecializationConstants fragment_specialization_constants; + std::vector fragment_specialization_constants_desc; + const configuration::sgsr_settings sgsr = application::get_config().sgsr; + if (sgsr.enabled) + { + fragment_shader_name = "reprojection_sgsr.frag"; + + fragment_specialization_constants = { + .use_edge_direction = sgsr.use_edge_direction, + .edge_threshold = float(sgsr.edge_threshold / 255.0), + .edge_sharpness = sgsr.edge_sharpness, + }; + + fragment_specialization_constants_desc = { + vk::SpecializationMapEntry{ + .constantID = 0, + .offset = offsetof(SgsrSpecializationConstants, use_edge_direction), + .size = sizeof(fragment_specialization_constants.use_edge_direction), + }, + vk::SpecializationMapEntry{ + .constantID = 1, + .offset = offsetof(SgsrSpecializationConstants, edge_threshold), + .size = sizeof(fragment_specialization_constants.edge_threshold), + }, + vk::SpecializationMapEntry{ + .constantID = 2, + .offset = offsetof(SgsrSpecializationConstants, edge_sharpness), + .size = sizeof(fragment_specialization_constants.edge_sharpness), + }, + }; + + fragment_specialization_info.setMapEntries(fragment_specialization_constants_desc); + fragment_specialization_info.setDataSize(sizeof(fragment_specialization_constants)); + fragment_specialization_info.setPData(&fragment_specialization_constants); + } + + vk::raii::ShaderModule fragment_shader = load_shader(device, fragment_shader_name); + + // Create graphics pipeline + vk::PipelineLayoutCreateInfo pipeline_layout_info; + pipeline_layout_info.setSetLayouts(*descriptor_set_layout); + + layout = vk::raii::PipelineLayout(device, pipeline_layout_info); vk::pipeline_builder pipeline_info{ .flags = {}, @@ -289,13 +337,13 @@ stream_reprojection::stream_reprojection( .stage = vk::ShaderStageFlagBits::eVertex, .module = *vertex_shader, .pName = "main", - .pSpecializationInfo = &specialization_info, + .pSpecializationInfo = &vertex_specialization_info, }, { .stage = vk::ShaderStageFlagBits::eFragment, .module = *fragment_shader, .pName = "main", - .pSpecializationInfo = &specialization_info, + .pSpecializationInfo = &fragment_specialization_info, }, }, .VertexBindingDescriptions = {}, diff --git a/client/shaders/reprojection.glsl b/client/shaders/reprojection.glsl index f143af10..6ab6dbda 100644 --- a/client/shaders/reprojection.glsl +++ b/client/shaders/reprojection.glsl @@ -19,6 +19,8 @@ #version 450 +#ifdef VERT_SHADER + layout (constant_id = 0) const bool use_foveation_x = false; layout (constant_id = 1) const bool use_foveation_y = false; layout (constant_id = 2) const int nb_x = 64; @@ -33,6 +35,12 @@ layout(set = 0, binding = 1) uniform UniformBufferObject } ubo; +layout(location = 0) out vec2 outUV; + +vec2 positions[6] = vec2[]( + vec2(0, 0), vec2(1, 0), vec2(0, 1), + vec2(1, 0), vec2(0, 1), vec2(1, 1)); + vec2 unfoveate(vec2 uv) { uv = 2 * uv - 1; @@ -54,14 +62,6 @@ vec2 unfoveate(vec2 uv) return uv; } -#ifdef VERT_SHADER - -vec2 positions[6] = vec2[]( - vec2(0, 0), vec2(1, 0), vec2(0, 1), - vec2(1, 0), vec2(0, 1), vec2(1, 1)); - -layout(location = 0) out vec2 outUV; - void main() { vec2 quad_size = 1 / vec2(nb_x, nb_y); @@ -75,6 +75,7 @@ void main() #endif #ifdef FRAG_SHADER + layout(set = 0, binding = 0) uniform sampler2D texSampler; layout(location = 0) in vec2 inUV; @@ -83,8 +84,7 @@ layout(location = 0) out vec4 outColor; void main() { - outColor = texture(texSampler, inUV).rgba; - + outColor = texture(texSampler, inUV).rgba; } -#endif +#endif diff --git a/client/shaders/reprojection_sgsr.frag.glsl b/client/shaders/reprojection_sgsr.frag.glsl new file mode 100644 index 00000000..80bebdad --- /dev/null +++ b/client/shaders/reprojection_sgsr.frag.glsl @@ -0,0 +1,179 @@ +/* + * Snapdragon™ Game Super Resolution + * Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved. + * + * https://github.com/SnapdragonStudios/snapdragon-gsr + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#version 450 + +precision mediump float; +precision highp int; + +#define OperationMode 1 + +layout (constant_id = 0) const bool use_edge_direction = true; +layout (constant_id = 1) const float edge_threshold = 4.0/255.0; +layout (constant_id = 2) const float edge_sharpness = 2.0; + +layout(set = 0, binding = 0) uniform mediump sampler2D texSampler; + +layout(location = 0) in highp vec2 inUV; + +layout(location = 0) out vec4 outColor; + +float fastLanczos2(float x) +{ + float wA = x-4.0; + float wB = x*wA-wA; + wA *= wA; + return wB*wA; +} + +vec2 weightY(float dx, float dy, float c, vec3 data) +{ + float std = data.x; + vec2 dir = data.yz; + + float edgeDis = ((dx*dir.y)+(dy*dir.x)); + float x = (((dx*dx)+(dy*dy))+((edgeDis*edgeDis)*((clamp(((c*c)*std),0.0,1.0)*0.7)+-1.0))); + + float w = fastLanczos2(x); + return vec2(w, w * c); +} + +vec2 weightYned(float dx, float dy, float c, float std) +{ + float x = ((dx*dx)+(dy* dy))* 0.55 + clamp(abs(c)*std, 0.0, 1.0); + + float w = fastLanczos2(x); + return vec2(w, w * c); +} + +vec2 edgeDirection(vec4 left, vec4 right) +{ + vec2 dir; + float RxLz = (right.x + (-left.z)); + float RwLy = (right.w + (-left.y)); + vec2 delta; + delta.x = (RxLz + RwLy); + delta.y = (RxLz + (-RwLy)); + float lengthInv = inversesqrt((delta.x * delta.x+ 3.075740e-05) + (delta.y * delta.y)); + dir.x = (delta.x * lengthInv); + dir.y = (delta.y * lengthInv); + return dir; +} + +void main() +{ + vec4 color = textureLod(texSampler,inUV,0.0).xyzw; + float alpha = color.a; + + if (OperationMode == 1) + color.a = 0.0; + + if (OperationMode != 4) + { + vec2 dim = textureSize(texSampler, 0); + vec4 viewportInfo = vec4(1/dim.x, 1/dim.y, dim.x, dim.y); + + highp vec2 imgCoord = ((inUV.xy*viewportInfo.zw)+vec2(-0.5,0.5)); + highp vec2 imgCoordPixel = floor(imgCoord); + highp vec2 coord = (imgCoordPixel*viewportInfo.xy); + vec2 pl = (imgCoord+(-imgCoordPixel)); + vec4 left = textureGather(texSampler,coord, OperationMode); + + float edgeVote = abs(left.z - left.y) + abs(color[OperationMode] - left.y) + abs(color[OperationMode] - left.z) ; + if(edgeVote > edge_threshold) + { + coord.x += viewportInfo.x; + + vec4 right = textureGather(texSampler,coord + vec2(viewportInfo.x, 0.0), OperationMode); + vec4 upDown; + upDown.xy = textureGather(texSampler,coord + vec2(0.0, -viewportInfo.y),OperationMode).wz; + upDown.zw = textureGather(texSampler,coord + vec2(0.0, viewportInfo.y), OperationMode).yx; + + float mean = (left.y+left.z+right.x+right.w)*0.25; + left = left - vec4(mean); + right = right - vec4(mean); + upDown = upDown - vec4(mean); + color.w =color[OperationMode] - mean; + + float sum = (((((abs(left.x)+abs(left.y))+abs(left.z))+abs(left.w))+(((abs(right.x)+abs(right.y))+abs(right.z))+abs(right.w)))+(((abs(upDown.x)+abs(upDown.y))+abs(upDown.z))+abs(upDown.w))); + float sumMean = 1.014185e+01/sum; + float std = (sumMean*sumMean); + + vec2 aWY; + if (use_edge_direction) { + vec3 data = vec3(std, edgeDirection(left, right)); + aWY = weightY(pl.x, pl.y+1.0, upDown.x,data); + aWY += weightY(pl.x-1.0, pl.y+1.0, upDown.y,data); + aWY += weightY(pl.x-1.0, pl.y-2.0, upDown.z,data); + aWY += weightY(pl.x, pl.y-2.0, upDown.w,data); + aWY += weightY(pl.x+1.0, pl.y-1.0, left.x,data); + aWY += weightY(pl.x, pl.y-1.0, left.y,data); + aWY += weightY(pl.x, pl.y, left.z,data); + aWY += weightY(pl.x+1.0, pl.y, left.w,data); + aWY += weightY(pl.x-1.0, pl.y-1.0, right.x,data); + aWY += weightY(pl.x-2.0, pl.y-1.0, right.y,data); + aWY += weightY(pl.x-2.0, pl.y, right.z,data); + aWY += weightY(pl.x-1.0, pl.y, right.w,data); + } else { + aWY = weightYned(pl.x, pl.y+1.0, upDown.x,std); + aWY += weightYned(pl.x-1.0, pl.y+1.0, upDown.y,std); + aWY += weightYned(pl.x-1.0, pl.y-2.0, upDown.z,std); + aWY += weightYned(pl.x, pl.y-2.0, upDown.w,std); + aWY += weightYned(pl.x+1.0, pl.y-1.0, left.x,std); + aWY += weightYned(pl.x, pl.y-1.0, left.y,std); + aWY += weightYned(pl.x, pl.y, left.z,std); + aWY += weightYned(pl.x+1.0, pl.y, left.w,std); + aWY += weightYned(pl.x-1.0, pl.y-1.0, right.x,std); + aWY += weightYned(pl.x-2.0, pl.y-1.0, right.y,std); + aWY += weightYned(pl.x-2.0, pl.y, right.z,std); + aWY += weightYned(pl.x-1.0, pl.y, right.w,std); + } + + float finalY = aWY.y/aWY.x; + float maxY = max(max(left.y,left.z),max(right.x,right.w)); + float minY = min(min(left.y,left.z),min(right.x,right.w)); + float deltaY = clamp(edge_sharpness*finalY, minY, maxY) -color.w; + + //smooth high contrast input + deltaY = clamp(deltaY, -23.0 / 255.0, 23.0 / 255.0); + + color.x = clamp((color.x+deltaY),0.0,1.0); + color.y = clamp((color.y+deltaY),0.0,1.0); + color.z = clamp((color.z+deltaY),0.0,1.0); + } + } + + outColor = vec4(color.rgb, alpha); +}