diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 2ae197ce..00000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,105 +0,0 @@ -version: 2.0 - -jobs: - build: - branches: - ignore: - - /docs-*/ - - /do-not-run-ci-*/ - - /only-appveyor-ci-*/ - - /only-travis-ci-*/ - environment: - QMAKE_SPEC: linux-g++ - QT_SELECT: opt-qt512 - MAKE_JOBS: 2 - docker: - - image: circleci/buildpack-deps:xenial - steps: - - checkout - - run: sudo apt-get update && sudo apt-get upgrade -y - - run: - name: Get apt-key - # Required for LLVM - command: | - sudo apt-get install software-properties-common apt-transport-https -y - - run: - name: Get LLVM repos - command: | - wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - - sudo add-apt-repository 'deb http://apt.llvm.org/xenial/ llvm-toolchain-xenial-8 main' - sudo add-apt-repository 'deb http://apt.llvm.org/xenial/ llvm-toolchain-xenial-7 main' - sudo apt-get update -qq - #- run: - # name: Install LLVM-8 binaries - # # clang is required due to a check by Qmake. - # # clang-tidy-8 has new errors compared to clang-tidy-7, so we haven't upgraded. - # command: | - # sudo apt-get install clang-format-8 -y - # sudo apt-get install clang-tidy-7 -y - # sudo apt-get install clang-8 -y - # sudo apt-get install clang -y - #- run: - # name: Run clang-format - # command: python ./build_scripts/run-clang-format.py ./src -r --color always --clang-format-executable clang-format-8 - - run: - name: Install g++ - command: | - sudo add-apt-repository ppa:ubuntu-toolchain-r/test - sudo apt-get update - sudo apt-get install g++-7 -y - - run: - name: Add required QT repos - command: | - sudo add-apt-repository ppa:beineri/opt-qt-5.12.2-xenial -y - sudo apt-get update -qq - - run: sudo apt-get install build-essential libgl1-mesa-dev -y - - run: - name: Install QT packages - command: | - sudo apt-get install qt512-meta-minimal qt512multimedia qt512declarative qt512quickcontrols2 qt512quickcontrols qt512tools qt512imageformats qt512svg qt512base qtchooser qt512websockets -y - - run: - name: Install X11 packages - command: sudo apt-get install libx11-dev libxt-dev libxtst-dev -y - - run: - name: Install pulse packages - command: sudo apt-get install libpulse-dev -y - - run: - name: Install bear/clang-tidy - command: sudo apt-get install bear clang-tidy -y - - run: - name: Install SDL libs - command: sudo apt-get install libsdl2-2.0-0 -y - - run: - name: Set up qtchooser - command: qtchooser -install opt-qt512 /opt/qt512/bin/qmake - - run: - name: Give build scripts +x - command: | - chmod +x ./build_scripts/linux/build_linux.sh - chmod +x ./build_scripts/linux/format.sh - chmod +x ./build_scripts/linux/run-clang-tidy.sh - chmod +x ./build_scripts/linux/verify_formatting.sh - - run: - name: Update version number - command: | - python ./build_scripts/append_to_version_file.py $(git rev-parse HEAD | cut -c -8) - cat ./build_scripts/compile_version_string.txt - - run: - name: Run build script - command: ./build_scripts/linux/build_linux.sh - - run: - name: Get qtdeploylinux - command: | - wget -c -nv https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage - chmod a+x ./linuxdeployqt-continuous-x86_64.AppImage - - run: - name: Create AppImage - command: ./build_scripts/linux/appimage.sh - - run: - name: Copy Artifacts - command: | - mkdir artifacts - cp -v ./OpenVR_Advanced_Settings-*.AppImage ./artifacts/ - - store_artifacts: - path: ./artifacts/ - diff --git a/.clang-format b/.clang-format index b0ce293d..ee2c752a 100644 --- a/.clang-format +++ b/.clang-format @@ -19,7 +19,7 @@ AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: false BinPackParameters: false -BraceWrapping: +BraceWrapping: AfterClass: true AfterControlStatement: true AfterEnum: true @@ -54,12 +54,12 @@ DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true -ForEachMacros: +ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IncludeBlocks: Preserve -IncludeCategories: +IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 1 - Regex: '^(<|"(gtest|gmock|isl|json)/)' diff --git a/.clang-tidy b/.clang-tidy index 4cfd0a75..fa786c72 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,19 @@ --- -Checks: '*, +# TODO: Contemplate: -bugprone-branch-clone,-cppcoreguidelines-avoid-non-const-global-variables,-cppcoreguidelines-avoid-magic-numbers, +# -hicpp-uppercase-literal-suffix,-misc-include-cleaner,-modernize-use-trailing-return-type,-readability-function-cognitive-complexity, +# -readability-uppercase-literal-suffix, -cppcoreguidelines-avoid-do-while, -altera-unroll-loops, -misc-no-recursion, +# -altera-struct-pack-align +Checks: | + *, + -abseil-string-find-str-contains, + -altera-unroll-loops, + -altera-struct-pack-align, + -bugprone-branch-clone, -cert-err58-cpp, + -cppcoreguidelines-avoid-const-or-ref-data-members, + -cppcoreguidelines-avoid-do-while, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-avoid-magic-numbers, -cppcoreguidelines-owning-memory, -cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-bounds-constant-array-index, @@ -12,6 +25,7 @@ Checks: '*, -fuchsia-default-arguments, -fuchsia-default-arguments-calls, -fuchsia-statically-constructed-objects, + -fuchsia-default-arguments-declarations, -google-default-arguments, -google-explicit-constructor, -google-readability-braces-around-statements, @@ -24,6 +38,7 @@ Checks: '*, -hicpp-no-array-decay, -hicpp-signed-bitwise, -hicpp-special-member-functions, + -hicpp-uppercase-literal-suffix, -hicpp-use-auto, -hicpp-use-equals-default, -hicpp-use-override, @@ -31,6 +46,8 @@ Checks: '*, -llvm-header-guard, -llvm-include-order, -llvmlibc-*, + -misc-include-cleaner, + -misc-no-recursion -misc-string-compare, -misc-unused-using-decls, -modernize-loop-convert, @@ -38,20 +55,27 @@ Checks: '*, -modernize-use-auto, -modernize-use-equals-default, -modernize-use-override, + -modernize-use-trailing-return-type, -modernize-use-using, -performance-for-range-copy, -performance-unnecessary-value-param, -readability-avoid-const-params-in-decls, -readability-braces-around-statements, -readability-else-after-return, + -readability-function-cognitive-complexity, -readability-implicit-bool-conversion, -readability-inconsistent-declaration-parameter-name, -readability-non-const-parameter, -readability-string-compare, -readability-redundant-declaration, -readability-redundant-member-init, - -readability-static-accessed-through-instance' -WarningsAsErrors: '*, + -readability-static-accessed-through-instance, + -readability-uppercase-literal-suffix, + -readability-magic-numbers, + -readability-convert-member-functions-to-static, + -readability-make-member-function-const +WarningsAsErrors: | + *, -cert-err58-cpp, -cppcoreguidelines-owning-memory, -cppcoreguidelines-pro-bounds-array-to-pointer-decay, @@ -98,10 +122,10 @@ WarningsAsErrors: '*, -readability-non-const-parameter, -readability-redundant-declaration, -readability-redundant-member-init, - -readability-static-accessed-through-instance' + -readability-static-accessed-through-instance HeaderFilterRegex: '^((?!qt).)*h$' -AnalyzeTemporaryDtors: false -FormatStyle: none +#AnalyzeTemporaryDtors: false +FormatStyle: llvm CheckOptions: - key: bugprone-argument-comment.StrictMode value: '0' @@ -258,7 +282,7 @@ CheckOptions: - key: modernize-make-shared.IgnoreMacros value: '1' - key: modernize-make-shared.IncludeStyle - value: '0' + value: llvm - key: modernize-make-shared.MakeSmartPtrFunction value: 'std::make_shared' - key: modernize-make-shared.MakeSmartPtrFunctionHeader diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..da88d3f9 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ + +root = true + +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space + +[*.cmake, CMakeLists.txt] +indent_size = 2 + +[CMakePresets.json] +indent_style = tab diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..8526fcc2 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,58 @@ +name: Test + +on: [push, pull_request, workflow_dispatch] + +jobs: + test: + runs-on: ${{ matrix.platform.os }} + strategy: + matrix: + platform: + - { os: ubuntu-latest, workflow: build-linux, qt-arch: linux_gcc_64 } + - { os: windows-latest, workflow: build-windows, qt-arch: win64_msvc2019_64 } + steps: + - uses: actions/checkout@v4 + + - uses: lukka/get-cmake@latest + + - uses: humbletim/setup-vulkan-sdk@v1.2.0 + with: + vulkan-query-version: "1.3.283.0" + vulkan-components: Vulkan-Headers + vulkan-use-cache: true + + - uses: actions/setup-python@v5 + with: + python-version: '3.11.x' + + - name: Install Qt + uses: jurplel/install-qt-action@v4 + with: + version: '6.7.2' + arch: ${{ matrix.platform.qt-arch }} + dir: lib/qt + setup-python: false + cache: true + modules: qtmultimedia qtwebsockets + + - name: Install required packages + if: startsWith(matrix.platform.os, 'ubuntu') + run: | + sudo apt-get install -y libxtst-dev gcc-12 g++-12 clang-tidy + clang-tidy --version + echo "CC=gcc" >> $GITHUB_ENV + echo "CXX=g++" >> $GITHUB_ENV + sudo update-alternatives --install \ + /usr/bin/gcc gcc /usr/bin/gcc-12 110 \ + --slave /usr/bin/g++ g++ /usr/bin/g++-12 + + - uses: lukka/run-cmake@v10 + with: + workflowPreset: ${{ matrix.platform.workflow }} + + # FIXME: replace with cmake integration, when this when this issue is resolved: https://bugreports.qt.io/browse/QTBUG-127578 + - name: Run clang-tidy + if: startsWith(matrix.platform.os, 'ubuntu') + run: | + clang-tidy $(find src \( -name '*.cpp' -or -name '*.h' \) -and \( -not \( -name '*win*' -or -name '*Windows*' \) \)) + diff --git a/.gitignore b/.gitignore index 2c6370b6..c9476b90 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,5 @@ installer/*.exe build_scripts/win/__pycache__ build_scripts/win/current_build.bat AdvancedSettings_resource.rc -.qtc_clangd/ \ No newline at end of file +.qtc_clangd/ +.cache/ diff --git a/CMakeLists.txt b/CMakeLists.txt index abd3c837..d22eac60 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.20) +cmake_minimum_required(VERSION 3.27) project(AdvancedSettings VERSION 5.7.4 LANGUAGES CXX) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -184,7 +184,8 @@ set_source_files_properties(src/res/qml/common/MyResources.qml PROPERTIES QT_QML qt_add_executable(AdvancedSettings WIN32 MACOSX_BUNDLE ${SRCS} ${RESOURCES} ${HEADERS}) target_include_directories(AdvancedSettings PUBLIC - src + src) +target_include_directories(AdvancedSettings SYSTEM PUBLIC third-party/nlohmann third-party/openvr/headers) @@ -232,25 +233,23 @@ qt_add_qml_module(AdvancedSettings ) -if(GCC) +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") # GCC target_compile_options(AdvancedSettings + PUBLIC + -Wall + -Wpedantic + -Wextra + -pedantic-errors -Wcast-align -Wconversion -Wdouble-promotion - -Wduplicated-branches - -Wduplicated-cond - -Wextra -Wformat=2 - -Wlogical-op -Wno-sign-conversion -Wnon-virtual-dtor -Wnull-dereference -Wold-style-cast -Woverloaded-virtual - -Wpedantic - -Wrestrict -Wshadow - -Wunused -Wzero-as-null-pointer-constant -flto ) @@ -264,6 +263,7 @@ endif() if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") target_compile_options(AdvancedSettings + PUBLIC --system-header-prefix=qt --system-header-prefix=third-party -Wcast-align @@ -292,9 +292,7 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") endif() if(debugSymbolsAndLogs) - target_compile_definitions(AdvancedSettings PRIVATE - ENABLE_DEBUG_LOGGING - ) + target_compile_definitions(AdvancedSettings PRIVATE ENABLE_DEBUG_LOGGING) endif() if(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") @@ -446,3 +444,60 @@ elseif(MACOS) src/tabcontrollers/audiomanager/AudioManagerDummy.cpp ) endif() + +# XXX: This is a hack, bcs SKIP_LINTING in qt is not working, but this doesn't work on +# github actions because the files are not generated before this glob is used +# fix this when this issue is resolved: https://bugreports.qt.io/browse/QTBUG-127578 +file(GLOB_RECURSE skip "${CMAKE_CURRENT_BINARY_DIR}/.rcc/qmlcache/**/*.cpp" "${CMAKE_CURRENT_BINARY_DIR}/.rcc/qmlcache/*.cpp") +message("${CMAKE_BINARY_DIR}: ${skip}") +set_property(SOURCE ${skip} PROPERTY SKIP_LINTING ON) + +# Get all propreties that cmake supports +execute_process(COMMAND cmake --help-property-list OUTPUT_VARIABLE CMAKE_PROPERTY_LIST) + +# Convert command output into a CMake list +STRING(REGEX REPLACE ";" "\\\\;" CMAKE_PROPERTY_LIST "${CMAKE_PROPERTY_LIST}") +STRING(REGEX REPLACE "\n" ";" CMAKE_PROPERTY_LIST "${CMAKE_PROPERTY_LIST}") +# Fix https://stackoverflow.com/questions/32197663/how-can-i-remove-the-the-location-property-may-not-be-read-from-target-error-i +list(FILTER CMAKE_PROPERTY_LIST EXCLUDE REGEX "^LOCATION$|^LOCATION_|_LOCATION$") +# For some reason, "TYPE" shows up twice - others might too? +list(REMOVE_DUPLICATES CMAKE_PROPERTY_LIST) + +# build whitelist by filtering down from CMAKE_PROPERTY_LIST in case cmake is +# a different version, and one of our hardcoded whitelisted properties +# doesn't exist! +unset(CMAKE_WHITELISTED_PROPERTY_LIST) +foreach(prop ${CMAKE_PROPERTY_LIST}) + if(prop MATCHES "^(INTERFACE|[_a-z]|IMPORTED_LIBNAME_|MAP_IMPORTED_CONFIG_)|^(COMPATIBLE_INTERFACE_(BOOL|NUMBER_MAX|NUMBER_MIN|STRING)|EXPORT_NAME|IMPORTED(_GLOBAL|_CONFIGURATIONS|_LIBNAME)?|NAME|TYPE|NO_SYSTEM_FROM_IMPORTED)$") + list(APPEND CMAKE_WHITELISTED_PROPERTY_LIST ${prop}) + endif() +endforeach(prop) + +function(print_properties) + message ("CMAKE_PROPERTY_LIST = ${CMAKE_PROPERTY_LIST}") +endfunction(print_properties) + +function(print_whitelisted_properties) + message ("CMAKE_WHITELISTED_PROPERTY_LIST = ${CMAKE_WHITELISTED_PROPERTY_LIST}") +endfunction(print_whitelisted_properties) + +function(print_target_properties tgt) + + get_source_file_property(target_type ${tgt} TYPE) + if(target_type STREQUAL "INTERFACE_LIBRARY") + set(PROP_LIST ${CMAKE_WHITELISTED_PROPERTY_LIST}) + else() + set(PROP_LIST ${CMAKE_PROPERTY_LIST}) + endif() + + foreach (prop ${PROP_LIST}) + string(REPLACE "" "${CMAKE_BUILD_TYPE}" prop ${prop}) + # message ("Checking ${prop}") + get_property(propval SOURCE ${tgt} PROPERTY ${prop} SET) + if (propval) + get_source_file_property(propval ${tgt} ${prop}) + message ("${tgt} ${prop} = ${propval}") + endif() + endforeach(prop) +endfunction(print_target_properties) +print_target_properties("${CMAKE_CURRENT_BINARY_DIR}/.rcc/qmlcache/AdvancedSettings_src/res/qml/utilities_page/media_keys/MediaButton_qml.cpp") diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 00000000..596ac798 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,92 @@ +{ + "$schema": "https://cmake.org/cmake/help/latest/_downloads/3e2d73bff478d88a7de0de736ba5e361/schema.json", + "version": 8, + "configurePresets": [ + { + "name": "default", + "description": "Default build using Ninja Multi-Config generator", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "errors": { + "dev": true, + "deprecated": true + } + }, + { + "name": "build-linux", + "inherits": "default" + }, + { + "name": "build-linux-lint", + "inherits": "default", + "cacheVariables": { + "CMAKE_CXX_CLANG_TIDY": "clang-tidy" + } + }, + { + "name": "build-windows", + "inherits": "default", + "generator": "Visual Studio 17 2022", + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Windows" + } + } + ], + "buildPresets": [ + { + "name": "build-linux", + "configurePreset": "build-linux" + }, + { + "name": "build-linux-lint", + "configurePreset": "build-linux-lint" + }, + { + "name": "build-windows", + "configurePreset": "build-windows" + } + ], + "workflowPresets": [ + { + "name": "build-linux", + "steps": [ + { + "type": "configure", + "name": "build-linux" + }, + { + "type": "build", + "name": "build-linux" + } + ] + }, + { + "name": "build-linux-lint", + "steps": [ + { + "type": "configure", + "name": "build-linux-lint" + }, + { + "type": "build", + "name": "build-linux-lint" + } + ] + }, + { + "name": "build-windows", + "steps": [ + { + "type": "configure", + "name": "build-windows" + }, + { + "type": "build", + "name": "build-windows" + } + ] + } + ] +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..4313536e --- /dev/null +++ b/flake.lock @@ -0,0 +1,76 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1723235520, + "narHash": "sha256-0C+3hHzlFHcwE3GmT0cVfZNJ6iPAd6rmzM+E7/RwakA=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "faa9072e36068a0b17ef830e165fdb223bd4f9ae", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1720957393, + "narHash": "sha256-oedh2RwpjEa+TNxhg5Je9Ch6d3W1NKi7DbRO1ziHemA=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "693bc46d169f5af9c992095736e82c3488bf7dbb", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "systems": "systems", + "treefmt-nix": "treefmt-nix" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "id": "systems", + "type": "indirect" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": "nixpkgs_2" + }, + "locked": { + "lastModified": 1722330636, + "narHash": "sha256-uru7JzOa33YlSRwf9sfXpJG+UAV+bnBEYMjrzKrQZFw=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "768acdb06968e53aa1ee8de207fd955335c754b7", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..23d4cc50 --- /dev/null +++ b/flake.nix @@ -0,0 +1,118 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs"; + treefmt-nix.url = "github:numtide/treefmt-nix"; + }; + + outputs = { + nixpkgs, + treefmt-nix, + systems, + ... + }: let + pkgs = nixpkgs.legacyPackages."x86_64-linux"; + eachSystem = f: + nixpkgs.lib.genAttrs (import systems) (system: f nixpkgs.legacyPackages.${system}); + treefmtEval = eachSystem (pkgs: + treefmt-nix.lib.evalModule pkgs ({pkgs, ...}: { + projectRootFile = "flake.nix"; + programs.clang-format.enable = true; + settings.formatter = { + "qmlformat" = { + command = "${pkgs.qt6.qtdeclarative}/bin/qmlformat"; + options = [ + "-i" + ]; + includes = ["*.qml"]; + }; + }; + })); + in { + formatter."x86_64-linux" = treefmtEval.${pkgs.system}.config.build.wrapper; + devShells."x86_64-linux" = { + #default = pkgs.mkShell { + default = pkgs.pkgsLLVM.stdenv.mkDerivation { + name = "shell"; + nativeBuildInputs = builtins.attrValues { + inherit + (pkgs) + cmake + ninja + pkg-config + clang-tools_18 + python3 + cppcheck + include-what-you-use + valgrind + qtcreator + vulkan-headers + gdb + appimagekit + ; + }; + propagatedBuildInputs = builtins.attrValues { + inherit (pkgs) pulseaudio glslang vulkan-loader vulkan-tools vulkan-validation-layers; + inherit + (pkgs.qt6) + qtbase + qtmultimedia + qtdeclarative + qtwebsockets + qtsvg + ; + inherit + (pkgs.xorg) + libX11 + libXt + libXtst + ; + }; + #VULKAN_SDK = "${pkgs.vulkan-validation-layers}/share/vulkan/explicit_layer.d"; + QT_VULKAN_LIB = "${pkgs.vulkan-loader}/lib/libvulkan.so"; + shellHook = '' + LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.libGL}/lib:${pkgs.vulkan-loader}/lib" + + # read the setting for nullglob ('on' or 'off') + nullglob=$(shopt nullglob | cut -f 2) + # turn on nullglob + if [ $nullglob = "off" ]; then + shopt -s nullglob + fi + + QML2_IMPORT_PATH= + for v in $(echo "$CMAKE_PREFIX_PATH" | tr : '\n' | sort | uniq); do + list=($v/lib/*/qml) + for f in "''${list[@]}"; do + if [ -z "$QML2_IMPORT_PATH" ]; then + QML2_IMPORT_PATH=$f + else + QML2_IMPORT_PATH=$QML2_IMPORT_PATH:$f + fi + done + done + export QML2_IMPORT_PATH + + QT_PLUGIN_PATH= + for v in $(echo "$CMAKE_PREFIX_PATH" | tr : '\n' | sort | uniq); do + list=($v/lib/*/plugins) + for f in "''${list[@]}"; do + if [ -z "$QT_PLUGIN_PATH" ]; then + QT_PLUGIN_PATH=$f + else + QT_PLUGIN_PATH=$QT_PLUGIN_PATH:$f + fi + done + done + export QT_PLUGIN_PATH + + # turn nullglob back to the initial value + if [ $nullglob = "off" ]; then + shopt -u nullglob + fi + + PS1="DEVELOP $PS1" + ''; + }; + }; + }; +} diff --git a/src/alarm_clock/vr_alarm.cpp b/src/alarm_clock/vr_alarm.cpp index 3573a533..ea86d65d 100644 --- a/src/alarm_clock/vr_alarm.cpp +++ b/src/alarm_clock/vr_alarm.cpp @@ -1,7 +1,7 @@ -#include "../tabcontrollers/UtilitiesTabController.h" #include "vr_alarm.h" #include "../openvr/ovr_overlay_wrapper.h" #include "../utils/update_rate.h" +#include "settings/settings.h" #include #include @@ -31,9 +31,10 @@ VrAlarm::VrAlarm() ovr_overlay_wrapper::setOverlayWidthInMeters( m_alarmOverlayHandle, 0.3f ); - vr::HmdMatrix34_t overlayTransform = { { { 1.0f, 0.0f, 0.0f, 0.12f }, - { 0.0f, 1.0f, 0.0f, 0.08f }, - { 0.0f, 0.0f, 1.0f, -0.3f } } }; + vr::HmdMatrix34_t const overlayTransform + = { { { 1.0f, 0.0f, 0.0f, 0.12f }, + { 0.0f, 1.0f, 0.0f, 0.08f }, + { 0.0f, 0.0f, 1.0f, -0.3f } } }; vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( m_alarmOverlayHandle, @@ -87,7 +88,7 @@ void VrAlarm::checkAlarmStatus() showAlarmNotification(); setAlarmEnabled( false ); - std::thread t( + std::thread alarm_thread( []( vr::VROverlayHandle_t overlayHandle ) { // This will freeze the overlay for 3 seconds @@ -95,7 +96,7 @@ void VrAlarm::checkAlarmStatus() ovr_overlay_wrapper::hideOverlay( overlayHandle ); }, m_alarmOverlayHandle ); - t.detach(); + alarm_thread.detach(); } } diff --git a/src/alarm_clock/vr_alarm.h b/src/alarm_clock/vr_alarm.h index 6bc0b85d..127c4b0b 100644 --- a/src/alarm_clock/vr_alarm.h +++ b/src/alarm_clock/vr_alarm.h @@ -2,9 +2,6 @@ #include #include #include -#include -#include "../settings/settings.h" -#include "../openvr/ovr_overlay_wrapper.h" namespace alarm_clock { diff --git a/src/keyboard_input/input_parser.cpp b/src/keyboard_input/input_parser.cpp index 3aff1838..a8be28f8 100644 --- a/src/keyboard_input/input_parser.cpp +++ b/src/keyboard_input/input_parser.cpp @@ -190,91 +190,90 @@ std::optional checkIfLegalCapitalLiteral( std::string input ) noexcept std::vector ParseKeyboardInputsToTokens( const std::string inputs ) noexcept { - std::vector tokens{}; + std::vector tokens; - for ( auto ch = inputs.begin(), end = inputs.end(); ch != end; ++ch ) + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) + for ( auto cha = inputs.begin(), end = inputs.end(); cha != end; ++cha ) { - if ( const auto c = getNumberOrLetter( *ch ); c.has_value() ) + if ( const auto numOLet = getNumberOrLetter( *cha ); + numOLet.has_value() ) { - tokens.push_back( *c ); + tokens.push_back( *numOLet ); continue; } - if ( const auto c = getModifier( *ch ); c.has_value() ) + if ( const auto mod = getModifier( *cha ); mod.has_value() ) { tokens.push_back( Token::TOKEN_NO_KEYUP_NEXT ); - tokens.push_back( *c ); + tokens.push_back( *mod ); continue; } - if ( isspace( *ch ) ) + if ( isspace( *cha ) ) { tokens.push_back( Token::TOKEN_NEW_SEQUENCE ); } - if ( !isupper( *ch ) || isspace( *ch ) ) + if ( !isupper( *cha ) || isspace( *cha ) ) { - qInfo() << "Unknown character found in sequence: " << *ch; + qInfo() << "Unknown character found in sequence: " << *cha; continue; } // Everything below is upper case - if ( *ch == 'F' ) + if ( *cha == 'F' ) { - ++ch; - if ( ch == end ) + ++cha; + if ( cha == end ) { break; } - const auto token = getFunctionNumber( *ch ); + const auto token = getFunctionNumber( *cha ); if ( token.has_value() ) { tokens.push_back( *token ); continue; } - else - { - // Spec says to abort on errors and submit correct values before - // error. - break; - } + + // Spec says to abort on errors and submit correct values before + // error. + break; } - else if ( *ch == 'G' ) + if ( *cha == 'G' ) { - ++ch; - if ( ch == end ) + ++cha; + if ( cha == end ) { break; } - const auto token = getFunctionNumberExtended( *ch ); + const auto token = getFunctionNumberExtended( *cha ); if ( token.has_value() ) { tokens.push_back( *token ); continue; } - else - { - // Spec says to abort on errors and submit correct values before - // error. - break; - } + + // Spec says to abort on errors and submit correct values before + // error. + break; } std::string characters; - characters.push_back( *ch ); - while ( ch + 1 != end ) + characters.push_back( *cha ); + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) + while ( cha + 1 != end ) { - ++ch; - characters.push_back( *ch ); - if ( auto c = checkIfLegalCapitalLiteral( characters ); - c.has_value() ) + ++cha; + characters.push_back( *cha ); + if ( auto cap = checkIfLegalCapitalLiteral( characters ); + cap.has_value() ) { - tokens.push_back( *c ); + tokens.push_back( *cap ); characters.clear(); // break out of the while break; } } - if ( ch == end ) + if ( cha == end ) { break; } @@ -343,14 +342,14 @@ std::vector std::vector removeIncorrectTokens( const std::vector& tokens ) noexcept { - const auto spacesRemoved = removeDuplicateNewSequences( tokens ); - const auto ctrlRemoved + auto spacesRemoved = removeDuplicateNewSequences( tokens ); + auto ctrlRemoved = removeTokenInSameSequence( spacesRemoved, Token::MODIFIER_CTRL ); - const auto altRemoved + auto altRemoved = removeTokenInSameSequence( ctrlRemoved, Token::MODIFIER_ALT ); - const auto shiftRemoved + auto shiftRemoved = removeTokenInSameSequence( altRemoved, Token::MODIFIER_SHIFT ); - const auto superRemoved + auto superRemoved = removeTokenInSameSequence( shiftRemoved, Token::MODIFIER_SUPER ); return superRemoved; diff --git a/src/keyboard_input/input_parser.h b/src/keyboard_input/input_parser.h index 54a3510e..858b05ee 100644 --- a/src/keyboard_input/input_parser.h +++ b/src/keyboard_input/input_parser.h @@ -1,9 +1,8 @@ #pragma once #include #include -#include -#include +// NOLINTBEGIN(misc-confusable-identifiers) enum class Token { @@ -102,6 +101,7 @@ enum class Token KEY_8 = '8', KEY_9 = '9', }; +// NOLINTEND(misc-confusable-identifiers) std::vector ParseKeyboardInputsToTokens( const std::string inputs ) noexcept; diff --git a/src/keyboard_input/input_sender.h b/src/keyboard_input/input_sender.h index 5dfba81d..3beedd2e 100644 --- a/src/keyboard_input/input_sender.h +++ b/src/keyboard_input/input_sender.h @@ -39,9 +39,9 @@ inline void sendTokensAsInput( const std::vector tokens ) } if ( token == Token::TOKEN_NEW_SEQUENCE ) { - for ( const auto& h : heldInputs ) + for ( const auto& held : heldInputs ) { - sendKeyPress( h, KeyStatus::Up ); + sendKeyPress( held, KeyStatus::Up ); } heldInputs.clear(); continue; @@ -50,9 +50,9 @@ inline void sendTokensAsInput( const std::vector tokens ) if ( !heldInputs.empty() ) { - for ( const auto& h : heldInputs ) + for ( const auto& held : heldInputs ) { - sendKeyPress( h, KeyStatus::Up ); + sendKeyPress( held, KeyStatus::Up ); } } diff --git a/src/keyboard_input/input_sender_dummy.cpp b/src/keyboard_input/input_sender_dummy.cpp index 7d9dbda4..53293c5c 100644 --- a/src/keyboard_input/input_sender_dummy.cpp +++ b/src/keyboard_input/input_sender_dummy.cpp @@ -1,6 +1,6 @@ #include "input_sender.h" -void sendTokensAsInput( [[maybe_unused]] const std::vector tokens ) -{ - // dummy -} +void initOsSystems() {} +void shutdownOsSystems() {} + +void sendKeyPress( const Token /*token*/, const KeyStatus /*status*/ ) {} diff --git a/src/keyboard_input/keyboard_input.h b/src/keyboard_input/keyboard_input.h index 5b06b043..fa78adb4 100644 --- a/src/keyboard_input/keyboard_input.h +++ b/src/keyboard_input/keyboard_input.h @@ -1,6 +1,5 @@ #pragma once -#include #include namespace keyboardinput diff --git a/src/main.cpp b/src/main.cpp index fa5d6f00..46c601e1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,10 +1,11 @@ +#include "openvr/openvr_init.h" +#include "overlaycontroller.h" #include "utils/setup.h" #include "settings/settings.h" #include "openvr/ovr_settings_wrapper.h" #include #include -#include #ifdef _WIN64 # include @@ -23,7 +24,7 @@ int main( int argc, char* argv[] ) QCoreApplication::setAttribute( Qt::AA_Use96Dpi ); QCoreApplication::setAttribute( Qt::AA_UseDesktopOpenGL ); - MyQApplication mainEventLoop( argc, argv ); + MyQApplication const mainEventLoop( argc, argv ); mainEventLoop.setOrganizationName( application_strings::applicationOrganizationName ); mainEventLoop.setApplicationName( application_strings::applicationName ); @@ -61,12 +62,12 @@ int main( int argc, char* argv[] ) QQmlComponent component( &qmlEngine, url ); auto errors = component.errors(); - for ( auto& e : errors ) + for ( auto& err : errors ) { qCritical() << "QML Error: " - << e.toString().toStdString(); //<< std::endl; + << err.toString().toStdString(); //<< std::endl; } - auto quickObj = component.create(); + auto* quickObj = component.create(); controller->SetWidget( qobject_cast( quickObj ), application_strings::applicationDisplayName, application_strings::applicationKey ); @@ -83,10 +84,8 @@ int main( int argc, char* argv[] ) throw std::runtime_error( "Could not find applications manifest." ); } - else - { - manifest::installApplicationManifest( *manifestPath ); - } + + manifest::installApplicationManifest( *manifestPath ); } catch ( std::exception& e ) { @@ -98,7 +97,7 @@ int main( int argc, char* argv[] ) || settings::getSetting( settings::BoolSetting::APPLICATION_desktopModeToggle ) ) { - auto m_pWindow = new QQuickWindow(); + auto* m_pWindow = new QQuickWindow(); qobject_cast( quickObj ) ->setParentItem( m_pWindow->contentItem() ); m_pWindow->setGeometry( diff --git a/src/media_keys/media_keys.h b/src/media_keys/media_keys.h index 5ded3e5c..62588ecd 100644 --- a/src/media_keys/media_keys.h +++ b/src/media_keys/media_keys.h @@ -1,5 +1,4 @@ #pragma once -#include #include namespace keyboardinput diff --git a/src/media_keys/media_keys_dbus.cpp b/src/media_keys/media_keys_dbus.cpp index 6edb4faf..f923bd98 100644 --- a/src/media_keys/media_keys_dbus.cpp +++ b/src/media_keys/media_keys_dbus.cpp @@ -25,7 +25,7 @@ void callMethodForAllMediaPlayerAvailableServices( const QString& method ) qCritical() << names.error().message(); } - foreach ( QString name, names.value() ) + foreach ( QString const name, names.value() ) { if ( name.contains( "org.mpris.MediaPlayer2" ) ) { diff --git a/src/media_keys/media_keys_win.cpp b/src/media_keys/media_keys_win.cpp index 8026904f..b6ba6abf 100644 --- a/src/media_keys/media_keys_win.cpp +++ b/src/media_keys/media_keys_win.cpp @@ -35,7 +35,7 @@ void sendKeyboardInputRaw( std::vector inputs ) if ( ( inputs.size() > 0 ) && !success ) { - char* err; + char* err = nullptr; auto errCode = GetLastError(); if ( !FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, diff --git a/src/openvr/ivrinput.cpp b/src/openvr/ivrinput.cpp index acdb834d..f18df20a 100644 --- a/src/openvr/ivrinput.cpp +++ b/src/openvr/ivrinput.cpp @@ -1,7 +1,6 @@ #include "ivrinput.h" #include "ivrinput_action.h" #include -#include #include #include #include @@ -439,7 +438,7 @@ update state. */ void SteamIVRInput::UpdateStates() { - vr::EVRInputError error; + vr::EVRInputError error = {}; if ( !m_exclusiveInputSetToggle ) { error = vr::VRInput()->UpdateActionState( diff --git a/src/openvr/ivrinput.h b/src/openvr/ivrinput.h index 2629d907..eff6d645 100644 --- a/src/openvr/ivrinput.h +++ b/src/openvr/ivrinput.h @@ -175,6 +175,7 @@ class SteamIVRInput void actionSetPriorityToggle( bool value ); // false is all Sets, True IS System + haptics + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) std::atomic m_exclusiveInputSetToggle = false; vr::VRActionHandle_t leftHapticActionHandle(); diff --git a/src/openvr/ivrinput_action.h b/src/openvr/ivrinput_action.h index 3206d591..ae317093 100644 --- a/src/openvr/ivrinput_action.h +++ b/src/openvr/ivrinput_action.h @@ -38,14 +38,14 @@ class Action /*! An API internal handle that identifies an action. */ - vr::VRActionHandle_t handle() const noexcept + [[nodiscard]] vr::VRActionHandle_t handle() const noexcept { return m_handle; } /*! The actions manfiest name of the action. Used for error reporting. */ - std::string name() const noexcept + [[nodiscard]] std::string name() const noexcept { return m_name; } diff --git a/src/openvr/ivrinput_input_source.h b/src/openvr/ivrinput_input_source.h index fc9e8218..fd5d26f0 100644 --- a/src/openvr/ivrinput_input_source.h +++ b/src/openvr/ivrinput_input_source.h @@ -25,14 +25,14 @@ class InputSource /*! An API internal handle that identifies an input handle. */ - vr::VRInputValueHandle_t handle() const noexcept + [[nodiscard]] vr::VRInputValueHandle_t handle() const noexcept { return m_handle; } /*! The actions manfiest name of the action. Used for error reporting. */ - std::string name() const noexcept + [[nodiscard]] std::string name() const noexcept { return m_name; } diff --git a/src/openvr/ivrinput_manifest.h b/src/openvr/ivrinput_manifest.h index 002120e3..74b34576 100644 --- a/src/openvr/ivrinput_manifest.h +++ b/src/openvr/ivrinput_manifest.h @@ -25,7 +25,7 @@ class Manifest return; } - const auto validManifestPath = actionManifestPath->c_str(); + const auto* const validManifestPath = actionManifestPath->c_str(); auto error = vr::VRInput()->SetActionManifestPath( validManifestPath ); if ( error != vr::EVRInputError::VRInputError_None ) diff --git a/src/openvr/lh_console_util.cpp b/src/openvr/lh_console_util.cpp index d67fa7c5..90c12ed6 100644 --- a/src/openvr/lh_console_util.cpp +++ b/src/openvr/lh_console_util.cpp @@ -23,12 +23,12 @@ bool LHCUtil::FindAll() bool LHCUtil::FindAllRX() { QProcess* lhProcess = new QProcess(); - QString program = "lighthouse_console.exe"; + QString const program = "lighthouse_console.exe"; lhProcess->start( path_, QStringList() << "" ); lhProcess->waitForFinished(); - QString output = QString( lhProcess->readAllStandardOutput() ); - QStringList outputLines + QString const output = QString( lhProcess->readAllStandardOutput() ); + QStringList const outputLines = output.split( QRegularExpression( "[\r\n]" ), Qt::SkipEmptyParts ); bool RecieverStart = false; @@ -61,8 +61,8 @@ bool LHCUtil::FindConnectedTX( QString RXSerial ) lhProcess->start( path_, QStringList() << "/serial" << RXSerial << "exit" ); lhProcess->waitForFinished(); - QString output = QString( lhProcess->readAllStandardOutput() ); - QStringList outputLines + QString const output = QString( lhProcess->readAllStandardOutput() ); + QStringList const outputLines = output.split( QRegularExpression( "[\r\n]" ), Qt::SkipEmptyParts ); // std::vector OutputLines // = exec( ( "\"" + path_ + "\" /serial " + RXSerial + " exit" ).c_str() @@ -74,7 +74,7 @@ bool LHCUtil::FindConnectedTX( QString RXSerial ) if ( outputLine.contains( "Connected to receiver" ) ) { auto splitList = outputLine.split( ":" ); - QString TXSerial = splitList[0]; + QString const TXSerial = splitList[0]; if ( TXSerial == "lighthouse_console" ) { lhConFound = true; diff --git a/src/openvr/lh_console_util.h b/src/openvr/lh_console_util.h index ae816413..a50c5e84 100644 --- a/src/openvr/lh_console_util.h +++ b/src/openvr/lh_console_util.h @@ -1,17 +1,11 @@ #pragma once -#include "openvr.h" -#include -#include -#include -#include -#include -#include -#include -#include #include +#include #include #include -#include +#include +#include +#include namespace lh_con_util { @@ -30,13 +24,10 @@ class LHCUtil bool FindAllRX(); bool FindAllTX(); bool path_Init = false; + std::vector RXTX_Pairs_; public: - explicit LHCUtil( QString path ) - { - path_ = path; - } - std::vector RXTX_Pairs_; + explicit LHCUtil( QString path ) : path_( std::move( path ) ) {} bool FindAll(); bool FindConnectedTX( QString RXSerial ); QString GetLinkedTX( QString RXSerial ); diff --git a/src/openvr/openvr_init.cpp b/src/openvr/openvr_init.cpp index 6f141c97..0845aceb 100644 --- a/src/openvr/openvr_init.cpp +++ b/src/openvr/openvr_init.cpp @@ -5,7 +5,6 @@ #include "openvr_init.h" #include #include -#include "../openvr/ivrinput_manifest.h" namespace openvr_init { @@ -54,10 +53,8 @@ bool initializeProperly( const OpenVrInitializationType initType ) return true; } -void initializeOpenVR( const OpenVrInitializationType initType, int count ) +void initializeOpenVR( const OpenVrInitializationType initType ) { - bool success = initializeProperly( initType ); - // The function call and error message was the same for all version checks. // Specific error messages are unlikely to be necessary since both the type // and version are in the string and will be output. @@ -72,68 +69,73 @@ void initializeOpenVR( const OpenVrInitializationType initType, int count ) << std::to_string( trynumber ); }; - // Check whether OpenVR is too outdated - - // Sleep duration is an attempt to hopefully alleviate a possible race - // condition in steamvr - if ( !vr::VR_IsInterfaceVersionValid( vr::IVRSystem_Version ) ) - { - reportVersionError( vr::IVRSystem_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRSettings_Version ) ) - { - reportVersionError( vr::IVRSettings_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVROverlay_Version ) ) - { - reportVersionError( vr::IVROverlay_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRApplications_Version ) ) - { - reportVersionError( vr::IVRApplications_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRChaperone_Version ) ) - { - reportVersionError( vr::IVRChaperone_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRChaperoneSetup_Version ) ) - { - reportVersionError( vr::IVRChaperoneSetup_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRCompositor_Version ) ) - { - reportVersionError( vr::IVRCompositor_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRNotifications_Version ) ) - { - reportVersionError( vr::IVRNotifications_Version, count ); - success = false; - } - else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRInput_Version ) ) - { - reportVersionError( vr::IVRInput_Version, count ); - success = false; - } - if ( !success && count < 3 ) + const int max_retries = 3; + for ( int count = 0; count < max_retries; count++ ) { + bool success = initializeProperly( initType ); + // Check whether OpenVR is too outdated + + // Sleep duration is an attempt to hopefully alleviate a possible race + // condition in steamvr + if ( !vr::VR_IsInterfaceVersionValid( vr::IVRSystem_Version ) ) + { + reportVersionError( vr::IVRSystem_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRSettings_Version ) ) + { + reportVersionError( vr::IVRSettings_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( vr::IVROverlay_Version ) ) + { + reportVersionError( vr::IVROverlay_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( + vr::IVRApplications_Version ) ) + { + reportVersionError( vr::IVRApplications_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRChaperone_Version ) ) + { + reportVersionError( vr::IVRChaperone_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( + vr::IVRChaperoneSetup_Version ) ) + { + reportVersionError( vr::IVRChaperoneSetup_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRCompositor_Version ) ) + { + reportVersionError( vr::IVRCompositor_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( + vr::IVRNotifications_Version ) ) + { + reportVersionError( vr::IVRNotifications_Version, count ); + success = false; + } + else if ( !vr::VR_IsInterfaceVersionValid( vr::IVRInput_Version ) ) + { + reportVersionError( vr::IVRInput_Version, count ); + success = false; + } + if ( success ) + return; + qWarning() << "An error occured on initialization of " "openvr/steamvr attempting again " - << std::to_string( count + 1 ) << " of 3 Attempts"; + << std::to_string( count + 1 ) << " of " << max_retries + << " Attempts"; std::this_thread::sleep_for( std::chrono::seconds( 5 ) ); // 5.8.1 Unknown if VR shutdown needs to be callled if vr init fails - initializeOpenVR( initType, ( count + 1 ) ); - } - if ( count >= 3 ) - { - qCritical() << "initialization errors persist proceeding anyways"; } + qCritical() << "initialization errors persist proceeding anyways"; } } // namespace openvr_init diff --git a/src/openvr/openvr_init.h b/src/openvr/openvr_init.h index 0a4faaf9..efa5685d 100644 --- a/src/openvr/openvr_init.h +++ b/src/openvr/openvr_init.h @@ -8,6 +8,6 @@ enum class OpenVrInitializationType Utility, }; -void initializeOpenVR( const OpenVrInitializationType initType, int count = 0 ); +void initializeOpenVR( const OpenVrInitializationType initType ); } // namespace openvr_init diff --git a/src/openvr/ovr_application_wrapper.cpp b/src/openvr/ovr_application_wrapper.cpp index 2d06ea93..026989a4 100644 --- a/src/openvr/ovr_application_wrapper.cpp +++ b/src/openvr/ovr_application_wrapper.cpp @@ -6,24 +6,24 @@ namespace ovr_application_wrapper { std::string getSceneAppID() { - uint32_t pidScene = vr::VRApplications()->GetCurrentSceneProcessId(); - char key[bufferLen]; - vr::EVRApplicationError error + uint32_t const pidScene = vr::VRApplications()->GetCurrentSceneProcessId(); + std::array key; + vr::EVRApplicationError const error = vr::VRApplications()->GetApplicationKeyByProcessId( - pidScene, key, bufferLen ); - std::string keys = key; + pidScene, key.data(), bufferLen ); + std::string keys = key.data(); if ( error != vr::VRApplicationError_None ) { qWarning() << "Could not Get App ID by PID: " + std::to_string( error ); qWarning() << "Attempting to find through Enumeration"; auto appCount = vr::VRApplications()->GetApplicationCount(); const uint32_t bufferMax = vr::k_unMaxApplicationKeyLength; - char cStringOut[bufferMax]; + std::array cStringOut; for ( uint32_t i = 0; i < appCount; i++ ) { auto error2 = vr::VRApplications()->GetApplicationKeyByIndex( - i, cStringOut, bufferMax ); - std::string appID( cStringOut ); + i, cStringOut.data(), bufferMax ); + std::string appID( cStringOut.data() ); if ( appID.find( "steam.app" ) != std::string::npos ) { qWarning() << "Found App ID through Enumeration (only " diff --git a/src/openvr/ovr_application_wrapper.h b/src/openvr/ovr_application_wrapper.h index 3eb1c44e..0c1ff737 100644 --- a/src/openvr/ovr_application_wrapper.h +++ b/src/openvr/ovr_application_wrapper.h @@ -1,10 +1,7 @@ #pragma once #include -#include #include -#include -#include /* Wrapper For OpenVR's IVR application class, allows us to do our error logging * while also minimizing code diff --git a/src/openvr/ovr_overlay_wrapper.cpp b/src/openvr/ovr_overlay_wrapper.cpp index 6631dc6f..e3ceb17b 100644 --- a/src/openvr/ovr_overlay_wrapper.cpp +++ b/src/openvr/ovr_overlay_wrapper.cpp @@ -1,4 +1,5 @@ #include "ovr_overlay_wrapper.h" +#include "utils/paths.h" #include #include #include @@ -10,7 +11,7 @@ OverlayError createOverlay( const std::string overlayKey, vr::VROverlayHandle_t* overlayHandle, std::string customErrorMsg ) { - vr::VROverlayError oError = vr::VROverlay()->CreateOverlay( + vr::VROverlayError const oError = vr::VROverlay()->CreateOverlay( overlayKey.c_str(), overlayName.c_str(), overlayHandle ); if ( oError != vr::VROverlayError_None ) { @@ -28,7 +29,7 @@ OverlayError setOverlayColor( vr::VROverlayHandle_t overlayHandle, float blue, std::string customErrorMsg ) { - vr::VROverlayError oError + vr::VROverlayError const oError = vr::VROverlay()->SetOverlayColor( overlayHandle, red, green, blue ); if ( oError != vr::VROverlayError_None ) { @@ -45,7 +46,7 @@ OverlayError setOverlayAlpha( vr::VROverlayHandle_t overlayHandle, float alpha, std::string customErrorMsg ) { - vr::VROverlayError oError + vr::VROverlayError const oError = vr::VROverlay()->SetOverlayAlpha( overlayHandle, alpha ); if ( oError != vr::VROverlayError_None ) { @@ -62,7 +63,7 @@ OverlayError setOverlayWidthInMeters( vr::VROverlayHandle_t overlayHandle, float widthInMeters, std::string customErrorMsg ) { - vr::VROverlayError oError = vr::VROverlay()->SetOverlayWidthInMeters( + vr::VROverlayError const oError = vr::VROverlay()->SetOverlayWidthInMeters( overlayHandle, widthInMeters ); if ( oError != vr::VROverlayError_None ) { @@ -86,7 +87,7 @@ OverlayError setOverlayFromFile( vr::VROverlayHandle_t overlayHandle, qCritical() << "File not Found: " << fileName << customErrorMsg; return OverlayError::UndefinedError; } - vr::VROverlayError oError = vr::VROverlay()->SetOverlayFromFile( + vr::VROverlayError const oError = vr::VROverlay()->SetOverlayFromFile( overlayHandle, overlayPath->c_str() ); if ( oError != vr::VROverlayError_None ) { @@ -106,7 +107,7 @@ OverlayError setOverlayFromQImage( vr::VROverlayHandle_t overlayHandle, std::string customErrorMsg ) { image.convertTo( QImage::Format_RGBA8888 ); - vr::VROverlayError oError = vr::VROverlay()->SetOverlayRaw( + vr::VROverlayError const oError = vr::VROverlay()->SetOverlayRaw( overlayHandle, image.bits(), image.width(), image.height(), 4 ); if ( oError != vr::VROverlayError_None ) { @@ -122,7 +123,8 @@ OverlayError setOverlayFromQImage( vr::VROverlayHandle_t overlayHandle, OverlayError showOverlay( vr::VROverlayHandle_t overlayHandle, std::string customErrorMsg ) { - vr::VROverlayError oError = vr::VROverlay()->ShowOverlay( overlayHandle ); + vr::VROverlayError const oError + = vr::VROverlay()->ShowOverlay( overlayHandle ); if ( oError != vr::VROverlayError_None ) { qCritical() << "Error showing overlay For " @@ -137,7 +139,8 @@ OverlayError showOverlay( vr::VROverlayHandle_t overlayHandle, OverlayError hideOverlay( vr::VROverlayHandle_t overlayHandle, std::string customErrorMsg ) { - vr::VROverlayError oError = vr::VROverlay()->HideOverlay( overlayHandle ); + vr::VROverlayError const oError + = vr::VROverlay()->HideOverlay( overlayHandle ); if ( oError != vr::VROverlayError_None ) { qCritical() << "Error hiding overlay For " @@ -155,8 +158,9 @@ OverlayError setOverlayTransformAbsolute( const vr::HmdMatrix34_t* trackingOriginToOverlayTransform, std::string customErrorMsg ) { - vr::VROverlayError oError = vr::VROverlay()->SetOverlayTransformAbsolute( - overlayHandle, trackingOrigin, trackingOriginToOverlayTransform ); + vr::VROverlayError const oError + = vr::VROverlay()->SetOverlayTransformAbsolute( + overlayHandle, trackingOrigin, trackingOriginToOverlayTransform ); if ( oError != vr::VROverlayError_None ) { qCritical() << "Error setting Overlay Position For " @@ -172,14 +176,14 @@ std::string getOverlayKey( vr::VROverlayHandle_t overlayHandle ) { // max size as of ovr 1.11.11 128 bytes const uint32_t bufferMax = vr::k_unVROverlayMaxKeyLength; - char cStringOut[bufferMax]; - vr::EVROverlayError oErrorOut; + std::array cStringOut; + vr::EVROverlayError oErrorOut = {}; vr::VROverlay()->GetOverlayKey( - overlayHandle, cStringOut, bufferMax, &oErrorOut ); - std::string output = cStringOut; + overlayHandle, cStringOut.data(), bufferMax, &oErrorOut ); + std::string output = cStringOut.data(); if ( oErrorOut != vr::VROverlayError_None ) { - std::string errorName + std::string const errorName = vr::VROverlay()->GetOverlayErrorNameFromEnum( oErrorOut ); return ( "can't get name:" + errorName ); } diff --git a/src/openvr/ovr_overlay_wrapper.h b/src/openvr/ovr_overlay_wrapper.h index ed6df73d..3dc1486c 100644 --- a/src/openvr/ovr_overlay_wrapper.h +++ b/src/openvr/ovr_overlay_wrapper.h @@ -1,12 +1,8 @@ #pragma once +#include #include -#include -#include -#include #include -#include -#include "../utils/paths.h" /* Wrapper For OpenVR's IVR settings class, allows us to do our error logging * while also minimizing code diff --git a/src/openvr/ovr_settings_wrapper.cpp b/src/openvr/ovr_settings_wrapper.cpp index 410fcccb..906f8184 100644 --- a/src/openvr/ovr_settings_wrapper.cpp +++ b/src/openvr/ovr_settings_wrapper.cpp @@ -1,6 +1,9 @@ #include "ovr_settings_wrapper.h" -#include + #include +#include +#include +#include namespace ovr_settings_wrapper { @@ -40,13 +43,13 @@ std::pair getBool( std::string section, std::string customErrorMsg ) { - bool value; - vr::EVRSettingsError error; + bool value = false; + vr::EVRSettingsError error = {}; value = vr::VRSettings()->GetBool( section.c_str(), settingsKey.c_str(), &error ); - SettingsError e = handleErrors( settingsKey, error, customErrorMsg ); - std::pair p( e, value ); - return p; + SettingsError const err + = handleErrors( settingsKey, error, customErrorMsg ); + return std::make_pair( err, value ); } std::pair getInt32( std::string section, @@ -54,13 +57,13 @@ std::pair getInt32( std::string section, std::string customErrorMsg ) { - int value; - vr::EVRSettingsError error; + int value = 0; + vr::EVRSettingsError error = {}; value = static_cast( vr::VRSettings()->GetInt32( section.c_str(), settingsKey.c_str(), &error ) ); - SettingsError e = handleErrors( settingsKey, error, customErrorMsg ); - std::pair p( e, value ); - return p; + SettingsError const err + = handleErrors( settingsKey, error, customErrorMsg ); + return std::make_pair( err, value ); } std::pair getFloat( std::string section, @@ -68,14 +71,14 @@ std::pair getFloat( std::string section, std::string customErrorMsg ) { - float value; - vr::EVRSettingsError error; + float value = NAN; + vr::EVRSettingsError error = {}; value = vr::VRSettings()->GetFloat( section.c_str(), settingsKey.c_str(), &error ); handleErrors( settingsKey, error, customErrorMsg ); - SettingsError e = handleErrors( settingsKey, error, customErrorMsg ); - std::pair p( e, value ); - return p; + SettingsError const err + = handleErrors( settingsKey, error, customErrorMsg ); + return std::make_pair( err, value ); } std::pair getString( std::string section, @@ -83,19 +86,22 @@ std::pair getString( std::string section, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; // This appears to be correct value as set in CVRSettingHelper as of // ovr 1.11.11 const uint32_t bufferMax = 4096; - char cStringOut[bufferMax]; + std::array cStringOut; - vr::VRSettings()->GetString( - section.c_str(), settingsKey.c_str(), cStringOut, bufferMax, &error ); + vr::VRSettings()->GetString( section.c_str(), + settingsKey.c_str(), + cStringOut.data(), + bufferMax, + &error ); handleErrors( settingsKey, error, customErrorMsg ); - std::string value = cStringOut; - SettingsError e = handleErrors( settingsKey, error, customErrorMsg ); - std::pair p( e, value ); - return p; + std::string const value = cStringOut.data(); + SettingsError const err + = handleErrors( settingsKey, error, customErrorMsg ); + return std::make_pair( err, value ); } // Setters @@ -105,7 +111,7 @@ SettingsError setBool( std::string section, bool value, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; vr::VRSettings()->SetBool( section.c_str(), settingsKey.c_str(), value, &error ); return handleErrors( settingsKey, error, customErrorMsg ); @@ -116,7 +122,7 @@ SettingsError setInt32( std::string section, int value, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; vr::VRSettings()->SetInt32( section.c_str(), settingsKey.c_str(), static_cast( value ), @@ -129,7 +135,7 @@ SettingsError setFloat( std::string section, float value, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; vr::VRSettings()->SetFloat( section.c_str(), settingsKey.c_str(), value, &error ); return handleErrors( settingsKey, error, customErrorMsg ); @@ -140,15 +146,16 @@ SettingsError setString( std::string section, char* value, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; vr::VRSettings()->SetString( section.c_str(), settingsKey.c_str(), value, &error ); return handleErrors( settingsKey, error, customErrorMsg ); } +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) SettingsError removeSection( std::string section, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; vr::VRSettings()->RemoveSection( section.c_str(), &error ); return handleErrors( "section", error, customErrorMsg ); } @@ -157,7 +164,7 @@ SettingsError removeKeyInSection( std::string section, std::string settingsKey, std::string customErrorMsg ) { - vr::EVRSettingsError error; + vr::EVRSettingsError error = {}; vr::VRSettings()->RemoveKeyInSection( section.c_str(), settingsKey.c_str(), &error ); return handleErrors( settingsKey, error, customErrorMsg ); diff --git a/src/openvr/ovr_settings_wrapper.h b/src/openvr/ovr_settings_wrapper.h index 8c98a2b3..1d65b4a2 100644 --- a/src/openvr/ovr_settings_wrapper.h +++ b/src/openvr/ovr_settings_wrapper.h @@ -1,7 +1,6 @@ #pragma once #include -#include #include #include diff --git a/src/openvr/ovr_system_wrapper.cpp b/src/openvr/ovr_system_wrapper.cpp index 45c4b468..c3935684 100644 --- a/src/openvr/ovr_system_wrapper.cpp +++ b/src/openvr/ovr_system_wrapper.cpp @@ -1,10 +1,14 @@ #include "ovr_system_wrapper.h" -#include + #include +#include +#include #include namespace ovr_system_wrapper { +using std::string; + SystemError handleTrackedPropertyErrors( vr::TrackedDeviceProperty tdp, vr::ETrackedPropertyError error, std::string customErrorMsg ) @@ -25,7 +29,7 @@ SystemError handleTrackedPropertyErrors( vr::TrackedDeviceProperty tdp, return SystemError::NoError; } -std::string getPropertyFromTrackedEnum( vr::TrackedDeviceProperty ) +std::string getPropertyFromTrackedEnum( vr::TrackedDeviceProperty /*unused*/ ) { return "TODO"; } @@ -36,15 +40,14 @@ std::pair std::string customErrorMsg ) { - uint32_t unIndex = static_cast( deviceIndex ); - vr::ETrackedPropertyError error; - bool value; + uint32_t const unIndex = static_cast( deviceIndex ); + vr::ETrackedPropertyError error = {}; + bool value = false; value = vr::VRSystem()->GetBoolTrackedDeviceProperty( unIndex, property, &error ); - SystemError e + SystemError const err = handleTrackedPropertyErrors( property, error, customErrorMsg ); - std::pair p( e, value ); - return p; + return std::make_pair( err, value ); } std::pair @@ -53,15 +56,14 @@ std::pair std::string customErrorMsg ) { - uint32_t unIndex = static_cast( deviceIndex ); - int value; - vr::ETrackedPropertyError error; + uint32_t const unIndex = static_cast( deviceIndex ); + int value = 0; + vr::ETrackedPropertyError error = {}; value = static_cast( vr::VRSystem()->GetInt32TrackedDeviceProperty( unIndex, property, &error ) ); - SystemError e + SystemError const err = handleTrackedPropertyErrors( property, error, customErrorMsg ); - std::pair p( e, value ); - return p; + return std::make_pair( err, value ); } std::pair @@ -70,15 +72,13 @@ std::pair std::string customErrorMsg ) { - uint32_t unIndex = static_cast( deviceIndex ); - vr::ETrackedPropertyError error; - float value; - value = vr::VRSystem()->GetFloatTrackedDeviceProperty( + uint32_t const unIndex = static_cast( deviceIndex ); + vr::ETrackedPropertyError error = {}; + float const value = vr::VRSystem()->GetFloatTrackedDeviceProperty( unIndex, property, &error ); - SystemError e + SystemError const err = handleTrackedPropertyErrors( property, error, customErrorMsg ); - std::pair p( e, value ); - return p; + return std::make_pair( err, value ); } std::pair @@ -90,32 +90,31 @@ std::pair // This appears to be correct value as set in CVRSettingHelper as of // ovr 1.11.11 const uint32_t bufferMax = 4096; - char cStringOut[bufferMax]; - uint32_t unIndex = static_cast( deviceIndex ); + std::array cStringOut; + uint32_t const unIndex = static_cast( deviceIndex ); vr::VRSystem()->GetStringTrackedDeviceProperty( - unIndex, property, cStringOut, bufferMax ); - std::string value = cStringOut; - SystemError e = handleTrackedPropertyErrors( + unIndex, property, cStringOut.data(), bufferMax ); + std::string const value = cStringOut.data(); + SystemError const err = handleTrackedPropertyErrors( property, vr::TrackedProp_Success, customErrorMsg ); - std::pair p( e, value ); - return p; + return std::make_pair( err, value ); } bool deviceConnected( int index ) { - uint32_t unIndex = static_cast( index ); + uint32_t const unIndex = static_cast( index ); return vr::VRSystem()->IsTrackedDeviceConnected( unIndex ); } vr::ETrackedDeviceClass getDeviceClass( int index ) { - uint32_t unIndex = static_cast( index ); + uint32_t const unIndex = static_cast( index ); return vr::VRSystem()->GetTrackedDeviceClass( unIndex ); } std::string getDeviceName( int index ) { - uint32_t unIndex = static_cast( index ); + uint32_t const unIndex = static_cast( index ); // checks if connected returns unknown if not if ( !vr::VRSystem()->IsTrackedDeviceConnected( unIndex ) ) { @@ -128,83 +127,83 @@ std::string getDeviceName( int index ) { return "Error"; } - std::string cn = controllerNamePair.second; - if ( strcmp( cn.c_str(), "oculus_touch" ) == 0 ) + std::string const controller_name = controllerNamePair.second; + if ( controller_name == "oculus_touch" ) { return "Touch"; } - if ( strcmp( cn.c_str(), "knuckles" ) == 0 ) + if ( controller_name == "knuckles" ) { return "Knuckles"; } - if ( strcmp( cn.c_str(), "vive_controller" ) == 0 ) + if ( controller_name == "vive_controller" ) { return "Wand"; } - if ( strcmp( cn.c_str(), "hpmotioncontroller" ) == 0 ) + if ( controller_name == "hpmotioncontroller" ) { return "Reverb G2 WMR"; } - if ( strcmp( cn.c_str(), "holographic_controller" ) == 0 ) + if ( controller_name == "holographic_controller" ) { return "WMR"; } - if ( strcmp( cn.c_str(), "vive_cosmos_controller" ) == 0 ) + if ( controller_name == "vive_cosmos_controller" ) { return "Cosmos"; } - if ( strcmp( cn.c_str(), "vive_tracker" ) == 0 ) + if ( controller_name == "vive_tracker" ) { return "Tracker"; } - if ( strcmp( cn.c_str(), "indexhmd" ) == 0 ) + if ( controller_name == "indexhmd" ) { return "Index Headset"; } - if ( cn.find( "vive_tracker_" ) != std::string::npos ) + if ( controller_name.find( "vive_tracker_" ) != std::string::npos ) { - std::string side = ""; - if ( cn.find( "_left" ) != std::string::npos ) + std::string side; + if ( controller_name.find( "_left" ) != std::string::npos ) { side = "left "; } - else if ( cn.find( "_right" ) != std::string::npos ) + else if ( controller_name.find( "_right" ) != std::string::npos ) { side = "right "; } - std::string part = ""; - if ( cn.find( "handed" ) != std::string::npos ) + std::string part; + if ( controller_name.find( "handed" ) != std::string::npos ) { part = " hand"; } - else if ( cn.find( "shoulder" ) != std::string::npos ) + else if ( controller_name.find( "shoulder" ) != std::string::npos ) { part = "shoulder"; } - else if ( cn.find( "knee" ) != std::string::npos ) + else if ( controller_name.find( "knee" ) != std::string::npos ) { part = "knee"; } - else if ( cn.find( "elbow" ) != std::string::npos ) + else if ( controller_name.find( "elbow" ) != std::string::npos ) { part = "elbow"; } - else if ( cn.find( "foot" ) != std::string::npos ) + else if ( controller_name.find( "foot" ) != std::string::npos ) { part = "foot"; } - else if ( cn.find( "camera" ) != std::string::npos ) + else if ( controller_name.find( "camera" ) != std::string::npos ) { part = "camera"; } - else if ( cn.find( "waist" ) != std::string::npos ) + else if ( controller_name.find( "waist" ) != std::string::npos ) { part = "waist"; } return "Tracker " + side + part; } // TODO add HMD's - return std::string( controllerNamePair.second ); + return { controllerNamePair.second }; } std::vector getAllConnectedDevices( bool onlyWearable ) @@ -252,9 +251,10 @@ std::string getControllerName() } if ( trackedDeviceClass == vr::TrackedDeviceClass_Controller ) { - auto handRole = getInt32TrackedProperty( - i, vr::Prop_ControllerRoleHint_Int32 ) - .second; + auto handRole + = getInt32TrackedProperty( static_cast( i ), + vr::Prop_ControllerRoleHint_Int32 ) + .second; switch ( handRole ) { case vr::TrackedControllerRole_LeftHand: @@ -274,14 +274,16 @@ std::string getControllerName() break; } } - bool isRightCon = false, isLeftCon = false; - std::string right, left; + bool isRightCon = false; + bool isLeftCon = false; + std::string right; + std::string left; if ( found == 0b110 || found == 0b100 ) { isLeftCon = vr::VRSystem()->IsTrackedDeviceConnected( lftIdx ); if ( isLeftCon ) { - left = getStringTrackedProperty( lftIdx, + left = getStringTrackedProperty( static_cast( lftIdx ), vr::Prop_ControllerType_String ) .second; } @@ -291,7 +293,7 @@ std::string getControllerName() isRightCon = vr::VRSystem()->IsTrackedDeviceConnected( rightIdx ); if ( isRightCon ) { - right = getStringTrackedProperty( rightIdx, + right = getStringTrackedProperty( static_cast( rightIdx ), vr::Prop_ControllerType_String ) .second; } @@ -300,7 +302,8 @@ std::string getControllerName() { qWarning() << "WARNING: No Controllers assuming based on HMD"; auto hmdName - = getStringTrackedProperty( hmdIdx, vr::Prop_ControllerType_String ) + = getStringTrackedProperty( static_cast( hmdIdx ), + vr::Prop_ControllerType_String ) .second; if ( hmdName == "indexhmd" ) { diff --git a/src/openvr/ovr_system_wrapper.h b/src/openvr/ovr_system_wrapper.h index 7716f428..f55393da 100644 --- a/src/openvr/ovr_system_wrapper.h +++ b/src/openvr/ovr_system_wrapper.h @@ -1,10 +1,8 @@ #pragma once #include -#include #include #include -#include #include /* Wrapper For OpenVR's IVR settings class, allows us to do our error logging diff --git a/src/overlaycontroller.cpp b/src/overlaycontroller.cpp index d57d4a41..4ed58f9f 100644 --- a/src/overlaycontroller.cpp +++ b/src/overlaycontroller.cpp @@ -18,13 +18,14 @@ #include #include #include -#include #include #include #include "openvr/ovr_overlay_wrapper.h" +#include "openvr/ovr_settings_wrapper.h" #include "utils/Matrix.h" #include "keyboard_input/input_sender.h" #include "settings/settings.h" +#include "utils/update_rate.h" #include #include #include @@ -40,7 +41,7 @@ int verifyCustomTickRate( const int tickRate ) { return 1; } - else if ( tickRate > k_maxCustomTickRate ) + if ( tickRate > k_maxCustomTickRate ) { return k_maxCustomTickRate; } @@ -59,24 +60,24 @@ OverlayController::OverlayController( bool desktopMode, // Arbitrarily chosen Max Length of Directory path, should be sufficient for // Any set-up const uint32_t maxLength = 16192; - uint32_t requiredLength; + uint32_t requiredLength = 0; - char tempRuntimePath[maxLength]; - bool pathIsGood - = vr::VR_GetRuntimePath( tempRuntimePath, maxLength, &requiredLength ); + std::array tempRuntimePath; + bool const pathIsGood = vr::VR_GetRuntimePath( + tempRuntimePath.data(), maxLength, &requiredLength ); // Throw Error If over 16k characters in path string if ( !pathIsGood ) { qCritical() << "Error Finding VR Runtime Path, Attempting Recovery: "; - uint32_t maxLengthRe = requiredLength; + uint32_t const maxLengthRe = requiredLength; qInfo() << "Open VR reporting Required path length of: " << maxLengthRe; } - m_runtimePathUrl = QUrl::fromLocalFile( tempRuntimePath ); + m_runtimePathUrl = QUrl::fromLocalFile( tempRuntimePath.data() ); qInfo() << "VR Runtime Path: " << m_runtimePathUrl.toLocalFile(); - const double initVol = soundVolume(); + const float initVol = static_cast( soundVolume() ); m_activationSoundEffect.setSource( QUrl( "qrc:/sounds/click.wav" ) ); m_activationSoundEffect.setVolume( initVol ); @@ -322,6 +323,7 @@ void OverlayController::exitApp() QApplication::exit(); qInfo() << "All systems exited."; + // NOLINTNEXTLINE(concurrency-mt-unsafe) exit( EXIT_SUCCESS ); // Does not fallthrough } @@ -362,7 +364,7 @@ void OverlayController::SetWidget( QQuickItem* quickItem, { if ( !m_desktopMode ) { - vr::VROverlayError overlayError + vr::VROverlayError const overlayError = vr::VROverlay()->CreateDashboardOverlay( key.c_str(), name.c_str(), @@ -454,7 +456,7 @@ void OverlayController::SetWidget( QQuickItem* quickItem, static_cast( quickItem->width() ), static_cast( quickItem->height() ) ); - vr::HmdVector2_t vecWindowSize + vr::HmdVector2_t const vecWindowSize = { static_cast( quickItem->width() ), static_cast( quickItem->height() ) }; vr::VROverlay()->SetOverlayMouseScale( m_ulOverlayHandle, @@ -528,6 +530,7 @@ void OverlayController::SetOverlayFromQRhiTexture( QRhiTexture& tex ) { case QRhi::OpenGLES2: { + // NOLINTNEXTLINE(performance-no-int-to-ptr) vrTex.handle = reinterpret_cast( tex.nativeTexture().object ); vrTex.eType = vr::TextureType_OpenGL; vrTex.eColorSpace = vr::ColorSpace_Auto; @@ -548,7 +551,7 @@ void OverlayController::SetOverlayFromQRhiTexture( QRhiTexture& tex ) .m_nQueueFamilyIndex = vulkan_handles->gfxQueueIdx, .m_nWidth = static_cast( tex.pixelSize().width() ), .m_nHeight = static_cast( tex.pixelSize().height() ), - .m_nFormat = static_cast(tex.format()), + .m_nFormat = static_cast( tex.format() ), .m_nSampleCount = static_cast( tex.sampleCount() ), }; vrTex.handle = &vulkan; @@ -591,21 +594,19 @@ bool OverlayController::pollNextEvent( vr::VROverlayHandle_t ulOverlayHandle, { return vr::VRSystem()->PollNextEvent( pEvent, sizeof( vr::VREvent_t ) ); } - else - { - return vr::VROverlay()->PollNextOverlayEvent( - ulOverlayHandle, pEvent, sizeof( vr::VREvent_t ) ); - } + + return vr::VROverlay()->PollNextOverlayEvent( + ulOverlayHandle, pEvent, sizeof( vr::VREvent_t ) ); } QPointF OverlayController::getMousePositionForEvent( vr::VREvent_Mouse_t mouse ) { - float y = mouse.y; + float mouse_y = mouse.y; #ifdef __linux__ - float h = static_cast( m_window.height() ); - y = h - y; + float const height = static_cast( m_window.height() ); + mouse_y = height - mouse_y; #endif - return { mouse.x, y }; + return { static_cast(mouse.x), static_cast(mouse_y) }; } void OverlayController::processMediaKeyBindings() @@ -702,7 +703,7 @@ void OverlayController::processPushToTalkBindings() } // strictly speaking this is not the most elegant solution, but // should work well enough. - else if ( !pushToTalkEnabled ) + if ( !pushToTalkEnabled ) { m_audioTabController.setMicMuted( false ); } @@ -881,7 +882,7 @@ std::string OverlayController::autoApplyChaperoneName() Q_INVOKABLE void OverlayController::setAutoChapProfileName( int index ) { - std::string value + std::string const value = m_chaperoneTabController.getChaperoneProfileName( index ) .toStdString(); settings::setSetting( @@ -1111,7 +1112,8 @@ void OverlayController::mainEventLoop() { case vr::VREvent_MouseMove: { - QPointF ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); + QPointF const ptNewMouse + = getMousePositionForEvent( vrEvent.data.mouse ); if ( ptNewMouse != m_ptLastMouse ) { QMouseEvent mouseEvent( QEvent::MouseMove, @@ -1129,8 +1131,9 @@ void OverlayController::mainEventLoop() case vr::VREvent_MouseButtonDown: { - QPointF ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); - Qt::MouseButton button + QPointF const ptNewMouse + = getMousePositionForEvent( vrEvent.data.mouse ); + Qt::MouseButton const button = vrEvent.data.mouse.button == vr::VRMouseButton_Right ? Qt::RightButton : Qt::LeftButton; @@ -1147,8 +1150,9 @@ void OverlayController::mainEventLoop() case vr::VREvent_MouseButtonUp: { - QPointF ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); - Qt::MouseButton button + QPointF const ptNewMouse + = getMousePositionForEvent( vrEvent.data.mouse ); + Qt::MouseButton const button = vrEvent.data.mouse.button == vr::VRMouseButton_Right ? Qt::RightButton : Qt::LeftButton; @@ -1197,6 +1201,7 @@ void OverlayController::mainEventLoop() exitApp(); // Won't fallthrough, but also exitApp() wont, but QT won't // acknowledge + // NOLINTNEXTLINE(concurrency-mt-unsafe) exit( EXIT_SUCCESS ); } @@ -1217,9 +1222,9 @@ void OverlayController::mainEventLoop() case vr::VREvent_KeyboardDone: { - char keyboardBuffer[1024]; - vr::VROverlay()->GetKeyboardText( keyboardBuffer, 1024 ); - emit keyBoardInputSignal( QString( keyboardBuffer ), + std::array keyboardBuffer; + vr::VROverlay()->GetKeyboardText( keyboardBuffer.data(), 1024 ); + emit keyBoardInputSignal( QString( keyboardBuffer.data() ), static_cast( vrEvent.data.keyboard.uUserValue ) ); } @@ -1241,9 +1246,9 @@ void OverlayController::mainEventLoop() // issues. case vr::VREvent_ChaperoneUniverseHasChanged: { - uint64_t previousUniverseId + uint64_t const previousUniverseId = vrEvent.data.chaperone.m_nPreviousUniverse; - uint64_t currentUniverseId + uint64_t const currentUniverseId = vrEvent.data.chaperone.m_nCurrentUniverse; qInfo() << "(VREvent) ChaperoneUniverseHasChanged... Previous : " << previousUniverseId << " Current:" << currentUniverseId; @@ -1279,11 +1284,12 @@ void OverlayController::mainEventLoop() m_moveCenterTabController.incomingZeroReset(); } - vr::TrackedDevicePose_t devicePoses[vr::k_unMaxTrackedDeviceCount]; + std::array + devicePoses; vr::VRSystem()->GetDeviceToAbsoluteTrackingPose( vr::TrackingUniverseStanding, 0.0f, - devicePoses, + devicePoses.data(), vr::k_unMaxTrackedDeviceCount ); // HMD/Controller Velocities @@ -1312,13 +1318,13 @@ void OverlayController::mainEventLoop() = std::sqrt( vel[0] * vel[0] + vel[1] * vel[1] + vel[2] * vel[2] ); } auto universe = vr::VRCompositor()->GetTrackingSpace(); - m_moveCenterTabController.eventLoopTick( universe, devicePoses ); + m_moveCenterTabController.eventLoopTick( universe, devicePoses.data() ); m_utilitiesTabController.eventLoopTick(); m_statisticsTabController.eventLoopTick( - devicePoses, leftSpeed, rightSpeed ); - m_chaperoneTabController.eventLoopTick( universe, devicePoses ); + devicePoses.data(), leftSpeed, rightSpeed ); + m_chaperoneTabController.eventLoopTick( universe, devicePoses.data() ); m_audioTabController.eventLoopTick(); - m_rotationTabController.eventLoopTick( devicePoses ); + m_rotationTabController.eventLoopTick( devicePoses.data() ); m_alarm.eventLoopTick(); @@ -1326,7 +1332,7 @@ void OverlayController::mainEventLoop() { m_settingsTabController.dashboardLoopTick(); m_steamVRTabController.dashboardLoopTick(); - m_fixFloorTabController.dashboardLoopTick( devicePoses ); + m_fixFloorTabController.dashboardLoopTick( devicePoses.data() ); m_videoTabController.dashboardLoopTick(); m_chaperoneTabController.dashboardLoopTick(); } @@ -1342,7 +1348,8 @@ void OverlayController::mainEventLoop() { m_window.update(); } - break; + default: + break; } } } @@ -1375,7 +1382,7 @@ void OverlayController::RotateUniverseCenter( vr::HmdMatrix34_t rotMat; vr::HmdMatrix34_t newPos; - utils::initRotationMatrix( rotMat, 1, yAngle ); + utils::initRotationMatrix( rotMat, utils::MatrixAxis_Y, yAngle ); utils::matMul33( newPos, rotMat, curPos ); newPos.m[0][3] = curPos.m[0][3]; newPos.m[1][3] = curPos.m[1][3]; @@ -1406,12 +1413,12 @@ void OverlayController::AddOffsetToCollisionBounds( unsigned axisId, float offset, bool commit ) { - float offsetArray[3] = { 0, 0, 0 }; + std::array offsetArray = { 0, 0, 0 }; offsetArray[axisId] = offset; AddOffsetToCollisionBounds( offsetArray, commit ); } -void OverlayController::AddOffsetToCollisionBounds( float offset[3], +void OverlayController::AddOffsetToCollisionBounds( std::array offset, bool commit ) { // Apparently Valve sanity-checks the y-coordinates of the collision @@ -1430,30 +1437,29 @@ void OverlayController::AddOffsetToCollisionBounds( float offset[3], nullptr, &collisionBoundsCount ); if ( collisionBoundsCount > 0 ) { - vr::HmdQuad_t* collisionBounds - = new vr::HmdQuad_t[collisionBoundsCount]; + std::vector collisionBounds; + collisionBounds.resize( collisionBoundsCount ); vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo( - collisionBounds, &collisionBoundsCount ); - for ( unsigned b = 0; b < collisionBoundsCount; b++ ) + collisionBounds.data(), &collisionBoundsCount ); + for ( auto& bounds : collisionBounds ) { - for ( unsigned c = 0; c < 4; c++ ) + for ( unsigned cIndex = 0; cIndex < 4; cIndex++ ) { - collisionBounds[b].vCorners[c].v[0] += offset[0]; + bounds.vCorners[cIndex].v[0] += offset[0]; // keep the lower corners on the ground so it doesn't reset // all y cooridinates. this causes the caperone to "grow" up // instead of not moving up at all. note that Valve still // forces a minimum height so we can't go into the ground - if ( collisionBounds[b].vCorners[c].v[1] != 0 ) + if ( bounds.vCorners[cIndex].v[1] != 0 ) { - collisionBounds[b].vCorners[c].v[1] += offset[1]; + bounds.vCorners[cIndex].v[1] += offset[1]; } - collisionBounds[b].vCorners[c].v[2] += offset[2]; + bounds.vCorners[cIndex].v[2] += offset[2]; } } vr::VRChaperoneSetup()->SetWorkingCollisionBoundsInfo( - collisionBounds, collisionBoundsCount ); - delete[] collisionBounds; + collisionBounds.data(), collisionBoundsCount ); } if ( commit && collisionBoundsCount > 0 ) { @@ -1474,26 +1480,25 @@ void OverlayController::RotateCollisionBounds( float angle, bool commit ) nullptr, &collisionBoundsCount ); if ( collisionBoundsCount > 0 ) { - vr::HmdQuad_t* collisionBounds - = new vr::HmdQuad_t[collisionBoundsCount]; + std::vector collisionBounds; + collisionBounds.resize( collisionBoundsCount ); vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo( - collisionBounds, &collisionBoundsCount ); + collisionBounds.data(), &collisionBoundsCount ); vr::HmdMatrix34_t rotMat; - utils::initRotationMatrix( rotMat, 1, angle ); - for ( unsigned b = 0; b < collisionBoundsCount; b++ ) + utils::initRotationMatrix( rotMat, utils::MatrixAxis_Y, angle ); + for ( auto& bounds : collisionBounds ) { - for ( unsigned c = 0; c < 4; c++ ) + for ( unsigned cIndex = 0; cIndex < 4; cIndex++ ) { - auto& corner = collisionBounds[b].vCorners[c]; + auto& corner = bounds.vCorners[cIndex]; vr::HmdVector3_t newVal; utils::matMul33( newVal, rotMat, corner ); corner = newVal; } } vr::VRChaperoneSetup()->SetWorkingCollisionBoundsInfo( - collisionBounds, collisionBoundsCount ); - delete[] collisionBounds; + collisionBounds.data(), collisionBoundsCount ); } if ( commit && collisionBoundsCount > 0 ) { @@ -1510,7 +1515,7 @@ bool OverlayController::isPreviousShutdownSafe() QString OverlayController::getVersionString() { - return QString( application_strings::applicationVersionString ); + return { application_strings::applicationVersionString }; } QUrl OverlayController::getVRRuntimePathUrl() @@ -1559,17 +1564,18 @@ void OverlayController::setKeyboardPos() vr::VROverlay()->SetKeyboardPositionForOverlay( m_ulOverlayHandle, empty ); } -void OverlayController::setSoundVolume( double value, bool notify ) +void OverlayController::setSoundVolume( double dvalue, bool notify ) { + auto value = static_cast( dvalue ); m_activationSoundEffect.setVolume( value ); m_focusChangedSoundEffect.setVolume( value ); // leaving alarm sound alone for now as chaperone warning setting effects it // m_alarm01SoundEffect.setVolume( value); settings::setSetting( settings::DoubleSetting::APPLICATION_appVolume, - value ); + dvalue ); if ( notify ) { - emit soundVolumeChanged( value ); + emit soundVolumeChanged( dvalue ); } } @@ -1629,7 +1635,7 @@ void OverlayController::playAlarm01Sound( bool loop ) void OverlayController::setAlarm01SoundVolume( float vol ) { - m_alarm01SoundEffect.setVolume( static_cast( vol ) ); + m_alarm01SoundEffect.setVolume( vol ); } void OverlayController::cancelAlarm01Sound() @@ -1641,7 +1647,7 @@ void OverlayController::OnNetworkReply( QNetworkReply* reply ) { if ( reply->error() == QNetworkReply::NoError ) { - QByteArray replyByteData = reply->readAll(); + QByteArray const replyByteData = reply->readAll(); qInfo() << "Version Check: Recieved Data: " << replyByteData; QJsonParseError parseError; m_remoteVersionJsonDocument diff --git a/src/overlaycontroller.h b/src/overlaycontroller.h index 96f74cbf..c8eb5cee 100644 --- a/src/overlaycontroller.h +++ b/src/overlaycontroller.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include // because of incompatibilities with QtOpenGL and GLEW we need to cherry pick @@ -27,8 +26,6 @@ #include #include -#include "openvr/openvr_init.h" - #include "utils/ChaperoneUtils.h" #include "tabcontrollers/SteamVRTabController.h" @@ -46,8 +43,6 @@ #include "alarm_clock/vr_alarm.h" -#include "utils/update_rate.h" - namespace application_strings { constexpr auto applicationOrganizationName = "AdvancedSettings-Team"; @@ -169,6 +164,8 @@ class OverlayController : public QObject QJsonObject m_remoteVersionJsonObject; public: + // NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) + // I know it's an ugly hack to make them public to enable external // access, but I am too lazy to implement getters. SteamVRTabController m_steamVRTabController; @@ -182,6 +179,7 @@ class OverlayController : public QObject VideoTabController m_videoTabController; RotationTabController m_rotationTabController; bool m_incomingReset = false; + // NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) private: QPointF getMousePositionForEvent( vr::VREvent_Mouse_t mouse ); @@ -206,7 +204,7 @@ class OverlayController : public QObject public: void SetOverlayFromQRhiTexture( QRhiTexture& tex ); OverlayController( bool desktopMode, bool noSound, QQmlEngine& qmlEngine ); - virtual ~OverlayController(); + ~OverlayController() override; void Shutdown(); Q_INVOKABLE void exitApp(); @@ -228,7 +226,8 @@ class OverlayController : public QObject void AddOffsetToCollisionBounds( unsigned axisId, float offset, bool commit = true ); - void AddOffsetToCollisionBounds( float offset[3], bool commit = true ); + void AddOffsetToCollisionBounds( std::array offset, + bool commit = true ); void RotateCollisionBounds( float angle, bool commit = true ); // around y axis @@ -257,21 +256,22 @@ class OverlayController : public QObject vr::VREvent_t* pEvent ); void mainEventLoop(); - bool crashRecoveryDisabled() const; - bool exclusiveInputEnabled() const; - bool autoApplyChaperoneEnabled() const; - bool enableDebug() const; - bool disableVersionCheck() const; - bool newVersionDetected() const; - bool vsyncDisabled() const; - QString versionCheckText() const; - int customTickRateMs() const; - int debugState() const; + [[nodiscard]] bool crashRecoveryDisabled() const; + [[nodiscard]] bool exclusiveInputEnabled() const; + [[nodiscard]] bool autoApplyChaperoneEnabled() const; + [[nodiscard]] bool enableDebug() const; + [[nodiscard]] bool disableVersionCheck() const; + [[nodiscard]] bool newVersionDetected() const; + [[nodiscard]] bool vsyncDisabled() const; + [[nodiscard]] QString versionCheckText() const; + [[nodiscard]] int customTickRateMs() const; + [[nodiscard]] int debugState() const; std::string autoApplyChaperoneName(); - double soundVolume() const; - bool desktopModeToggle() const; + [[nodiscard]] double soundVolume() const; + [[nodiscard]] bool desktopModeToggle() const; + // NOLINTNEXTLINE(readability-redundant-access-specifiers) public slots: void renderOverlay(); void OnRenderRequest(); diff --git a/src/quaternion/quaternion.h b/src/quaternion/quaternion.h index c8d34162..71dc2b8d 100644 --- a/src/quaternion/quaternion.h +++ b/src/quaternion/quaternion.h @@ -1,37 +1,41 @@ #pragma once -#include #include +#include namespace quaternion { inline vr::HmdQuaternion_t fromHmdMatrix34( vr::HmdMatrix34_t matrix ) { - vr::HmdQuaternion_t q; + vr::HmdQuaternion_t quat; - q.w = sqrt( fmax( 0, + quat.w + = sqrt( fmax( 0, static_cast( 1 + matrix.m[0][0] + matrix.m[1][1] + matrix.m[2][2] ) ) ) / 2; - q.x = sqrt( fmax( 0, + quat.x + = sqrt( fmax( 0, static_cast( 1 + matrix.m[0][0] - matrix.m[1][1] - matrix.m[2][2] ) ) ) / 2; - q.y = sqrt( fmax( 0, + quat.y + = sqrt( fmax( 0, static_cast( 1 - matrix.m[0][0] + matrix.m[1][1] - matrix.m[2][2] ) ) ) / 2; - q.z = sqrt( fmax( 0, + quat.z + = sqrt( fmax( 0, static_cast( 1 - matrix.m[0][0] - matrix.m[1][1] + matrix.m[2][2] ) ) ) / 2; - q.x = copysign( q.x, - static_cast( matrix.m[2][1] - matrix.m[1][2] ) ); - q.y = copysign( q.y, - static_cast( matrix.m[0][2] - matrix.m[2][0] ) ); - q.z = copysign( q.z, - static_cast( matrix.m[1][0] - matrix.m[0][1] ) ); - return q; + quat.x = copysign( quat.x, + static_cast( matrix.m[2][1] - matrix.m[1][2] ) ); + quat.y = copysign( quat.y, + static_cast( matrix.m[0][2] - matrix.m[2][0] ) ); + quat.z = copysign( quat.z, + static_cast( matrix.m[1][0] - matrix.m[0][1] ) ); + return quat; } inline vr::HmdQuaternion_t multiply( const vr::HmdQuaternion_t& lhs, @@ -59,7 +63,7 @@ inline vr::HmdQuaternion_t conjugate( const vr::HmdQuaternion_t& quat ) inline double getYaw( const vr::HmdQuaternion_t& quat ) { - double yawResult + double const yawResult = atan2( 2.0 * ( quat.y * quat.w + quat.x * quat.z ), ( 2.0 * ( quat.w * quat.w + quat.x * quat.x ) ) - 1.0 ); return yawResult; @@ -70,7 +74,7 @@ inline double getPitch( const vr::HmdQuaternion_t& quat ) // positive forward // negative behind - double pitchResult + double const pitchResult = atan2( 2.0 * ( quat.x * quat.w + quat.y * quat.z ), 1.0 - 2.0 * ( quat.x * quat.x + quat.y * quat.y ) ); // double pitchResult @@ -81,8 +85,8 @@ inline double getPitch( const vr::HmdQuaternion_t& quat ) inline double getRoll( const vr::HmdQuaternion_t& quat ) { - double rollResult; - double sinp = 2 * ( quat.w * quat.z - quat.y * quat.x ); + double rollResult = NAN; + double const sinp = 2 * ( quat.w * quat.z - quat.y * quat.x ); if ( std::abs( sinp ) >= 1 ) { diff --git a/src/settings/internal/bool_setting_value.h b/src/settings/internal/bool_setting_value.h index 8aad5fd5..301896ff 100755 --- a/src/settings/internal/bool_setting_value.h +++ b/src/settings/internal/bool_setting_value.h @@ -1,6 +1,6 @@ #pragma once #include -#include "settings.h" +#include "../settings.h" #include "settings_internal.h" #include "setting_value.h" @@ -16,11 +16,11 @@ class BoolSettingValue : public SettingValue : SettingValue( category, qtInfo ), m_setting( setting ), m_value( defaultValue ) { - const auto v = getQtSetting( SettingValue::category(), - SettingValue::qtInfo().settingName ); - if ( isValidQVariant( v, QMetaType::Bool ) ) + const auto var = getQtSetting( SettingValue::category(), + SettingValue::qtInfo().settingName ); + if ( isValidQVariant( var ) ) { - m_value = v.toBool(); + m_value = var.toBool(); } } @@ -29,22 +29,22 @@ class BoolSettingValue : public SettingValue m_value = value; } - bool value() const noexcept + [[nodiscard]] bool value() const noexcept { return m_value; } - BoolSetting setting() const noexcept + [[nodiscard]] BoolSetting setting() const noexcept { return m_setting; } - SettingCategory category() const noexcept + [[nodiscard]] SettingCategory category() const noexcept { return SettingValue::category(); } - QtInfo qtInfo() const noexcept + [[nodiscard]] QtInfo qtInfo() const noexcept { return SettingValue::qtInfo(); } diff --git a/src/settings/internal/double_setting_value.h b/src/settings/internal/double_setting_value.h index 947a4823..40ee2dd9 100644 --- a/src/settings/internal/double_setting_value.h +++ b/src/settings/internal/double_setting_value.h @@ -1,6 +1,6 @@ #pragma once #include -#include "settings.h" +#include "../settings.h" #include "settings_internal.h" #include "setting_value.h" @@ -16,11 +16,11 @@ class DoubleSettingValue : public SettingValue : SettingValue( category, qtInfo ), m_setting( setting ), m_value( defaultValue ) { - const auto v = getQtSetting( SettingValue::category(), - SettingValue::qtInfo().settingName ); - if ( isValidQVariant( v, QMetaType::Double ) ) + const auto val = getQtSetting( SettingValue::category(), + SettingValue::qtInfo().settingName ); + if ( isValidQVariant( val ) ) { - m_value = v.toDouble(); + m_value = val.toDouble(); } } @@ -29,22 +29,22 @@ class DoubleSettingValue : public SettingValue m_value = value; } - double value() const noexcept + [[nodiscard]] double value() const noexcept { return m_value; } - DoubleSetting setting() const noexcept + [[nodiscard]] DoubleSetting setting() const noexcept { return m_setting; } - SettingCategory category() const noexcept + [[nodiscard]] SettingCategory category() const noexcept { return SettingValue::category(); } - QtInfo qtInfo() const noexcept + [[nodiscard]] QtInfo qtInfo() const noexcept { return SettingValue::qtInfo(); } diff --git a/src/settings/internal/settings_controller.h b/src/settings/internal/settings_controller.h index e8efb81b..f87d8568 100644 --- a/src/settings/internal/settings_controller.h +++ b/src/settings/internal/settings_controller.h @@ -1,5 +1,4 @@ #pragma once -#include #include #include #include @@ -14,17 +13,16 @@ namespace settings { template std::string valueToString( Value value ) { - using std::is_same; - if constexpr ( is_same::value ) + if constexpr ( std::is_same_v ) { return value ? "true" : "false"; } - else if constexpr ( is_same::value - || is_same::value ) + else if constexpr ( std::is_same_v + || std::is_same_v ) { return std::to_string( value ); } - if constexpr ( is_same::value ) + if constexpr ( std::is_same_v ) { return value; } @@ -32,20 +30,20 @@ template std::string valueToString( Value value ) template [[nodiscard]] std::string - returnSettingsAndValues( std::array v ) + returnSettingsAndValues( std::array vals ) { - std::string s = "default"; + std::string str = "default"; - for ( const auto& setting : v ) + for ( const auto& setting : vals ) { - s += setting.qtInfo().settingName + ": '" - + valueToString( setting.value() ) + "' | "; + str += setting.qtInfo().settingName + ": '" + + valueToString( setting.value() ) + "' | "; } - return s; + return str; } template -void verifySettings( std::array v ) noexcept +void verifySettings( std::array vals ) noexcept { for ( int settingIndex = 0; settingIndex < ( ArraySize - 1 ); ++settingIndex ) @@ -55,13 +53,13 @@ void verifySettings( std::array v ) noexcept // Also ensures that there are no mising values const auto currentSetting - = v[static_cast( settingIndex )].setting(); + = vals[static_cast( settingIndex )].setting(); const auto settingCorrectlyLocated = currentSetting == static_cast( settingIndex ); if ( !settingCorrectlyLocated ) { - const auto enumName = typeid( Enum ).name(); + const auto* const enumName = typeid( Enum ).name(); const auto enumSettingNumber = static_cast( currentSetting ); @@ -71,6 +69,7 @@ void verifySettings( std::array v ) noexcept << "'. Exiting " "with error code " << ReturnErrorCode::SETTING_INCORRECT_INDEX << "."; + // NOLINTNEXTLINE(concurrency-mt-unsafe) exit( ReturnErrorCode::SETTING_INCORRECT_INDEX ); } } @@ -90,21 +89,21 @@ class SettingsController verifySettings( m_intSettings ); } - std::string getSettingsAndValues() const noexcept + [[nodiscard]] std::string getSettingsAndValues() const noexcept { - std::string s; - s += returnSettingsAndValues( m_boolSettings ); + std::string str; + str += returnSettingsAndValues( m_boolSettings ); - s += returnSettingsAndValues( m_doubleSettings ); + str += returnSettingsAndValues( m_doubleSettings ); - s += returnSettingsAndValues( m_stringSettings ); + str += returnSettingsAndValues( m_stringSettings ); - s += returnSettingsAndValues( m_intSettings ); + str += returnSettingsAndValues( m_intSettings ); - return s; + return str; } - std::string getSettingsFileName() const noexcept + [[nodiscard]] std::string getSettingsFileName() const noexcept { return getQSettings().fileName().toStdString(); } @@ -116,7 +115,7 @@ class SettingsController return; } - for ( const auto setting : m_changedSettings ) + for ( auto* const setting : m_changedSettings ) { setting->saveValue(); } @@ -174,31 +173,31 @@ class SettingsController if constexpr ( std::is_same::value ) { - auto& s = m_boolSettings[index]; - s.setValue( value ); + auto& sett = m_boolSettings[index]; + sett.setValue( value ); - m_changedSettings.push_back( &s ); + m_changedSettings.push_back( &sett ); } else if constexpr ( std::is_same::value ) { - auto& s = m_doubleSettings[index]; - s.setValue( value ); + auto& sett = m_doubleSettings[index]; + sett.setValue( value ); - m_changedSettings.push_back( &s ); + m_changedSettings.push_back( &sett ); } else if constexpr ( std::is_same::value ) { - auto& s = m_intSettings[index]; - s.setValue( value ); + auto& sett = m_intSettings[index]; + sett.setValue( value ); - m_changedSettings.push_back( &s ); + m_changedSettings.push_back( &sett ); } else if constexpr ( std::is_same::value ) { - auto& s = m_stringSettings[index]; - s.setValue( value ); + auto& sett = m_stringSettings[index]; + sett.setValue( value ); - m_changedSettings.push_back( &s ); + m_changedSettings.push_back( &sett ); } } diff --git a/src/settings/internal/settings_internal.h b/src/settings/internal/settings_internal.h index 10bb1d9e..054aac69 100644 --- a/src/settings/internal/settings_internal.h +++ b/src/settings/internal/settings_internal.h @@ -25,17 +25,18 @@ struct QtInfo const std::string settingName; }; -[[nodiscard]] QSettings& getQSettings() +[[nodiscard]] inline QSettings& getQSettings() { - static QSettings s( QSettings::IniFormat, - QSettings::UserScope, - application_strings::applicationOrganizationName, - application_strings::applicationName ); + static QSettings settings( QSettings::IniFormat, + QSettings::UserScope, + application_strings::applicationOrganizationName, + application_strings::applicationName ); - return s; + return settings; } -[[nodiscard]] std::string getQtCategoryName( const SettingCategory category ) +[[nodiscard]] inline std::string + getQtCategoryName( const SettingCategory category ) { switch ( category ) { @@ -63,46 +64,43 @@ struct QtInfo return "no-value"; } -[[nodiscard]] QVariant getQtSetting( const SettingCategory category, - const std::string qtSettingName ) +[[nodiscard]] inline QVariant getQtSetting( const SettingCategory category, + const std::string qtSettingName ) { getQSettings().beginGroup( getQtCategoryName( category ).c_str() ); - const auto v = getQSettings().value( qtSettingName.c_str() ); + auto val = getQSettings().value( qtSettingName.c_str() ); getQSettings().endGroup(); - return v; + return val; } -void saveQtSetting( const SettingCategory category, - const std::string qtSettingName, - const QVariant value ) +inline void saveQtSetting( const SettingCategory category, + const std::string qtSettingName, + const QVariant value ) { getQSettings().beginGroup( getQtCategoryName( category ).c_str() ); getQSettings().setValue( qtSettingName.c_str(), value ); getQSettings().endGroup(); } -template [[nodiscard]] bool isValidQVariant( const QVariant v ) +template +[[nodiscard]] bool isValidQVariant( const QVariant var ) { - auto savedSettingIsValid = v.isValid() && !v.isNull(); + auto savedSettingIsValid = var.isValid() && !var.isNull(); - if constexpr ( std::is_same::value ) + if constexpr ( std::is_same_v ) { // Special case for std::string because Qt refuses to recognize it - savedSettingIsValid = savedSettingIsValid && v.canConvert(); + savedSettingIsValid = savedSettingIsValid && var.canConvert(); } else { - savedSettingIsValid = savedSettingIsValid && v.canConvert(); + savedSettingIsValid = savedSettingIsValid && var.canConvert(); } - if ( savedSettingIsValid ) - { - return true; - } - return false; + return savedSettingIsValid; } } // namespace settings diff --git a/src/settings/internal/settings_object_data.h b/src/settings/internal/settings_object_data.h index 727610ba..d1656254 100644 --- a/src/settings/internal/settings_object_data.h +++ b/src/settings/internal/settings_object_data.h @@ -1,5 +1,6 @@ #pragma once #include +#include namespace settings { diff --git a/src/settings/internal/specific_setting_value.h b/src/settings/internal/specific_setting_value.h index 0f81ec55..320d718a 100644 --- a/src/settings/internal/specific_setting_value.h +++ b/src/settings/internal/specific_setting_value.h @@ -23,29 +23,29 @@ class SpecificSettingValue : public SettingValue constexpr auto isInt = std::is_same::value; static_assert( isBool || isDouble || isString || isInt ); - const auto v = getQtSetting( SettingValue::category(), - SettingValue::qtInfo().settingName ); + const auto val = getQtSetting( SettingValue::category(), + SettingValue::qtInfo().settingName ); - if ( isValidQVariant( v ) ) + if ( isValidQVariant( val ) ) { if constexpr ( std::is_same::value ) { - m_value = v.toBool(); + m_value = val.toBool(); } else if constexpr ( std::is_same::value ) { - m_value = v.toDouble(); + m_value = val.toDouble(); } else if constexpr ( std::is_same::value ) { - m_value = v.toString().toStdString(); + m_value = val.toString().toStdString(); } else if constexpr ( std::is_same::value ) { - m_value = v.toInt(); + m_value = val.toInt(); } } diff --git a/src/settings/settings.cpp b/src/settings/settings.cpp index 316d6e54..bab9d655 100644 --- a/src/settings/settings.cpp +++ b/src/settings/settings.cpp @@ -1,12 +1,13 @@ -#include #include #include -#include "../overlaycontroller.h" #include "internal/settings_controller.h" namespace settings { -static SettingsController settingController{}; +namespace +{ + SettingsController settingController{}; +} // namespace void saveChangedSettings() { diff --git a/src/settings/settings_object.cpp b/src/settings/settings_object.cpp index 5986edae..34ac304d 100644 --- a/src/settings/settings_object.cpp +++ b/src/settings/settings_object.cpp @@ -1,4 +1,5 @@ #include +#include #include "settings_object.h" namespace settings @@ -35,38 +36,37 @@ void saveListToDisk( std::list values, const std::string structName, const std::string typeName ) { - auto& s = settings::getQSettings(); + auto& qset = settings::getQSettings(); - s.beginGroup( structName.c_str() ); - s.beginWriteArray( typeName.c_str() ); + qset.beginGroup( structName.c_str() ); + qset.beginWriteArray( typeName.c_str() ); for ( int i = 0; !values.empty(); ++i ) { - s.setArrayIndex( i ); - if constexpr ( std::is_same::value ) + qset.setArrayIndex( i ); + if constexpr ( std::is_same_v ) { - s.setValue( typeName.c_str(), values.front().c_str() ); + qset.setValue( typeName.c_str(), values.front().c_str() ); } else { - s.setValue( typeName.c_str(), values.front() ); + qset.setValue( typeName.c_str(), values.front() ); } values.pop_front(); } - s.endArray(); - s.endGroup(); + qset.endArray(); + qset.endGroup(); } template std::list loadListFromDisk( const std::string structName, const std::string typeName ) { - using std::is_same; - const auto isBool = is_same::value; - const auto isInt = is_same::value; - const auto isDouble = is_same::value; - const auto isFloat = is_same::value; - const auto isString = is_same::value; + const auto isBool = std::is_same_v; + const auto isInt = std::is_same_v; + const auto isDouble = std::is_same_v; + const auto isFloat = std::is_same_v; + const auto isString = std::is_same_v; static_assert( !isFloat, "'float' is not supported. Use 'double' instead." ); @@ -74,72 +74,74 @@ std::list loadListFromDisk( const std::string structName, static_assert( isBool || isInt || isDouble || isString, "Type is not supported for the settings object." ); - auto& s = settings::getQSettings(); + auto& qset = settings::getQSettings(); - s.beginGroup( structName.c_str() ); - auto size = s.beginReadArray( typeName.c_str() ); + qset.beginGroup( structName.c_str() ); + auto size = qset.beginReadArray( typeName.c_str() ); std::list list; - for ( int i = 0; i < size; ++i ) + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) + for ( int index = 0; index < size; index++ ) { - s.setArrayIndex( i ); - auto v = s.value( typeName.c_str() ); + qset.setArrayIndex( index ); + auto val = qset.value( typeName.c_str() ); if constexpr ( isBool ) { - list.push_back( v.toBool() ); + list.push_back( val.toBool() ); } else if constexpr ( isInt ) { - list.push_back( v.toInt() ); + list.push_back( val.toInt() ); } else if constexpr ( isDouble ) { - list.push_back( v.toDouble() ); + list.push_back( val.toDouble() ); } else if constexpr ( isString ) { - list.push_back( v.toString().toStdString() ); + list.push_back( val.toString().toStdString() ); } } - s.endArray(); - s.endGroup(); + qset.endArray(); + qset.endGroup(); return list; } settings::SettingsObjectData loadSettingsObject( std::string objName ) { - settings::SettingsObjectData s; + settings::SettingsObjectData sod; auto boolValues = loadListFromDisk( objName, "bools" ); - addListToObject( boolValues, s ); + addListToObject( boolValues, sod ); auto intValues = loadListFromDisk( objName, "ints" ); - addListToObject( intValues, s ); + addListToObject( intValues, sod ); auto doubleValues = loadListFromDisk( objName, "doubles" ); - addListToObject( doubleValues, s ); + addListToObject( doubleValues, sod ); auto stringValues = loadListFromDisk( objName, "strings" ); - addListToObject( stringValues, s ); + addListToObject( stringValues, sod ); - return s; + return sod; } -void saveSettingsObject( settings::SettingsObjectData& s, std::string objName ) +void saveSettingsObject( settings::SettingsObjectData& sod, + std::string objName ) { - auto boolValues = createListFromObject( s ); + auto boolValues = createListFromObject( sod ); saveListToDisk( boolValues, objName, "bools" ); - auto intValues = createListFromObject( s ); + auto intValues = createListFromObject( sod ); saveListToDisk( intValues, objName, "ints" ); - auto doubleValues = createListFromObject( s ); + auto doubleValues = createListFromObject( sod ); saveListToDisk( doubleValues, objName, "doubles" ); - auto stringValues = createListFromObject( s ); + auto stringValues = createListFromObject( sod ); saveListToDisk( stringValues, objName, "strings" ); } @@ -155,36 +157,36 @@ namespace settings { void saveObject( const ISettingsObject& obj ) { - auto s = obj.saveSettings(); - saveSettingsObject( s, obj.settingsName() ); + auto sod = obj.saveSettings(); + saveSettingsObject( sod, obj.settingsName() ); } void loadObject( ISettingsObject& obj ) { - auto s = loadSettingsObject( obj.settingsName() ); - obj.loadSettings( s ); + auto sod = loadSettingsObject( obj.settingsName() ); + obj.loadSettings( sod ); } void saveNumberedObject( const ISettingsObject& obj, const int slot ) { - auto s = obj.saveSettings(); + auto sod = obj.saveSettings(); saveSettingsObject( - s, appendSlotNumberToSettingsName( obj.settingsName(), slot ) ); + sod, appendSlotNumberToSettingsName( obj.settingsName(), slot ) ); } void loadNumberedObject( ISettingsObject& obj, const int slot ) { - auto s = loadSettingsObject( + auto sod = loadSettingsObject( appendSlotNumberToSettingsName( obj.settingsName(), slot ) ); - obj.loadSettings( s ); + obj.loadSettings( sod ); } int getAmountOfSavedObjects( ISettingsObject& obj ) { - auto& s = getQSettings(); + auto& sod = getQSettings(); - auto groups = s.childGroups(); + auto groups = sod.childGroups(); for ( int i = 1;; ++i ) { diff --git a/src/settings/settings_object.h b/src/settings/settings_object.h index eddcbcc6..460ab286 100644 --- a/src/settings/settings_object.h +++ b/src/settings/settings_object.h @@ -1,5 +1,7 @@ #pragma once #include "internal/settings_object_data.h" +#include +#include namespace settings { @@ -47,7 +49,7 @@ class ISettingsObject See \c ISettingsObject class for an example. */ - virtual SettingsObjectData saveSettings() const = 0; + [[nodiscard]] virtual SettingsObjectData saveSettings() const = 0; /*! \brief Function to convert from \c SettingsObjectData to parent object. @@ -62,7 +64,7 @@ class ISettingsObject globally. \return Internal identifier for saving/loading. */ - virtual std::string settingsName() const = 0; + [[nodiscard]] virtual std::string settingsName() const = 0; }; /*! @@ -100,14 +102,14 @@ void saveNumberedObject( const ISettingsObject& obj, const int slot ); template void saveAllObjects( const std::vector vec ) { static_assert( - std::is_base_of::value, + std::is_base_of_v, "Only objects that inherit from ISettingsObject can be saved." ); - auto i = 1; - for ( auto& p : vec ) + auto index = 1; + for ( auto& obj : vec ) { - saveNumberedObject( p, i ); - ++i; + saveNumberedObject( obj, index ); + ++index; } } @@ -120,15 +122,17 @@ template void saveAllObjects( const std::vector vec ) template void loadAllObjects( std::vector& vec ) { static_assert( - std::is_base_of::value, + std::is_base_of_v, "Only objects that inherit from ISettingsObject can be loaded." ); vec.clear(); // We'll need to know which name the object is saved under. // We could check vec.at(0), but it's not guaranteed to exist. - auto o = T{}; - auto profileCount = getAmountOfSavedObjects( o ); + auto obj = T{}; + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) + auto profileCount = getAmountOfSavedObjects( obj ); + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) for ( int profileNumber = 1; profileNumber <= profileCount; ++profileNumber ) { diff --git a/src/tabcontrollers/AudioTabController.cpp b/src/tabcontrollers/AudioTabController.cpp index 898f537a..c0ae0e85 100644 --- a/src/tabcontrollers/AudioTabController.cpp +++ b/src/tabcontrollers/AudioTabController.cpp @@ -21,7 +21,7 @@ namespace advsettings { void AudioTabController::initStage1() { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; #ifdef _WIN32 audioManager.reset( new AudioManagerWindows() ); #elif __linux__ @@ -34,10 +34,10 @@ void AudioTabController::initStage1() m_playbackDevices = audioManager->getPlaybackDevices(); m_recordingDevices = audioManager->getRecordingDevices(); findPlaybackDeviceIndex( audioManager->getPlaybackDevId(), false ); - char deviceId[1024]; + std::array deviceId; vr::VRSettings()->GetString( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackMirrorDevice_String, - deviceId, + deviceId.data(), 1024, &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) @@ -50,9 +50,9 @@ void AudioTabController::initStage1() } else { - audioManager->setMirrorDevice( deviceId ); + audioManager->setMirrorDevice( deviceId.data() ); findMirrorDeviceIndex( audioManager->getMirrorDevId(), false ); - lastMirrorDevId = deviceId; + lastMirrorDevId = deviceId.data(); m_mirrorVolume = audioManager->getMirrorVolume(); m_mirrorMuted = audioManager->getMirrorMuted(); } @@ -103,7 +103,7 @@ void AudioTabController::initStage2( OverlayController* var_parent ) *pushToImg ); vr::VROverlay()->SetOverlayWidthInMeters( m_pushToTalkValues.overlayHandle, 0.02f ); - vr::HmdMatrix34_t notificationTransform + vr::HmdMatrix34_t const notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.12f }, { 0.0f, 1.0f, 0.0f, 0.08f }, { 0.0f, 0.0f, 1.0f, -0.3f } } }; @@ -117,7 +117,7 @@ void AudioTabController::initStage2( OverlayController* var_parent ) void AudioTabController::reloadAudioSettings() { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); setMicProximitySensorCanMute( settings::getSetting( @@ -176,11 +176,11 @@ void AudioTabController::eventLoopTick() return; } - vr::EVRSettingsError vrSettingsError; - char mirrorDeviceId[1024]; + vr::EVRSettingsError vrSettingsError = {}; + std::array mirrorDeviceId; vr::VRSettings()->GetString( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackMirrorDevice_String, - mirrorDeviceId, + mirrorDeviceId.data(), 1024, &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) @@ -191,11 +191,11 @@ void AudioTabController::eventLoopTick() << vr::VRSettings()->GetSettingsErrorNameFromEnum( vrSettingsError ); } - if ( lastMirrorDevId.compare( mirrorDeviceId ) != 0 ) + if ( lastMirrorDevId.compare( mirrorDeviceId.data() ) != 0 ) { - audioManager->setMirrorDevice( mirrorDeviceId ); + audioManager->setMirrorDevice( mirrorDeviceId.data() ); findMirrorDeviceIndex( audioManager->getMirrorDevId() ); - lastMirrorDevId = mirrorDeviceId; + lastMirrorDevId = mirrorDeviceId.data(); } if ( m_mirrorDeviceIndex >= 0 ) { @@ -259,7 +259,7 @@ void AudioTabController::onPttDisabled() void AudioTabController::setMirrorVolume( float value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( value != m_mirrorVolume ) { m_mirrorVolume = value; @@ -276,7 +276,7 @@ void AudioTabController::setMirrorVolume( float value, bool notify ) void AudioTabController::setMirrorMuted( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( value != m_mirrorMuted ) { m_mirrorMuted = value; @@ -293,7 +293,7 @@ void AudioTabController::setMirrorMuted( bool value, bool notify ) void AudioTabController::setMicVolume( float value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( value != m_micVolume ) { m_micVolume = value; @@ -310,7 +310,7 @@ void AudioTabController::setMicVolume( float value, bool notify ) void AudioTabController::setMicMuted( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( value != m_micMuted ) { @@ -328,7 +328,7 @@ void AudioTabController::setMicMuted( bool value, bool notify ) void AudioTabController::setMicProximitySensorCanMute( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); settings::setSetting( settings::BoolSetting::AUDIO_micProximitySensorCanMute, value ); @@ -341,7 +341,7 @@ void AudioTabController::setMicProximitySensorCanMute( bool value, bool notify ) void AudioTabController::setMicReversePtt( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); settings::setSetting( settings::BoolSetting::AUDIO_micReversePtt, value ); @@ -375,7 +375,7 @@ void AudioTabController::setMicReversePtt( bool value, bool notify ) void AudioTabController::setAudioProfileDefault( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( value != m_isDefaultAudioProfile ) { m_isDefaultAudioProfile = value; @@ -458,10 +458,8 @@ QString AudioTabController::getPlaybackDeviceName( int index ) return QString::fromStdString( m_playbackDevices.at( static_cast( index ) ).name() ); } - else - { - return ""; - } + + return ""; } std::string AudioTabController::getPlaybackDeviceID( int index ) @@ -470,10 +468,8 @@ std::string AudioTabController::getPlaybackDeviceID( int index ) { return m_playbackDevices.at( static_cast( index ) ).id(); } - else - { - return ""; - } + + return ""; } std::string AudioTabController::getMirrorDeviceID( int index ) @@ -492,10 +488,8 @@ std::string AudioTabController::getRecordingDeviceID( int index ) { return m_recordingDevices.at( static_cast( index ) ).id(); } - else - { - return ""; - } + + return ""; } QString AudioTabController::getRecordingDeviceName( int index ) @@ -505,10 +499,8 @@ QString AudioTabController::getRecordingDeviceName( int index ) return QString::fromStdString( m_recordingDevices.at( static_cast( index ) ).name() ); } - else - { - return ""; - } + + return ""; } int AudioTabController::playbackDeviceIndex() const @@ -547,11 +539,11 @@ void AudioTabController::setPlaybackDeviceIndex( int index, bool notify ) void AudioTabController::setMirrorDeviceIndex( int index, bool notify ) { + vr::EVRSettingsError vrSettingsError = {}; if ( index != m_mirrorDeviceIndex ) { if ( index == -1 ) { - vr::EVRSettingsError vrSettingsError; vr::VRSettings()->RemoveKeyInSection( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackMirrorDevice_String, @@ -574,7 +566,6 @@ void AudioTabController::setMirrorDeviceIndex( int index, bool notify ) && index != m_playbackDeviceIndex && index != m_mirrorDeviceIndex ) { - vr::EVRSettingsError vrSettingsError; vr::VRSettings()->SetString( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackMirrorDevice_String, @@ -604,7 +595,7 @@ void AudioTabController::setMirrorDeviceIndex( int index, bool notify ) void AudioTabController::setMicDeviceIndex( int index, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( index != m_recordingDeviceIndex ) { if ( index >= 0 @@ -635,80 +626,76 @@ void AudioTabController::setMicDeviceIndex( int index, bool notify ) } } -void AudioTabController::findPlaybackDeviceIndex( std::string id, bool notify ) +void AudioTabController::findPlaybackDeviceIndex( std::string dev_id, + bool notify ) { - int i = 0; + int index = 0; bool deviceFound = false; - for ( auto d : m_playbackDevices ) + for ( auto dev : m_playbackDevices ) { - if ( d.id().compare( id ) == 0 ) + if ( dev.id().compare( dev_id ) == 0 ) { deviceFound = true; break; } - else - { - ++i; - } + + ++index; } if ( deviceFound ) { - m_playbackDeviceIndex = i; + m_playbackDeviceIndex = index; if ( notify ) { - emit playbackDeviceIndexChanged( i ); + emit playbackDeviceIndexChanged( index ); } } } -void AudioTabController::findMirrorDeviceIndex( std::string id, bool notify ) +void AudioTabController::findMirrorDeviceIndex( std::string dev_id, + bool notify ) { - int i = 0; + int index = 0; bool deviceFound = false; - for ( auto d : m_playbackDevices ) + for ( auto dev : m_playbackDevices ) { - if ( d.id().compare( id ) == 0 ) + if ( dev.id().compare( dev_id ) == 0 ) { deviceFound = true; break; } - else - { - ++i; - } + + ++index; } - if ( deviceFound && m_mirrorDeviceIndex != i ) + if ( deviceFound && m_mirrorDeviceIndex != index ) { - m_mirrorDeviceIndex = i; + m_mirrorDeviceIndex = index; if ( notify ) { - emit mirrorDeviceIndexChanged( i ); + emit mirrorDeviceIndexChanged( index ); } } } -void AudioTabController::findMicDeviceIndex( std::string id, bool notify ) +void AudioTabController::findMicDeviceIndex( std::string dev_id, bool notify ) { - int i = 0; + int index = 0; bool deviceFound = false; - for ( auto d : m_recordingDevices ) + for ( auto dev : m_recordingDevices ) { - if ( d.id().compare( id ) == 0 ) + if ( dev.id().compare( dev_id ) == 0 ) { deviceFound = true; break; } - else - { - ++i; - } + + ++index; } if ( deviceFound ) { - m_recordingDeviceIndex = i; + m_recordingDeviceIndex = index; if ( notify ) { - emit micDeviceIndexChanged( i ); + emit micDeviceIndexChanged( index ); } } } @@ -741,19 +728,19 @@ audioProfiles[] void AudioTabController::addAudioProfile( QString name ) { AudioProfile* profile = nullptr; - for ( auto& p : audioProfiles ) + for ( auto& pro : audioProfiles ) { - if ( p.profileName.compare( name.toStdString() ) == 0 ) + if ( pro.profileName.compare( name.toStdString() ) == 0 ) { - profile = &p; + profile = &pro; break; } } if ( !profile ) { - auto i = audioProfiles.size(); + auto index = audioProfiles.size(); audioProfiles.emplace_back(); - profile = &audioProfiles[i]; + profile = &audioProfiles[index]; } profile->profileName = name.toStdString(); profile->playbackName @@ -802,12 +789,12 @@ Description: Applies the required logic to activate the audio profile. void AudioTabController::applyAudioProfile( unsigned index ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); if ( index < audioProfiles.size() ) { auto& profile = audioProfiles[index]; - int mInd = getMirrorIndex( profile.mirrorID ); - int pInd = getPlaybackIndex( profile.playbackID ); + int const mInd = getMirrorIndex( profile.mirrorID ); + int const pInd = getPlaybackIndex( profile.playbackID ); // Needed to keep remembering when swtiching from mirror/main etc. // TODO OPTI can possibly clean up logic to reduce overhead in future. @@ -861,7 +848,7 @@ void AudioTabController::deleteAudioProfile( unsigned index ) // via native windows api. if ( audioProfiles.at( index ).defaultProfile ) { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->RemoveKeyInSection( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackDeviceOverrideName_String, @@ -911,7 +898,7 @@ void AudioTabController::setPlaybackOverride( bool value, bool notify ) if ( value != m_isPlaybackOverride ) { m_isPlaybackOverride = value; - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetBool( vr::k_pch_audio_Section, vr::k_pch_audio_EnablePlaybackDeviceOverride_Bool, @@ -934,7 +921,7 @@ void AudioTabController::setRecordingOverride( bool value, bool notify ) if ( value != m_isRecordingOverride ) { m_isRecordingOverride = value; - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetBool( vr::k_pch_audio_Section, vr::k_pch_audio_EnableRecordingDeviceOverride_Bool, @@ -955,7 +942,7 @@ void AudioTabController::setRecordingOverride( bool value, bool notify ) void AudioTabController::initOverride() { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; auto temp = vr::VRSettings()->GetBool( vr::k_pch_audio_Section, vr::k_pch_audio_EnableRecordingDeviceOverride_Bool, @@ -1066,7 +1053,7 @@ int AudioTabController::getMirrorIndex( std::string str ) void AudioTabController::setDefaultPlayback( int index, bool notify ) { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetString( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackDeviceOverrideName_String, @@ -1089,7 +1076,7 @@ void AudioTabController::setDefaultPlayback( int index, bool notify ) void AudioTabController::setDefaultMic( int index, bool notify ) { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetString( vr::k_pch_audio_Section, vr::k_pch_audio_RecordingDeviceOverrideName_String, @@ -1114,7 +1101,7 @@ void AudioTabController::setDefaultMirror( int index, bool notify ) { if ( index == -1 ) { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->RemoveKeyInSection( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackMirrorDevice_String, @@ -1134,7 +1121,7 @@ void AudioTabController::setDefaultMirror( int index, bool notify ) } else { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetString( vr::k_pch_audio_Section, vr::k_pch_audio_PlaybackMirrorDevice_String, @@ -1167,11 +1154,11 @@ description: checks all profiles and removes any OTHERS that are set as default. void AudioTabController::removeOtherDefaultProfiles( QString name ) { AudioProfile* profile = nullptr; - for ( auto& p : audioProfiles ) + for ( auto& pro : audioProfiles ) { - if ( p.profileName.compare( name.toStdString() ) != 0 ) + if ( pro.profileName.compare( name.toStdString() ) != 0 ) { - profile = &p; + profile = &pro; profile->defaultProfile = false; } } @@ -1286,7 +1273,7 @@ void AudioTabController::stopPtt() void AudioTabController::setPttEnabled( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); settings::setSetting( settings::BoolSetting::AUDIO_pttEnabled, value ); @@ -1307,7 +1294,7 @@ void AudioTabController::setPttEnabled( bool value, bool notify ) void AudioTabController::setPttShowNotification( bool value, bool notify ) { - std::lock_guard lock( eventLoopMutex ); + std::lock_guard const lock( eventLoopMutex ); settings::setSetting( settings::BoolSetting::AUDIO_pttShowNotification, value ); diff --git a/src/tabcontrollers/AudioTabController.h b/src/tabcontrollers/AudioTabController.h index 83a1e700..5874279e 100644 --- a/src/tabcontrollers/AudioTabController.h +++ b/src/tabcontrollers/AudioTabController.h @@ -6,8 +6,8 @@ #include "audiomanager/AudioManager.h" #include #include -#include "../utils/FrameRateUtils.h" #include "../settings/settings_object.h" +#include "openvr.h" class QQuickWindow; // application namespace @@ -15,9 +15,9 @@ namespace advsettings { // forward declaration class OverlayController; - struct AudioProfile : settings::ISettingsObject { + // NOLINTBEGIN(misc-non-private-member-variables-in-classes) std::string profileName; std::string playbackName; std::string mirrorName; @@ -30,30 +30,31 @@ struct AudioProfile : settings::ISettingsObject bool micMute = false; bool mirrorMute = false; bool defaultProfile = false; + // NOLINTEND(misc-non-private-member-variables-in-classes) - virtual settings::SettingsObjectData saveSettings() const + [[nodiscard]] settings::SettingsObjectData saveSettings() const override { - settings::SettingsObjectData o; + settings::SettingsObjectData sod; - o.addValue( profileName ); - o.addValue( playbackName ); - o.addValue( mirrorName ); - o.addValue( micName ); - o.addValue( recordingID ); - o.addValue( playbackID ); - o.addValue( mirrorID ); + sod.addValue( profileName ); + sod.addValue( playbackName ); + sod.addValue( mirrorName ); + sod.addValue( micName ); + sod.addValue( recordingID ); + sod.addValue( playbackID ); + sod.addValue( mirrorID ); - o.addValue( static_cast( mirrorVol ) ); - o.addValue( static_cast( micVol ) ); + sod.addValue( static_cast( mirrorVol ) ); + sod.addValue( static_cast( micVol ) ); - o.addValue( micMute ); - o.addValue( mirrorMute ); - o.addValue( defaultProfile ); + sod.addValue( micMute ); + sod.addValue( mirrorMute ); + sod.addValue( defaultProfile ); - return o; + return sod; } - virtual void loadSettings( settings::SettingsObjectData& obj ) + void loadSettings( settings::SettingsObjectData& obj ) override { profileName = obj.getNextValueOrDefault( "" ); playbackName = obj.getNextValueOrDefault( "" ); @@ -70,7 +71,7 @@ struct AudioProfile : settings::ISettingsObject defaultProfile = obj.getNextValueOrDefault( false ); } - virtual std::string settingsName() const + [[nodiscard]] std::string settingsName() const override { return "AudioTabController::AudioProfile"; } @@ -156,9 +157,9 @@ class AudioTabController : public QObject return m_pushToTalkValues.overlayHandle; } - void findPlaybackDeviceIndex( std::string id, bool notify = true ); - void findMirrorDeviceIndex( std::string id, bool notify = true ); - void findMicDeviceIndex( std::string id, bool notify = true ); + void findPlaybackDeviceIndex( std::string dev_id, bool notify = true ); + void findMirrorDeviceIndex( std::string dev_id, bool notify = true ); + void findMicDeviceIndex( std::string dev_id, bool notify = true ); int getPlaybackIndex( std::string str ); int getRecordingIndex( std::string str ); @@ -188,20 +189,20 @@ class AudioTabController : public QObject bool pttChangeValid(); - int playbackDeviceIndex() const; + [[nodiscard]] int playbackDeviceIndex() const; - int mirrorDeviceIndex() const; - float mirrorVolume() const; - bool mirrorMuted() const; + [[nodiscard]] int mirrorDeviceIndex() const; + [[nodiscard]] float mirrorVolume() const; + [[nodiscard]] bool mirrorMuted() const; - int micDeviceIndex() const; - float micVolume() const; - bool micMuted() const; - bool micProximitySensorCanMute() const; - bool micReversePtt() const; - bool audioProfileDefault() const; - bool playbackOverride() const; - bool recordingOverride() const; + [[nodiscard]] int micDeviceIndex() const; + [[nodiscard]] float micVolume() const; + [[nodiscard]] bool micMuted() const; + [[nodiscard]] bool micProximitySensorCanMute() const; + [[nodiscard]] bool micReversePtt() const; + [[nodiscard]] bool audioProfileDefault() const; + [[nodiscard]] bool playbackOverride() const; + [[nodiscard]] bool recordingOverride() const; void reloadAudioProfiles(); void saveAudioProfiles(); @@ -223,14 +224,13 @@ class AudioTabController : public QObject void onDeviceStateChanged(); void shutdown(); - bool pttEnabled() const; - bool pttActive() const; - bool pttShowNotification() const; + [[nodiscard]] bool pttEnabled() const; + [[nodiscard]] bool pttActive() const; + [[nodiscard]] bool pttShowNotification() const; void startPtt(); void stopPtt(); -public slots: void setMirrorVolume( float value, bool notify = true ); void setMirrorMuted( bool value, bool notify = true ); diff --git a/src/tabcontrollers/ChaperoneTabController.cpp b/src/tabcontrollers/ChaperoneTabController.cpp index 64f28416..0653169c 100644 --- a/src/tabcontrollers/ChaperoneTabController.cpp +++ b/src/tabcontrollers/ChaperoneTabController.cpp @@ -4,9 +4,10 @@ #include #include "../overlaycontroller.h" #include "../settings/settings.h" -#include "../utils/Matrix.h" -#include "../quaternion/quaternion.h" #include "../utils/update_rate.h" +#include "openvr/ovr_overlay_wrapper.h" +#include "openvr/ovr_settings_wrapper.h" +#include #include // application namespace @@ -89,7 +90,7 @@ void ChaperoneTabController::handleChaperoneWarnings( float distance ) // Switch to Beginner Mode if ( isChaperoneSwitchToBeginnerEnabled() ) { - float activationDistance = chaperoneSwitchToBeginnerDistance(); + float const activationDistance = chaperoneSwitchToBeginnerDistance(); if ( distance <= activationDistance && m_isHMDActive && !m_chaperoneSwitchToBeginnerActive ) @@ -117,7 +118,7 @@ void ChaperoneTabController::handleChaperoneWarnings( float distance ) if ( isChaperoneHapticFeedbackEnabled() ) { - float activationDistance = chaperoneHapticFeedbackDistance(); + float const activationDistance = chaperoneHapticFeedbackDistance(); if ( distance <= activationDistance && proxSensorOverrideState ) { @@ -185,7 +186,7 @@ void ChaperoneTabController::handleChaperoneWarnings( float distance ) if ( isChaperoneAlarmSoundEnabled() ) { qWarning() << "In alarm"; - float activationDistance = chaperoneAlarmSoundDistance(); + float const activationDistance = chaperoneAlarmSoundDistance(); if ( distance <= activationDistance && proxSensorOverrideState ) { @@ -220,7 +221,7 @@ void ChaperoneTabController::handleChaperoneWarnings( float distance ) // Show Dashboard if ( isChaperoneShowDashboardEnabled() ) { - float activationDistance = chaperoneShowDashboardDistance(); + float const activationDistance = chaperoneShowDashboardDistance(); if ( distance <= activationDistance && !m_chaperoneShowDashboardActive ) { if ( !vr::VROverlay()->IsDashboardVisible() ) @@ -264,7 +265,7 @@ void ChaperoneTabController::eventLoopTick( } else { - float pct = std::min( + float const pct = std::min( 1.0f, 2.0f - static_cast( count ) / 5000.0f ); // Originally this used opacity, but steam will override that it // seems @@ -275,7 +276,7 @@ void ChaperoneTabController::eventLoopTick( if ( devicePoses ) { m_isHMDActive = false; - std::lock_guard lock( + std::lock_guard const lock( parent->chaperoneUtils().mutex() ); auto minDistance = NAN; auto& poseHmd = devicePoses[vr::k_unTrackedDeviceIndex_Hmd]; @@ -398,20 +399,19 @@ void ChaperoneTabController::updateChaperoneSettings() void ChaperoneTabController::setBoundsVisibility( float value, bool notify ) { - setChaperoneColorA( - static_cast( static_cast( value ) * 255.0f ), notify ); + setChaperoneColorA( static_cast( value * 255.0f ), notify ); } float ChaperoneTabController::fadeDistance() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getFloat( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_FadeDistance_Float, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_fadeDistance; } @@ -436,15 +436,15 @@ void ChaperoneTabController::setFadeDistance( float value, bool notify ) float ChaperoneTabController::height() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getFloat( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_WallHeight_Float, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - m_height = p.second; - return p.second; + m_height = pair.second; + return pair.second; } return m_height; @@ -482,14 +482,14 @@ void ChaperoneTabController::updateHeight( float value, bool notify ) bool ChaperoneTabController::centerMarker() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getBool( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_CenterMarkerOn_Bool, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_centerMarker; @@ -514,14 +514,14 @@ void ChaperoneTabController::setCenterMarker( bool value, bool notify ) bool ChaperoneTabController::playSpaceMarker() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getBool( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_PlaySpaceOn_Bool, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_playSpaceMarker; @@ -626,103 +626,102 @@ float ChaperoneTabController::chaperoneShowDashboardDistance() const int ChaperoneTabController::chaperoneColorR() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getInt32( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_ColorGammaR_Int32, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_chaperoneColorR; } int ChaperoneTabController::chaperoneColorG() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getInt32( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_ColorGammaG_Int32, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_chaperoneColorG; } int ChaperoneTabController::chaperoneColorB() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getInt32( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_ColorGammaB_Int32, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_chaperoneColorB; } // aka transparancy int ChaperoneTabController::chaperoneColorA() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getInt32( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_ColorGammaA_Int32, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { return m_chaperoneColorA; } - return p.second; + return pair.second; } float ChaperoneTabController::boundsVisibility() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getInt32( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_ColorGammaA_Int32, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return static_cast( static_cast( m_chaperoneColorA ) - / 255.0f ); + return static_cast( m_chaperoneColorA ) / 255.0f; } - return static_cast( static_cast( p.second ) / 255.0f ); + return static_cast( pair.second ) / 255.0f; } bool ChaperoneTabController::chaperoneFloorToggle() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getBool( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_GroundPerimeterOn_Bool, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_chaperoneFloorToggle; } int ChaperoneTabController::collisionBoundStyle() { - std::pair p + std::pair const pair = ovr_settings_wrapper::getInt32( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_Style_Int32, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_collisionBoundStyle; } bool ChaperoneTabController::centerMarkerNew() { - bool temp = settings::getSetting( + bool const temp = settings::getSetting( settings::BoolSetting::CHAPERONE_centerMarkerNew ); return temp; } @@ -737,12 +736,10 @@ Q_INVOKABLE QString { if ( index >= chaperoneProfiles.size() ) { - return QString(); - } - else - { - return QString::fromStdString( chaperoneProfiles[index].profileName ); + return {}; } + + return QString::fromStdString( chaperoneProfiles[index].profileName ); } void ChaperoneTabController::setForceBounds( bool value, bool notify ) @@ -843,9 +840,9 @@ void ChaperoneTabController::setChaperoneColorB( int value, bool notify ) } void ChaperoneTabController::updateCenterMarkerOverlayColor() { - float chapColorR = static_cast( m_chaperoneColorR ) / 255.0f; - float chapColorG = static_cast( m_chaperoneColorG ) / 255.0f; - float chapColorB = static_cast( m_chaperoneColorB ) / 255.0f; + float const chapColorR = static_cast( m_chaperoneColorR ) / 255.0f; + float const chapColorG = static_cast( m_chaperoneColorG ) / 255.0f; + float const chapColorB = static_cast( m_chaperoneColorB ) / 255.0f; ovr_overlay_wrapper::setOverlayColor( m_chaperoneFloorOverlayHandle, chapColorR, chapColorG, chapColorB, "" ); } @@ -1236,19 +1233,19 @@ void ChaperoneTabController::addChaperoneProfile( bool includesProximityWarningSettings ) { ChaperoneProfile* profile = nullptr; - for ( auto& p : chaperoneProfiles ) + for ( auto& pro : chaperoneProfiles ) { - if ( p.profileName.compare( name.toStdString() ) == 0 ) + if ( pro.profileName.compare( name.toStdString() ) == 0 ) { - profile = &p; + profile = &pro; break; } } if ( !profile ) { - auto i = chaperoneProfiles.size(); + auto index = chaperoneProfiles.size(); chaperoneProfiles.emplace_back(); - profile = &chaperoneProfiles[i]; + profile = &chaperoneProfiles[index]; } profile->profileName = name.toStdString(); profile->includesChaperoneGeometry = includeGeometry; @@ -1260,10 +1257,7 @@ void ChaperoneTabController::addChaperoneProfile( vr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo( nullptr, &quadCount ); profile->chaperoneGeometryQuadCount = quadCount; - for ( int i = 0; i < static_cast( quadCount ); ++i ) - { - profile->chaperoneGeometryQuads.emplace_back(); - } + profile->chaperoneGeometryQuads.assign( quadCount, {} ); vr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo( profile->chaperoneGeometryQuads.data(), &quadCount ); @@ -1442,9 +1436,9 @@ std::pair { std::pair result = { false, 0 }; unsigned profileIndex = 0; - for ( auto& p : chaperoneProfiles ) + for ( auto& pro : chaperoneProfiles ) { - if ( name == p.profileName ) + if ( name == pro.profileName ) { result.first = true; result.second = profileIndex; @@ -1461,7 +1455,7 @@ void ChaperoneTabController::createNewAutosaveProfile() updateChaperoneSettings(); // lookup the index for old autosave and delete it - std::pair previousAutosaveIndexLookup + std::pair const previousAutosaveIndexLookup = getChaperoneProfileIndexFromName( "«Autosaved Profile (previous)»" ); if ( previousAutosaveIndexLookup.first ) { @@ -1474,7 +1468,7 @@ void ChaperoneTabController::createNewAutosaveProfile() } // lookup the index for current autosave and rename to old - std::pair currentAutosaveIndexLookup + std::pair const currentAutosaveIndexLookup = getChaperoneProfileIndexFromName( "«Autosaved Profile»" ); if ( currentAutosaveIndexLookup.first ) { @@ -1505,7 +1499,7 @@ void ChaperoneTabController::createNewAutosaveProfile() void ChaperoneTabController::applyAutosavedProfile() { // lookup index of autosave - std::pair autosaveIndexLookup + std::pair const autosaveIndexLookup = getChaperoneProfileIndexFromName( "«Autosaved Profile»" ); // check if it exists @@ -1610,9 +1604,9 @@ void ChaperoneTabController::addRightHapticClick( bool rightHapticClickPressed ) void ChaperoneTabController::initCenterMarkerOverlay() { - std::string overlayFloorMarkerKey + std::string const overlayFloorMarkerKey = std::string( application_strings::applicationKey ) + ".floormarker"; - ovr_overlay_wrapper::OverlayError overlayError + ovr_overlay_wrapper::OverlayError const overlayError = ovr_overlay_wrapper::createOverlay( overlayFloorMarkerKey, overlayFloorMarkerKey, &m_chaperoneFloorOverlayHandle, @@ -1672,7 +1666,7 @@ void ChaperoneTabController::checkCenterMarkerOverlayRotationCount() { m_rotationUpdateCounter = 0; float rotation = parent->m_statisticsTabController.hmdRotations(); - int rotationNext; + int rotationNext = 0; if ( rotation > 0 ) { rotation = rotation + 0.5f; diff --git a/src/tabcontrollers/ChaperoneTabController.h b/src/tabcontrollers/ChaperoneTabController.h index 38b31763..17d859f2 100644 --- a/src/tabcontrollers/ChaperoneTabController.h +++ b/src/tabcontrollers/ChaperoneTabController.h @@ -1,20 +1,14 @@ - #pragma once #include +#include #include #include #include #include #include -#include -#include "../utils/FrameRateUtils.h" -#include "../utils/ChaperoneUtils.h" #include "../settings/settings_object.h" #include "MoveCenterTabController.h" -#include "../openvr/ovr_overlay_wrapper.h" -#include "../openvr/ovr_settings_wrapper.h" -#include class QQuickWindow; // application namespace @@ -26,6 +20,7 @@ class OverlayController; struct ChaperoneProfile : settings::ISettingsObject { + // NOLINTBEGIN(misc-non-private-member-variables-in-classes) std::string profileName; bool includesChaperoneGeometry = false; @@ -50,7 +45,7 @@ struct ChaperoneProfile : settings::ISettingsObject bool floorBoundsMarker = false; bool includesBoundsColor = false; - int boundsColor[3] = { 0, 0, 0 }; + std::array boundsColor = { 0, 0, 0 }; bool includesChaperoneStyle = false; int chaperoneStyle = 0; @@ -71,28 +66,29 @@ struct ChaperoneProfile : settings::ISettingsObject float chaperoneShowDashboardDistance = 0.0f; bool centerMarkerNew = false; float chaperoneDimHeight = 0.0f; + // NOLINTEND(misc-non-private-member-variables-in-classes) - virtual settings::SettingsObjectData saveSettings() const override + [[nodiscard]] settings::SettingsObjectData saveSettings() const override { - settings::SettingsObjectData o; + settings::SettingsObjectData sod; - o.addValue( profileName ); + sod.addValue( profileName ); - o.addValue( includesChaperoneGeometry ); - o.addValue( static_cast( chaperoneGeometryQuadCount ) ); + sod.addValue( includesChaperoneGeometry ); + sod.addValue( static_cast( chaperoneGeometryQuadCount ) ); const auto chaperoneGeometryQuadsValid = chaperoneGeometryQuadCount > 0; - o.addValue( chaperoneGeometryQuadsValid ); + sod.addValue( chaperoneGeometryQuadsValid ); if ( chaperoneGeometryQuadsValid ) { - for ( auto& arrayMember : chaperoneGeometryQuads ) + for ( const auto& arrayMember : chaperoneGeometryQuads ) { - for ( auto& corner : arrayMember.vCorners ) + for ( const auto& corner : arrayMember.vCorners ) { - for ( auto& vector : corner.v ) + for ( const auto& vector : corner.v ) { - o.addValue( static_cast( vector ) ); + sod.addValue( static_cast( vector ) ); } } } @@ -102,59 +98,60 @@ struct ChaperoneProfile : settings::ISettingsObject { for ( int j = 0; j < 4; ++j ) { - o.addValue( static_cast( standingCenter.m[i][j] ) ); + sod.addValue( static_cast( standingCenter.m[i][j] ) ); } } - o.addValue( static_cast( playSpaceAreaX ) ); - o.addValue( static_cast( playSpaceAreaZ ) ); + sod.addValue( static_cast( playSpaceAreaX ) ); + sod.addValue( static_cast( playSpaceAreaZ ) ); - o.addValue( includesVisibility ); - o.addValue( static_cast( visibility ) ); + sod.addValue( includesVisibility ); + sod.addValue( static_cast( visibility ) ); - o.addValue( includesFadeDistance ); - o.addValue( static_cast( fadeDistance ) ); + sod.addValue( includesFadeDistance ); + sod.addValue( static_cast( fadeDistance ) ); - o.addValue( includesCenterMarker ); - o.addValue( centerMarker ); + sod.addValue( includesCenterMarker ); + sod.addValue( centerMarker ); - o.addValue( includesPlaySpaceMarker ); - o.addValue( playSpaceMarker ); + sod.addValue( includesPlaySpaceMarker ); + sod.addValue( playSpaceMarker ); - o.addValue( includesFloorBoundsMarker ); - o.addValue( floorBoundsMarker ); + sod.addValue( includesFloorBoundsMarker ); + sod.addValue( floorBoundsMarker ); - o.addValue( includesBoundsColor ); + sod.addValue( includesBoundsColor ); - for ( const auto& c : boundsColor ) + for ( const auto& color : boundsColor ) { - o.addValue( c ); + sod.addValue( color ); } - o.addValue( includesChaperoneStyle ); - o.addValue( chaperoneStyle ); - - o.addValue( includesForceBounds ); - o.addValue( forceBounds ); - - o.addValue( includesProximityWarningSettings ); - o.addValue( enableChaperoneSwitchToBeginner ); - o.addValue( static_cast( chaperoneSwitchToBeginnerDistance ) ); - o.addValue( enableChaperoneHapticFeedback ); - o.addValue( static_cast( chaperoneHapticFeedbackDistance ) ); - o.addValue( enableChaperoneAlarmSound ); - o.addValue( chaperoneAlarmSoundLooping ); - o.addValue( chaperoneAlarmSoundAdjustVolume ); - o.addValue( static_cast( chaperoneAlarmSoundDistance ) ); - o.addValue( enableChaperoneShowDashboard ); - o.addValue( static_cast( chaperoneShowDashboardDistance ) ); - o.addValue( centerMarkerNew ); - o.addValue( static_cast( chaperoneDimHeight ) ); - - return o; + sod.addValue( includesChaperoneStyle ); + sod.addValue( chaperoneStyle ); + + sod.addValue( includesForceBounds ); + sod.addValue( forceBounds ); + + sod.addValue( includesProximityWarningSettings ); + sod.addValue( enableChaperoneSwitchToBeginner ); + sod.addValue( + static_cast( chaperoneSwitchToBeginnerDistance ) ); + sod.addValue( enableChaperoneHapticFeedback ); + sod.addValue( static_cast( chaperoneHapticFeedbackDistance ) ); + sod.addValue( enableChaperoneAlarmSound ); + sod.addValue( chaperoneAlarmSoundLooping ); + sod.addValue( chaperoneAlarmSoundAdjustVolume ); + sod.addValue( static_cast( chaperoneAlarmSoundDistance ) ); + sod.addValue( enableChaperoneShowDashboard ); + sod.addValue( static_cast( chaperoneShowDashboardDistance ) ); + sod.addValue( centerMarkerNew ); + sod.addValue( static_cast( chaperoneDimHeight ) ); + + return sod; } - virtual void loadSettings( settings::SettingsObjectData& obj ) override + void loadSettings( settings::SettingsObjectData& obj ) override { profileName = obj.getNextValueOrDefault( "" ); @@ -166,11 +163,7 @@ struct ChaperoneProfile : settings::ISettingsObject = obj.getNextValueOrDefault( false ); if ( chaperoneGeometryQuadsValid ) { - for ( int i = 0; i < static_cast( chaperoneGeometryQuadCount ); - ++i ) - { - chaperoneGeometryQuads.emplace_back(); - } + chaperoneGeometryQuads.assign( chaperoneGeometryQuadCount, {} ); for ( auto& arrayMember : chaperoneGeometryQuads ) { @@ -214,9 +207,9 @@ struct ChaperoneProfile : settings::ISettingsObject includesBoundsColor = obj.getNextValueOrDefault( false ); - for ( auto& c : boundsColor ) + for ( auto& color : boundsColor ) { - c = obj.getNextValueOrDefault( 0 ); + color = obj.getNextValueOrDefault( 0 ); } includesChaperoneStyle = obj.getNextValueOrDefault( false ); @@ -245,7 +238,7 @@ struct ChaperoneProfile : settings::ISettingsObject = static_cast( obj.getNextValueOrDefault( 0.0 ) ); } - virtual std::string settingsName() const override + [[nodiscard]] std::string settingsName() const override { return "ChaperoneTabController::ChaperoneProfile"; } @@ -394,9 +387,10 @@ class ChaperoneTabController : public QObject vr::ETrackingUniverseOrigin m_trackingUniverse = vr::TrackingUniverseRawAndUncalibrated; + bool m_centerMarkerOverlayNeedsUpdate = false; public: - ~ChaperoneTabController(); + ~ChaperoneTabController() override; void initStage1(); void initStage2( OverlayController* parent ); @@ -412,8 +406,8 @@ class ChaperoneTabController : public QObject float height(); bool centerMarker(); bool playSpaceMarker(); - bool forceBounds() const; - bool disableChaperone() const; + [[nodiscard]] bool forceBounds() const; + [[nodiscard]] bool disableChaperone() const; int chaperoneColorR(); int chaperoneColorG(); @@ -423,13 +417,16 @@ class ChaperoneTabController : public QObject int getChaperoneProfileIndex(); bool centerMarkerNew(); - bool m_centerMarkerOverlayNeedsUpdate = false; + inline bool centerMarkerOverlayNeedsUpdate() + { + return m_centerMarkerOverlayNeedsUpdate; + } bool chaperoneFloorToggle(); int collisionBoundStyle(); - float chaperoneDimHeight() const; + [[nodiscard]] float chaperoneDimHeight() const; void setRightHapticActionHandle( vr::VRActionHandle_t handle ); void setLeftHapticActionHandle( vr::VRActionHandle_t handle ); @@ -438,19 +435,19 @@ class ChaperoneTabController : public QObject void setProxState( bool value ); - bool isChaperoneSwitchToBeginnerEnabled() const; - float chaperoneSwitchToBeginnerDistance() const; + [[nodiscard]] bool isChaperoneSwitchToBeginnerEnabled() const; + [[nodiscard]] float chaperoneSwitchToBeginnerDistance() const; - bool isChaperoneHapticFeedbackEnabled() const; - float chaperoneHapticFeedbackDistance() const; + [[nodiscard]] bool isChaperoneHapticFeedbackEnabled() const; + [[nodiscard]] float chaperoneHapticFeedbackDistance() const; - bool isChaperoneAlarmSoundEnabled() const; - bool isChaperoneAlarmSoundLooping() const; - bool isChaperoneAlarmSoundAdjustVolume() const; - float chaperoneAlarmSoundDistance() const; + [[nodiscard]] bool isChaperoneAlarmSoundEnabled() const; + [[nodiscard]] bool isChaperoneAlarmSoundLooping() const; + [[nodiscard]] bool isChaperoneAlarmSoundAdjustVolume() const; + [[nodiscard]] float chaperoneAlarmSoundDistance() const; - bool isChaperoneShowDashboardEnabled() const; - float chaperoneShowDashboardDistance() const; + [[nodiscard]] bool isChaperoneShowDashboardEnabled() const; + [[nodiscard]] float chaperoneShowDashboardDistance() const; void reloadChaperoneProfiles(); void saveChaperoneProfiles(); @@ -466,7 +463,6 @@ class ChaperoneTabController : public QObject void addLeftHapticClick( bool leftHapticClickPressed ); void addRightHapticClick( bool rightHapticClickPressed ); -public slots: void setBoundsVisibility( float value, bool notify = true ); void setFadeDistance( float value, bool notify = true ); void setHeight( float value, bool notify = true ); diff --git a/src/tabcontrollers/FixFloorTabController.cpp b/src/tabcontrollers/FixFloorTabController.cpp index 7ea11dbe..4e5e3b2e 100644 --- a/src/tabcontrollers/FixFloorTabController.cpp +++ b/src/tabcontrollers/FixFloorTabController.cpp @@ -57,9 +57,9 @@ void FixFloorTabController::dashboardLoopTick( state = 0; return; } - else if ( !rightPose->bPoseIsValid || !rightPose->bDeviceIsConnected - || rightPose->eTrackingResult - != vr::TrackingResult_Running_OK ) + if ( !rightPose->bPoseIsValid || !rightPose->bDeviceIsConnected + || rightPose->eTrackingResult + != vr::TrackingResult_Running_OK ) { statusMessage = "Right controller tracking problems."; statusMessageTimeout = 2.0; @@ -68,50 +68,48 @@ void FixFloorTabController::dashboardLoopTick( state = 0; return; } + + // The controller with the lowest y-pos is the floor fix + // reference + + if ( leftPose->mDeviceToAbsoluteTracking.m[1][3] + < rightPose->mDeviceToAbsoluteTracking.m[1][3] ) + { + referenceController = leftId; + } else { - // The controller with the lowest y-pos is the floor fix - // reference - - if ( leftPose->mDeviceToAbsoluteTracking.m[1][3] - < rightPose->mDeviceToAbsoluteTracking.m[1][3] ) - { - referenceController = leftId; - } - else - { - referenceController = rightId; - } + referenceController = rightId; + } - auto& m = devicePoses[referenceController] - .mDeviceToAbsoluteTracking.m; - tempOffsetX = static_cast( m[0][3] ); - tempOffsetY = static_cast( m[1][3] ); - tempOffsetZ = static_cast( m[2][3] ); + auto& mat + = devicePoses[referenceController].mDeviceToAbsoluteTracking.m; + tempOffsetX = static_cast( mat[0][3] ); + tempOffsetY = static_cast( mat[1][3] ); + tempOffsetZ = static_cast( mat[2][3] ); - /* - | Intrinsic y-x'-z" rotation matrix: - | cr*cy+sp*sr*sy | cr*sp*sy-cy*sr | cp*sy | - | cp*sr | cp*cr |-sp | - | cy*sp*sr-cr*sy | cr*cy*sp+sr*sy | cp*cy | + /* + | Intrinsic y-x'-z" rotation matrix: + | cr*cy+sp*sr*sy | cr*sp*sy-cy*sr | cp*sy | + | cp*sr | cp*cr |-sp | + | cy*sp*sr-cr*sy | cr*cy*sp+sr*sy | cp*cy | - yaw = atan2(cp*sy, cp*cy) [pi, -pi], CCW - pitch = -asin(-sp) [pi/2, -pi/2] - roll = atan2(cp*sr, cp*cr) [pi, -pi], CW - */ - tempRoll = std::atan2( static_cast( m[1][0] ), - static_cast( m[1][1] ) ); - measurementCount = 1; - } + yaw = atan2(cp*sy, cp*cy) [pi, -pi], CCW + pitch = -asin(-sp) [pi/2, -pi/2] + roll = atan2(cp*sr, cp*cr) [pi, -pi], CW + */ + tempRoll = std::atan2( static_cast( mat[1][0] ), + static_cast( mat[1][1] ) ); + measurementCount = 1; } else { measurementCount++; - auto& m + auto& mat = devicePoses[referenceController].mDeviceToAbsoluteTracking.m; - double rollDiff = std::atan2( static_cast( m[1][0] ), - static_cast( m[1][1] ) ) + double rollDiff = std::atan2( static_cast( mat[1][0] ), + static_cast( mat[1][1] ) ) - tempRoll; if ( rollDiff > M_PI ) { @@ -201,7 +199,7 @@ void FixFloorTabController::dashboardLoopTick( qInfo() << "Fix Floor and adjust space center: Floor Offset = [" << floorOffsetX << ", " << floorOffsetY << ", " << floorOffsetZ << "]"; - float offset[3] = { 0, 0, 0 }; + std::array offset = { 0, 0, 0 }; offset[1] = floorOffsetY; if ( state == 2 ) { @@ -234,14 +232,15 @@ int FixFloorTabController::getControllerType( big. We are just going to set 64 as an arbitrary size, and print error to log if too small */ - char controllerTypeString[maxLength]; - vr::ETrackedPropertyError error; + std::array controllerTypeStringData; + vr::ETrackedPropertyError error = {}; auto stringLength = vr::VRSystem()->GetStringTrackedDeviceProperty( controllerRole, vr::Prop_ControllerType_String, - controllerTypeString, + controllerTypeStringData.data(), maxLength, &error ); + std::string const controllerTypeString = controllerTypeStringData.data(); if ( error != vr::TrackedProp_Success ) { qCritical() << "Error With Controller Type: " @@ -251,11 +250,11 @@ int FixFloorTabController::getControllerType( { qCritical() << "Device Index not valid"; } - else if ( strcmp( controllerTypeString, "knuckles" ) == 0 ) + else if ( controllerTypeString == "knuckles" ) { return Controller_Knuckles; } - else if ( strcmp( controllerTypeString, "vive_controller" ) == 0 ) + else if ( controllerTypeString == "vive_controller" ) { return Controller_Wand; } @@ -307,16 +306,17 @@ void FixFloorTabController::recenterClicked() void FixFloorTabController::undoFixFloorClicked() { - float off[3] = { -floorOffsetX, -floorOffsetY, -floorOffsetZ }; - parent->m_moveCenterTabController.addOffset( off ); - qInfo() << "Fix Floor: Undo Floor Offset = [" << -floorOffsetX << ", " - << -floorOffsetY << ", " << -floorOffsetZ << "]"; - floorOffsetY = 0.0f; - statusMessage = "Undo ... OK"; - statusMessageTimeout = 1.0; - emit statusMessageSignal(); - setCanUndo( false ); - parent->m_moveCenterTabController.zeroOffsets(); + std::array const off = {-floorOffsetX, -floorOffsetY, + -floorOffsetZ}; + parent->m_moveCenterTabController.addOffset(off); + qInfo() << "Fix Floor: Undo Floor Offset = [" << -floorOffsetX << ", " + << -floorOffsetY << ", " << -floorOffsetZ << "]"; + floorOffsetY = 0.0f; + statusMessage = "Undo ... OK"; + statusMessageTimeout = 1.0; + emit statusMessageSignal(); + setCanUndo(false); + parent->m_moveCenterTabController.zeroOffsets(); } } // namespace advsettings diff --git a/src/tabcontrollers/FixFloorTabController.h b/src/tabcontrollers/FixFloorTabController.h index 9155c693..f2fe6ca9 100644 --- a/src/tabcontrollers/FixFloorTabController.h +++ b/src/tabcontrollers/FixFloorTabController.h @@ -61,9 +61,8 @@ class FixFloorTabController : public QObject Q_INVOKABLE QString currentStatusMessage(); Q_INVOKABLE float currentStatusMessageTimeout(); - bool canUndo() const; + [[nodiscard]] bool canUndo() const; -public slots: void fixFloorClicked(); void recenterClicked(); void undoFixFloorClicked(); diff --git a/src/tabcontrollers/MoveCenterTabController.cpp b/src/tabcontrollers/MoveCenterTabController.cpp index d38064c7..d964f2cf 100644 --- a/src/tabcontrollers/MoveCenterTabController.cpp +++ b/src/tabcontrollers/MoveCenterTabController.cpp @@ -6,31 +6,33 @@ #include "../quaternion/quaternion.h" #include "../settings/settings.h" -void rotateCoordinates( double coordinates[3], double angle ) +void rotateCoordinates( std::array coordinates, double angle ) { if ( angle == 0 ) { return; } - double s = sin( angle ); - double c = cos( angle ); - double newX = coordinates[0] * c - coordinates[2] * s; - double newZ = coordinates[0] * s + coordinates[2] * c; + double const sangle = sin( angle ); + double const cangle = cos( angle ); + double const newX = coordinates[0] * cangle - coordinates[2] * sangle; + double const newZ = coordinates[0] * sangle + coordinates[2] * cangle; coordinates[0] = newX; coordinates[2] = newZ; } -void rotateFloatCoordinates( float coordinates[3], float angle ) +void rotateFloatCoordinates( std::array coordinates, float angle ) { if ( angle == 0 ) { return; } // crazy casts for compiler warnings - float s = static_cast( sin( static_cast( angle ) ) ); - float c = static_cast( cos( static_cast( angle ) ) ); - float newX = coordinates[0] * c - coordinates[2] * s; - float newZ = coordinates[0] * s + coordinates[2] * c; + float const sangle + = static_cast( sin( static_cast( angle ) ) ); + float const cangle + = static_cast( cos( static_cast( angle ) ) ); + float const newX = coordinates[0] * cangle - coordinates[2] * sangle; + float const newZ = coordinates[0] * sangle + coordinates[2] * cangle; coordinates[0] = newX; coordinates[2] = newZ; } @@ -71,30 +73,28 @@ Q_INVOKABLE QString { if ( index >= m_offsetProfiles.size() ) { - return QString(); - } - else - { - return QString::fromStdString( m_offsetProfiles[index].profileName ); + return {}; } + + return QString::fromStdString( m_offsetProfiles[index].profileName ); } void MoveCenterTabController::addOffsetProfile( QString name ) { OffsetProfile* profile = nullptr; - for ( auto& p : m_offsetProfiles ) + for ( auto& pro : m_offsetProfiles ) { - if ( p.profileName.compare( name.toStdString() ) == 0 ) + if ( pro.profileName.compare( name.toStdString() ) == 0 ) { - profile = &p; + profile = &pro; break; } } if ( !profile ) { - auto i = m_offsetProfiles.size(); + auto index = m_offsetProfiles.size(); m_offsetProfiles.emplace_back(); - profile = &m_offsetProfiles[i]; + profile = &m_offsetProfiles[index]; } profile->profileName = name.toStdString(); profile->offsetX = m_offsetX; @@ -125,7 +125,7 @@ void MoveCenterTabController::applyOffsetProfile( unsigned index ) } } -void MoveCenterTabController::addOffset( float offset[] ) +void MoveCenterTabController::addOffset( std::array offset ) { m_universeCenterForReset.m[0][3] += offset[0]; m_universeCenterForReset.m[1][3] += offset[1]; @@ -140,7 +140,7 @@ void MoveCenterTabController::addOffset( float offset[] ) void MoveCenterTabController::addCurOffsetAsCenter() { - float off[3] = { -m_offsetX, m_offsetY, -m_offsetZ }; + std::array const off = { -m_offsetX, m_offsetY, -m_offsetZ }; // zeroOffsets(); resetOffsets( true ); addOffset( off ); @@ -159,15 +159,16 @@ void MoveCenterTabController::deleteOffsetProfile( unsigned index ) void MoveCenterTabController::outputLogPoses() { - vr::TrackedDevicePose_t devicePosesStanding[vr::k_unMaxTrackedDeviceCount]; + std::array + devicePosesStanding; vr::VRSystem()->GetDeviceToAbsoluteTrackingPose( vr::TrackingUniverseStanding, 0.0f, - devicePosesStanding, + devicePosesStanding.data(), vr::k_unMaxTrackedDeviceCount ); - vr::HmdMatrix34_t hmdStanding + vr::HmdMatrix34_t const hmdStanding = devicePosesStanding[0].mDeviceToAbsoluteTracking; qInfo() << ""; @@ -176,15 +177,16 @@ void MoveCenterTabController::outputLogPoses() qInfo() << "HMD POSE (standing universe)"; outputLogHmdMatrix( hmdStanding ); - vr::TrackedDevicePose_t devicePosesSeated[vr::k_unMaxTrackedDeviceCount]; + std::array + devicePosesSeated; vr::VRSystem()->GetDeviceToAbsoluteTrackingPose( vr::TrackingUniverseSeated, 0.0f, - devicePosesSeated, + devicePosesSeated.data(), vr::k_unMaxTrackedDeviceCount ); - vr::HmdMatrix34_t hmdSeated + vr::HmdMatrix34_t const hmdSeated = devicePosesSeated[0].mDeviceToAbsoluteTracking; qInfo() << "HMD POSE (seated universe)"; @@ -195,9 +197,9 @@ void MoveCenterTabController::outputLogPoses() auto rightHand = vr::VRSystem()->GetTrackedDeviceIndexForControllerRole( vr::TrackedControllerRole_RightHand ); - vr::HmdMatrix34_t leftHandMatrix + vr::HmdMatrix34_t const leftHandMatrix = devicePosesStanding[leftHand].mDeviceToAbsoluteTracking; - vr::HmdMatrix34_t rightHandMatrix + vr::HmdMatrix34_t const rightHandMatrix = devicePosesStanding[rightHand].mDeviceToAbsoluteTracking; qInfo() << "LEFT Hand Controller Pose (standing universe)"; @@ -224,7 +226,7 @@ void MoveCenterTabController::outputLogPoses() qInfo() << "GetLiveSeatedZeroPoseToRawTrackingPose"; outputLogHmdMatrix( seatedZeroLive ); - vr::HmdMatrix34_t seatedToStandingAbsolute + vr::HmdMatrix34_t const seatedToStandingAbsolute = vr::VRSystem()->GetSeatedZeroPoseToStandingAbsoluteTrackingPose(); qInfo() << "GetSeatedZeroPoseToStandingAbsoluteTrackingPose"; outputLogHmdMatrix( seatedToStandingAbsolute ); @@ -248,14 +250,15 @@ void MoveCenterTabController::outputLogHmdMatrix( vr::HmdMatrix34_t hmdMatrix ) qInfo() << hmdMatrix.m[2][0] << "\t\t\t" << hmdMatrix.m[2][1] << "\t\t\t" << hmdMatrix.m[2][2] << "\t\t\t" << hmdMatrix.m[2][3]; - float atan2Yaw = std::atan2( hmdMatrix.m[0][2], hmdMatrix.m[2][2] ); + float const atan2Yaw = std::atan2( hmdMatrix.m[0][2], hmdMatrix.m[2][2] ); qInfo() << "atan2 Yaw Calculation: " << atan2Yaw << "radians " << ( ( static_cast( atan2Yaw ) * k_radiansToCentidegrees ) / 100 ) << "degrees"; - vr::HmdQuaternion_t hmdQuat = quaternion::fromHmdMatrix34( hmdMatrix ); - double hmdQuatYaw = quaternion::getYaw( hmdQuat ); + vr::HmdQuaternion_t const hmdQuat + = quaternion::fromHmdMatrix34( hmdMatrix ); + double const hmdQuatYaw = quaternion::getYaw( hmdQuat ); qInfo() << "Quaternion Yaw Calculation: " << hmdQuatYaw << "radians " << ( ( hmdQuatYaw * k_radiansToCentidegrees ) / 100 ) << "degrees"; qInfo() << ""; @@ -348,11 +351,11 @@ void MoveCenterTabController::setRotation( int value, bool notify ) return; } - double angle = ( value - m_rotation ) * k_centidegreesToRadians; + double const angle = ( value - m_rotation ) * k_centidegreesToRadians; // Get hmd pose matrix. - vr::TrackedDevicePose_t - devicePosesForRot[vr::k_unMaxTrackedDeviceCount]; + std::array + devicePosesForRot; // source must be current universe if ( m_trackingUniverse == vr::TrackingUniverseSeated ) @@ -360,7 +363,7 @@ void MoveCenterTabController::setRotation( int value, bool notify ) vr::VRSystem()->GetDeviceToAbsoluteTrackingPose( vr::TrackingUniverseSeated, 0.0f, - devicePosesForRot, + devicePosesForRot.data(), vr::k_unMaxTrackedDeviceCount ); } else @@ -368,23 +371,25 @@ void MoveCenterTabController::setRotation( int value, bool notify ) vr::VRSystem()->GetDeviceToAbsoluteTrackingPose( vr::TrackingUniverseStanding, 0.0f, - devicePosesForRot, + devicePosesForRot.data(), vr::k_unMaxTrackedDeviceCount ); } - vr::HmdMatrix34_t oldHmdPos + vr::HmdMatrix34_t const oldHmdPos = devicePosesForRot[0].mDeviceToAbsoluteTracking; // Set up xyz coordinate values from pose matrix. - double oldHmdXyz[3] = { static_cast( oldHmdPos.m[0][3] ), - static_cast( oldHmdPos.m[1][3] ), - static_cast( oldHmdPos.m[2][3] ) }; - double newHmdXyz[3] = { static_cast( oldHmdPos.m[0][3] ), - static_cast( oldHmdPos.m[1][3] ), - static_cast( oldHmdPos.m[2][3] ) }; + std::array oldHmdXyz + = { static_cast( oldHmdPos.m[0][3] ), + static_cast( oldHmdPos.m[1][3] ), + static_cast( oldHmdPos.m[2][3] ) }; + std::array newHmdXyz + = { static_cast( oldHmdPos.m[0][3] ), + static_cast( oldHmdPos.m[1][3] ), + static_cast( oldHmdPos.m[2][3] ) }; // Convert oldHmdXyz into un-rotated coordinates. - double oldAngle = -m_rotation * k_centidegreesToRadians; + double const oldAngle = -m_rotation * k_centidegreesToRadians; rotateCoordinates( oldHmdXyz, oldAngle ); // Set newHmdXyz to have additional rotation from incoming angle change. @@ -392,7 +397,7 @@ void MoveCenterTabController::setRotation( int value, bool notify ) // find difference in x,z offset due to incoming angle change // (coordinates are in un-rotated axis). - double hmdRotDiff[3] + std::array const hmdRotDiff = { oldHmdXyz[0] - newHmdXyz[0], 0, oldHmdXyz[2] - newHmdXyz[2] }; m_rotation = value; @@ -720,7 +725,7 @@ void MoveCenterTabController::setDragMult( float value, bool notify ) valuesubmit = 20.0; } settings::setSetting( settings::DoubleSetting::PLAYSPACE_dragMult, - static_cast( valuesubmit ) ); + valuesubmit ); if ( notify ) { @@ -948,6 +953,8 @@ void MoveCenterTabController::incomingZeroReset() } } +// TODO: remove when fixed +// NOLINTNEXTLINE(misc-no-recursion) void MoveCenterTabController::reset() { // DO NOT attempt to apply autosaved profile on reset, as it is triggered by @@ -986,7 +993,7 @@ void MoveCenterTabController::reset() // For Center Marker // Needs to happen after apply chaperone - if ( parent->m_chaperoneTabController.m_centerMarkerOverlayNeedsUpdate ) + if ( parent->m_chaperoneTabController.centerMarkerOverlayNeedsUpdate() ) { m_offsetmatrix = utils::k_forwardUpMatrix; if ( m_trackingUniverse == vr::TrackingUniverseSeated ) @@ -1020,9 +1027,9 @@ void MoveCenterTabController::zeroOffsets() vr::HmdMatrix34_t currentCenter; vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( ¤tCenter ); - double currentCenterYaw = static_cast( + double const currentCenterYaw = static_cast( std::atan2( currentCenter.m[0][2], currentCenter.m[2][2] ) ); - double currentCenterXyz[3] + std::array currentCenterXyz = { static_cast( currentCenter.m[0][3] ), static_cast( currentCenter.m[1][3] ), static_cast( currentCenter.m[2][3] ) }; @@ -1173,7 +1180,7 @@ void MoveCenterTabController::resetHmdYawTotal() m_hmdYawTurnCount = 0; } -void MoveCenterTabController::clampVelocity( double* velocity ) +void MoveCenterTabController::clampVelocity( std::array velocity ) { for ( int i = 0; i < 3; i++ ) { @@ -1202,11 +1209,11 @@ void MoveCenterTabController::updateChaperoneResetData() unsigned currentQuadCount = 0; vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo( nullptr, ¤tQuadCount ); - m_collisionBoundsForReset = new vr::HmdQuad_t[currentQuadCount]; + m_collisionBoundsForReset.clear(); + m_collisionBoundsForReset.resize( currentQuadCount ); // m_collisionBoundsForOffset = new vr::HmdQuad_t[currentQuadCount]; - m_collisionBoundsCountForReset = currentQuadCount; vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo( - m_collisionBoundsForReset, ¤tQuadCount ); + m_collisionBoundsForReset.data(), ¤tQuadCount ); vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( &m_universeCenterForReset ); @@ -1228,10 +1235,11 @@ void MoveCenterTabController::updateChaperoneResetData() void MoveCenterTabController::applyChaperoneResetData() { - if ( m_collisionBoundsCountForReset > 0 ) + if ( !m_collisionBoundsForReset.empty() ) { vr::VRChaperoneSetup()->SetWorkingCollisionBoundsInfo( - m_collisionBoundsForReset, m_collisionBoundsCountForReset ); + m_collisionBoundsForReset.data(), + static_cast( m_collisionBoundsForReset.size() ) ); } // zeroOffsets(); // These commands set play area as centered which is un-desirable @@ -1253,14 +1261,14 @@ void MoveCenterTabController::applyChaperoneResetData() void MoveCenterTabController::setBoundsBasisHeight( float newHeight ) { - if ( m_collisionBoundsCountForReset > 0 ) + if ( !m_collisionBoundsForReset.empty() ) { - for ( unsigned b = 0; b < m_collisionBoundsCountForReset; b++ ) + for ( auto& bounds : m_collisionBoundsForReset ) { - m_collisionBoundsForReset[b].vCorners[0].v[1] = 0.0; - m_collisionBoundsForReset[b].vCorners[1].v[1] = newHeight; - m_collisionBoundsForReset[b].vCorners[2].v[1] = newHeight; - m_collisionBoundsForReset[b].vCorners[3].v[1] = 0.0; + bounds.vCorners[0].v[1] = 0.0; + bounds.vCorners[1].v[1] = newHeight; + bounds.vCorners[2].v[1] = newHeight; + bounds.vCorners[3].v[1] = 0.0; } // updateCollisionBoundsForOffset(); @@ -1271,24 +1279,15 @@ void MoveCenterTabController::setBoundsBasisHeight( float newHeight ) float MoveCenterTabController::getBoundsBasisMaxY() { float result = FP_NAN; - if ( m_collisionBoundsCountForReset > 0 ) + if ( !m_collisionBoundsForReset.empty() ) { - for ( unsigned b = 0; b < m_collisionBoundsCountForReset; b++ ) + for ( auto& bounds : m_collisionBoundsForReset ) { - int ci; - if ( m_collisionBoundsForReset[b].vCorners[1].v[1] - >= m_collisionBoundsForReset[b].vCorners[2].v[1] ) - { - ci = 1; - } - else - { - ci = 2; - } - if ( std::isnan( result ) - || result < m_collisionBoundsForReset[b].vCorners[ci].v[1] ) + int const cindex + = bounds.vCorners[1].v[1] >= bounds.vCorners[2].v[1] ? 1 : 2; + if ( std::isnan( result ) || result < bounds.vCorners[cindex].v[1] ) { - result = m_collisionBoundsForReset[b].vCorners[ci].v[1]; + result = bounds.vCorners[cindex].v[1]; } } } @@ -2078,13 +2077,13 @@ void MoveCenterTabController::updateHmdRotationCounter( } // Get hmd pose matrix (in rotated coordinates) - vr::HmdMatrix34_t hmdMatrix = hmdPose.mDeviceToAbsoluteTracking; + vr::HmdMatrix34_t const hmdMatrix = hmdPose.mDeviceToAbsoluteTracking; // Set up (un)rotation matrix vr::HmdMatrix34_t hmdMatrixRotMat; vr::HmdMatrix34_t hmdMatrixAbsolute; utils::initRotationMatrix( - hmdMatrixRotMat, 1, static_cast( angle ) ); + hmdMatrixRotMat, utils::MatrixAxis_Y, static_cast( angle ) ); // Get hmdMatrixAbsolute in un-rotated coordinates. utils::matMul33( hmdMatrixAbsolute, hmdMatrixRotMat, hmdMatrix ); @@ -2101,7 +2100,7 @@ void MoveCenterTabController::updateHmdRotationCounter( return; } - double hmdYawCurrent = quaternion::getYaw( m_hmdQuaternion ); + double const hmdYawCurrent = quaternion::getYaw( m_hmdQuaternion ); // double hmdPitchCurrent = quaternion::getPitch( m_hmdQuaternion ); // double hmdRollCurrent = quaternion::getRoll( m_hmdQuaternion ); @@ -2119,7 +2118,7 @@ void MoveCenterTabController::updateHmdRotationCounter( if ( std::abs( m_hmdYawOld - hmdYawCurrent ) > M_PI ) { // Checks if the HMD is inverted, and skips if it is - bool isInverted = ( hmdMatrixAbsolute.m[1][1] < 0 ); + bool const isInverted = ( hmdMatrixAbsolute.m[1][1] < 0 ); if ( !isInverted ) { if ( m_hmdYawOld >= 0 ) @@ -2177,18 +2176,18 @@ void MoveCenterTabController::updateHandDrag( return; } - vr::TrackedDevicePose_t* movePose; + vr::TrackedDevicePose_t* movePose = nullptr; movePose = devicePoses + moveHandId; if ( m_seatedModeDetected ) { - vr::TrackedDevicePose_t - seatedDevicePoses[vr::k_unMaxTrackedDeviceCount]; + std::array + seatedDevicePoses; vr::VRSystem()->GetDeviceToAbsoluteTrackingPose( vr::TrackingUniverseSeated, 0.0f, - seatedDevicePoses, + seatedDevicePoses.data(), vr::k_unMaxTrackedDeviceCount ); - movePose = seatedDevicePoses + moveHandId; + movePose = &seatedDevicePoses[moveHandId]; } if ( !movePose->bPoseIsValid || !movePose->bDeviceIsConnected @@ -2198,14 +2197,14 @@ void MoveCenterTabController::updateHandDrag( return; } - double relativeControllerPosition[] = { + std::array relativeControllerPosition = { static_cast( movePose->mDeviceToAbsoluteTracking.m[0][3] ), static_cast( movePose->mDeviceToAbsoluteTracking.m[1][3] ), static_cast( movePose->mDeviceToAbsoluteTracking.m[2][3] ) }; rotateCoordinates( relativeControllerPosition, -angle ); - float absoluteControllerPosition[] = { + std::array const absoluteControllerPosition = { static_cast( relativeControllerPosition[0] ) + m_offsetX, static_cast( relativeControllerPosition[1] ) + m_offsetY, static_cast( relativeControllerPosition[2] ) + m_offsetZ, @@ -2213,7 +2212,7 @@ void MoveCenterTabController::updateHandDrag( if ( m_lastMoveHand == m_activeDragHand ) { - double diff[3] = { + std::array diff = { static_cast( absoluteControllerPosition[0] - m_lastControllerPosition[0] ), static_cast( absoluteControllerPosition[1] @@ -2251,7 +2250,7 @@ void MoveCenterTabController::updateHandDrag( m_offsetZ += static_cast( diff[2] ); } - double secondsSinceLastDragUpdate + double const secondsSinceLastDragUpdate = std::chrono::duration( std::chrono::steady_clock::now() - m_lastDragUpdateTimePoint ) .count(); @@ -2296,7 +2295,7 @@ void MoveCenterTabController::updateHandTurn( } // Get hand's rotation. // handMatrix is in rotated coordinates. - vr::HmdMatrix34_t handMatrix = rotatePose->mDeviceToAbsoluteTracking; + vr::HmdMatrix34_t const handMatrix = rotatePose->mDeviceToAbsoluteTracking; // We need un-rotated coordinates for valid comparison between // handQuaternion and lastHandQuaternion. Set up (un)rotation @@ -2304,7 +2303,7 @@ void MoveCenterTabController::updateHandTurn( vr::HmdMatrix34_t handMatrixRotMat; vr::HmdMatrix34_t handMatrixAbsolute; utils::initRotationMatrix( - handMatrixRotMat, 1, static_cast( angle ) ); + handMatrixRotMat, utils::MatrixAxis_Y, static_cast( angle ) ); // Get handMatrixAbsolute in un-rotated coordinates. utils::matMul33( handMatrixAbsolute, handMatrixRotMat, handMatrix ); @@ -2326,12 +2325,12 @@ void MoveCenterTabController::updateHandTurn( { // Construct a quaternion representing difference // between old hand and new hand. - vr::HmdQuaternion_t handDiffQuaternion = quaternion::multiply( + vr::HmdQuaternion_t const handDiffQuaternion = quaternion::multiply( m_handQuaternion, quaternion::conjugate( m_lastHandQuaternion ) ); // Calculate yaw from quaternion. - double handYawDiff = quaternion::getYaw( handDiffQuaternion ); + double const handYawDiff = quaternion::getYaw( handDiffQuaternion ); int newRotationAngleDeg = static_cast( round( handYawDiff * k_radiansToCentidegrees ) + m_rotation ); @@ -2360,7 +2359,7 @@ void MoveCenterTabController::updateGravity() { currentGravity *= -1.0f; } - double secondsSinceLastGravityUpdate + double const secondsSinceLastGravityUpdate = std::chrono::duration( std::chrono::steady_clock::now() - m_lastGravityUpdateTimePoint ) .count(); @@ -2445,7 +2444,7 @@ void MoveCenterTabController::updateGravity() { // get ratio of how much from y velocity applied to overcome y // offset and get down to ground. - double ratioVelocityScaledByTouchdown + double const ratioVelocityScaledByTouchdown = 1 - ( ( static_cast( m_offsetY - m_gravityFloor ) + ( m_velocity[1] * secondsSinceLastGravityUpdate ) ) @@ -2500,6 +2499,8 @@ void MoveCenterTabController::updateGravity() m_velocity[2] = 0.0; } +// TODO: remove when fixed +// NOLINTNEXTLINE(misc-no-recursion) void MoveCenterTabController::updateSpace( bool forceUpdate ) { // Do nothing if all offsets and rotation are still the same... @@ -2529,7 +2530,7 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) vr::HmdMatrix34_t rotationMatrix; utils::initRotationMatrix( rotationMatrix, - 1, + utils::MatrixAxis_Y, static_cast( m_rotation * k_centidegreesToRadians ) ); utils::matMul33( offsetUniverseCenter, rotationMatrix, m_universeCenterForReset ); @@ -2562,10 +2563,10 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) // check if we just pushed offsetUniverseCenter out of bounds (40km) // (we reuse offsetUniverseCenterYaw to rotate the chaperone also) - double offsetUniverseCenterYaw = static_cast( std::atan2( + double const offsetUniverseCenterYaw = static_cast( std::atan2( offsetUniverseCenter.m[0][2], offsetUniverseCenter.m[2][2] ) ); - double offsetUniverseCenterXyz[3] + std::array offsetUniverseCenterXyz = { static_cast( offsetUniverseCenter.m[0][3] ), static_cast( offsetUniverseCenter.m[1][3] ), static_cast( offsetUniverseCenter.m[2][3] ) }; @@ -2667,10 +2668,11 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) } // Center Marker for playspace. - if ( parent->m_chaperoneTabController.m_centerMarkerOverlayNeedsUpdate ) + if ( parent->m_chaperoneTabController.centerMarkerOverlayNeedsUpdate() ) { // Set Unrotated Coordinates - float universePlayCenterTempCoords[3] = { 0.0f, 0.0f, 0.0f }; + std::array universePlayCenterTempCoords + = { 0.0f, 0.0f, 0.0f }; universePlayCenterTempCoords[0] -= offsetUniverseCenter.m[0][3] - m_universeCenterForReset.m[0][3]; universePlayCenterTempCoords[1] @@ -2686,7 +2688,7 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) vr::HmdMatrix34_t rotMatrix; utils::initRotationMatrix( rotMatrix, - 1, + utils::MatrixAxis_Y, static_cast( -( ( m_rotation * k_centidegreesToRadians ) + offsetUniverseCenterYaw ) ) ); @@ -2715,7 +2717,7 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) vr::VRChaperoneSetup()->ShowWorkingSetPreview(); - if ( m_collisionBoundsCountForReset > 0 ) + if ( !m_collisionBoundsForReset.empty() ) { parent->chaperoneUtils().loadChaperoneData( false ); } @@ -2750,7 +2752,7 @@ void MoveCenterTabController::eventLoopTick( reset(); vr::VRChaperoneSetup()->RevertWorkingCopy(); } - setTrackingUniverse( int( universe ) ); + setTrackingUniverse( static_cast( universe ) ); // TODO set to allow. return; } @@ -2786,10 +2788,10 @@ void MoveCenterTabController::eventLoopTick( } else { - setTrackingUniverse( int( universe ) ); + setTrackingUniverse( static_cast( universe ) ); // get current space rotation in radians - double angle = m_rotation * k_centidegreesToRadians; + double const angle = m_rotation * k_centidegreesToRadians; // hmd rotations stats counting doesn't need to be smooth, so we // skip some frames for performance diff --git a/src/tabcontrollers/MoveCenterTabController.h b/src/tabcontrollers/MoveCenterTabController.h index 2606a190..267bac6a 100644 --- a/src/tabcontrollers/MoveCenterTabController.h +++ b/src/tabcontrollers/MoveCenterTabController.h @@ -6,7 +6,6 @@ #include #include #include "../utils/Matrix.h" -#include "../utils/FrameRateUtils.h" #include "../settings/settings_object.h" class QQuickWindow; @@ -32,32 +31,34 @@ class OverlayController; struct OffsetProfile : settings::ISettingsObject { + // NOLINTBEGIN(misc-non-private-member-variables-in-classes) std::string profileName; float offsetX = 0.0f; float offsetY = 0.0f; float offsetZ = 0.0f; int rotation = 0; + // NOLINTEND(misc-non-private-member-variables-in-classes) - virtual std::string settingsName() const override + [[nodiscard]] std::string settingsName() const override { return "MoveCenterTabController::OffsetProfile"; } - virtual settings::SettingsObjectData saveSettings() const override + [[nodiscard]] settings::SettingsObjectData saveSettings() const override { - settings::SettingsObjectData o; + settings::SettingsObjectData sod; - o.addValue( profileName ); - o.addValue( static_cast( offsetX ) ); - o.addValue( static_cast( offsetY ) ); - o.addValue( static_cast( offsetZ ) ); + sod.addValue( profileName ); + sod.addValue( static_cast( offsetX ) ); + sod.addValue( static_cast( offsetY ) ); + sod.addValue( static_cast( offsetZ ) ); - o.addValue( rotation ); + sod.addValue( rotation ); - return o; + return sod; } - virtual void loadSettings( settings::SettingsObjectData& obj ) override + void loadSettings( settings::SettingsObjectData& obj ) override { profileName = ( obj.getNextValueOrDefault( "" ) ); offsetX = static_cast( obj.getNextValueOrDefault( 0.0 ) ); @@ -150,7 +151,7 @@ class MoveCenterTabController : public QObject bool m_moveShortcutRightPressed = false; bool m_moveShortcutLeftPressed = false; vr::TrackedDeviceIndex_t m_activeMoveController; - float m_lastControllerPosition[3]; + std::array m_lastControllerPosition; bool m_heightToggle = false; float m_gravityFloor = 0.0f; bool m_ignoreChaperoneState = false; @@ -201,11 +202,10 @@ class MoveCenterTabController : public QObject // Matrix used For Center Marker vr::HmdMatrix34_t m_offsetmatrix = utils::k_forwardUpMatrix; - double m_velocity[3] = { 0.0, 0.0, 0.0 }; + std::array m_velocity = { 0.0, 0.0, 0.0 }; std::chrono::steady_clock::time_point m_lastGravityUpdateTimePoint; std::chrono::steady_clock::time_point m_lastDragUpdateTimePoint; - vr::HmdQuad_t* m_collisionBoundsForReset; - uint32_t m_collisionBoundsCountForReset = 0; + std::vector m_collisionBoundsForReset; vr::HmdMatrix34_t m_universeCenterForReset = { { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, @@ -223,7 +223,7 @@ class MoveCenterTabController : public QObject void updateHandTurn( vr::TrackedDevicePose_t* devicePoses, double angle ); void updateGravity(); void updateSpace( bool forceUpdate = false ); - void clampVelocity( double* velocity ); + void clampVelocity( std::array velocity ); void applyChaperoneResetData(); // void saveUncommittedChaperone(); void outputLogHmdMatrix( vr::HmdMatrix34_t hmdMatrix ); @@ -237,36 +237,36 @@ class MoveCenterTabController : public QObject void eventLoopTick( vr::ETrackingUniverseOrigin universe, vr::TrackedDevicePose_t* devicePoses ); - float offsetX() const; - float offsetY() const; - float offsetZ() const; - int rotation() const; - int tempRotation() const; - int snapTurnAngle() const; - int smoothTurnRate() const; - int frictionPercent() const; - bool moveShortcutRight() const; - bool moveShortcutLeft() const; - bool turnBindRight() const; - bool turnBindLeft() const; - bool dragBounds() const; - bool turnBounds() const; - int dragComfortFactor() const; - int turnComfortFactor() const; - bool heightToggle() const; - float heightToggleOffset() const; - float gravityStrength() const; - float flingStrength() const; - float dragMult() const; - bool gravityActive() const; - bool momentumSave() const; - bool lockXToggle() const; - bool lockYToggle() const; - bool lockZToggle() const; - bool showLogMatricesButton() const; + [[nodiscard]] float offsetX() const; + [[nodiscard]] float offsetY() const; + [[nodiscard]] float offsetZ() const; + [[nodiscard]] int rotation() const; + [[nodiscard]] int tempRotation() const; + [[nodiscard]] int snapTurnAngle() const; + [[nodiscard]] int smoothTurnRate() const; + [[nodiscard]] int frictionPercent() const; + [[nodiscard]] bool moveShortcutRight() const; + [[nodiscard]] bool moveShortcutLeft() const; + [[nodiscard]] bool turnBindRight() const; + [[nodiscard]] bool turnBindLeft() const; + [[nodiscard]] bool dragBounds() const; + [[nodiscard]] bool turnBounds() const; + [[nodiscard]] int dragComfortFactor() const; + [[nodiscard]] int turnComfortFactor() const; + [[nodiscard]] bool heightToggle() const; + [[nodiscard]] float heightToggleOffset() const; + [[nodiscard]] float gravityStrength() const; + [[nodiscard]] float flingStrength() const; + [[nodiscard]] float dragMult() const; + [[nodiscard]] bool gravityActive() const; + [[nodiscard]] bool momentumSave() const; + [[nodiscard]] bool lockXToggle() const; + [[nodiscard]] bool lockYToggle() const; + [[nodiscard]] bool lockZToggle() const; + [[nodiscard]] bool showLogMatricesButton() const; // bool allowExternalEdits() const; - bool universeCenteredRotation() const; - bool isInitComplete() const; + [[nodiscard]] bool universeCenteredRotation() const; + [[nodiscard]] bool isInitComplete() const; double getHmdYawTotal(); void resetHmdYawTotal(); void incomingZeroReset(); @@ -280,7 +280,7 @@ class MoveCenterTabController : public QObject Q_INVOKABLE unsigned getOffsetProfileCount(); Q_INVOKABLE QString getOffsetProfileName( unsigned index ); - void addOffset( float offset[3] ); + void addOffset( std::array offset ); // actions: void leftHandSpaceDrag( bool leftHandDragActive ); @@ -306,8 +306,7 @@ class MoveCenterTabController : public QObject void yAxisLockToggle( bool yAxisLockToggleJustPressed ); void zAxisLockToggle( bool zAxisLockToggleJustPressed ); -public slots: - int trackingUniverse() const; + [[nodiscard]] int trackingUniverse() const; void setTrackingUniverse( int value, bool notify = true ); void setOffsetX( float value, bool notify = true ); diff --git a/src/tabcontrollers/RotationTabController.cpp b/src/tabcontrollers/RotationTabController.cpp index 8e31aa5c..a1c7a519 100644 --- a/src/tabcontrollers/RotationTabController.cpp +++ b/src/tabcontrollers/RotationTabController.cpp @@ -4,8 +4,8 @@ #include #include "../overlaycontroller.h" #include "../settings/settings.h" -#include "../utils/Matrix.h" #include "../quaternion/quaternion.h" +#include "openvr/ovr_overlay_wrapper.h" #include // application namespace @@ -28,7 +28,7 @@ void RotationTabController::initStage2( OverlayController* var_parent ) const auto overlayError = vr::VROverlay()->CreateOverlay( autoturnOverlayKey.c_str(), autoturnOverlayKey.c_str(), - &m_autoturnValues.overlayHandle ); + &m_overlayHandle ); if ( overlayError != vr::VROverlayError_None ) { qCritical() << "Could not create autoturn notification overlay: " @@ -39,22 +39,20 @@ void RotationTabController::initStage2( OverlayController* var_parent ) return; } - m_autoturnValues.autoturnImg.reset( - new QImage( QString( ":/rotation/autoturn.png" ) ) ); - m_autoturnValues.noautoturnImg.reset( + m_autoturnImg.reset( new QImage( QString( ":/rotation/autoturn.png" ) ) ); + m_noautoturnImg.reset( new QImage( QString( ":/rotation/noautoturn.png" ) ) ); - ovr_overlay_wrapper::setOverlayFromQImage( m_autoturnValues.overlayHandle, - *m_autoturnValues.autoturnImg ); + ovr_overlay_wrapper::setOverlayFromQImage( m_overlayHandle, + *m_autoturnImg ); - vr::VROverlay()->SetOverlayWidthInMeters( m_autoturnValues.overlayHandle, - 0.02f ); - vr::HmdMatrix34_t notificationTransform + vr::VROverlay()->SetOverlayWidthInMeters( m_overlayHandle, 0.02f ); + vr::HmdMatrix34_t const notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.12f }, { 0.0f, 1.0f, 0.0f, 0.08f }, { 0.0f, 0.0f, 1.0f, -0.3f } } }; vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( - m_autoturnValues.overlayHandle, + m_overlayHandle, vr::k_unTrackedDeviceIndex_Hmd, ¬ificationTransform ); @@ -67,7 +65,7 @@ void RotationTabController::eventLoopTick( if ( devicePoses ) { m_isHMDActive = false; - std::lock_guard lock( + std::lock_guard const lock( parent->chaperoneUtils().mutex() ); auto& poseHmd = devicePoses[vr::k_unTrackedDeviceIndex_Hmd]; @@ -128,7 +126,7 @@ void RotationTabController::eventLoopTick( } else { - float pct + float const pct = std::min( 1.0f, 3.0f - static_cast( count ) / 500.0f ); vr::VROverlay()->SetOverlayAlpha( getNotificationOverlayHandle(), pct ); @@ -168,18 +166,18 @@ void RotationTabController::doViewRatchetting( = quaternion::fromHmdMatrix34( poseHmd.mDeviceToAbsoluteTracking ); // Get HMD raw yaw - double hmdYaw = quaternion::getYaw( hmdQuaternion ); + double const hmdYaw = quaternion::getYaw( hmdQuaternion ); // Get angle between HMD position and nearest point on // wall - double hmdPositionToWallYaw = static_cast( + double const hmdPositionToWallYaw = static_cast( std::atan2( nearestWall.nearestPoint.v[0] - poseHmd.mDeviceToAbsoluteTracking.m[0][3], nearestWall.nearestPoint.v[2] - poseHmd.mDeviceToAbsoluteTracking.m[2][3] ) ); // Get angle between HMD and wall - double hmdToWallYaw + double const hmdToWallYaw = reduceAngle<>( hmdYaw - hmdPositionToWallYaw, -M_PI, M_PI ); do @@ -200,7 +198,7 @@ void RotationTabController::doViewRatchetting( break; } // Magnify that change - double delta_degrees + double const delta_degrees = reduceAngle<>( hmdToWallYaw - m_ratchettingLastHmdRotation, -M_PI, M_PI ) * viewRatchettingPercent(); @@ -249,23 +247,23 @@ void RotationTabController::doVestibularMotion( poseHmd.mDeviceToAbsoluteTracking ); // Get HMD raw yaw - double hmdYaw = quaternion::getYaw( hmdQuaternion ); + double const hmdYaw = quaternion::getYaw( hmdQuaternion ); // Get angle between HMD position and nearest point on // wall - double hmdPositionToWallYaw = static_cast( + double const hmdPositionToWallYaw = static_cast( std::atan2( poseHmd.mDeviceToAbsoluteTracking.m[0][3] - nearestWall->nearestPoint.v[0], poseHmd.mDeviceToAbsoluteTracking.m[2][3] - nearestWall->nearestPoint.v[2] ) ); // Get angle between HMD and wall - double hmdToWallYaw + double const hmdToWallYaw = reduceAngle<>( hmdYaw - hmdPositionToWallYaw, -M_PI, M_PI ); - bool turnLeft = hmdToWallYaw > 0.0; + bool const turnLeft = hmdToWallYaw > 0.0; // Only turn if moving forward - double hmdMovementDirection = static_cast( + double const hmdMovementDirection = static_cast( std::atan2( m_autoTurnLastHmdUpdate.m[0][3] - poseHmd.mDeviceToAbsoluteTracking.m[0][3], m_autoTurnLastHmdUpdate.m[2][3] @@ -279,7 +277,7 @@ void RotationTabController::doVestibularMotion( // Get the distance between previous and current // position - double distanceChange = static_cast( + double const distanceChange = static_cast( std::hypot( poseHmd.mDeviceToAbsoluteTracking.m[0][3] - m_autoTurnLastHmdUpdate.m[0][3], poseHmd.mDeviceToAbsoluteTracking.m[2][3] @@ -287,16 +285,16 @@ void RotationTabController::doVestibularMotion( // Get the arc length between the previous point and current point // 2 sin-1( (d/2)/r ) (in radians) - double arcLength = 2 - * std::asin( ( distanceChange / 2 ) - / vestibularMotionRadius() ); + double const arcLength = 2 + * std::asin( ( distanceChange / 2 ) + / vestibularMotionRadius() ); if ( std::isnan( arcLength ) ) { break; } - double rotationAmount = arcLength * ( turnLeft ? 1 : -1 ); - int newRotationAngle = reduceAngle<>( + double const rotationAmount = arcLength * ( turnLeft ? 1 : -1 ); + int const newRotationAngle = reduceAngle<>( parent->m_moveCenterTabController.rotation() + static_cast( rotationAmount * k_radiansToCentidegrees ), @@ -335,7 +333,7 @@ void RotationTabController::doAutoTurn( == AutoTurnModes::LINEAR_SMOOTH_TURN && m_autoTurnLinearSmoothTurnRemaining != 0 ) { - double deltaSeconds + double const deltaSeconds = FrameRates::toDoubleSeconds( m_estimatedFrameRate ); auto miniDeltaAngle = static_cast( std::abs( @@ -346,11 +344,10 @@ void RotationTabController::doAutoTurn( { miniDeltaAngle = m_autoTurnLinearSmoothTurnRemaining; } - int newRotationAngleDeg - = reduceAngle<>( parent->m_moveCenterTabController.rotation() - + static_cast( miniDeltaAngle ), - 0, - 36000 ); + int const newRotationAngleDeg = reduceAngle<>( + parent->m_moveCenterTabController.rotation() + miniDeltaAngle, + 0, + 36000 ); parent->m_moveCenterTabController.setRotation( newRotationAngleDeg ); @@ -369,18 +366,18 @@ void RotationTabController::doAutoTurn( poseHmd.mDeviceToAbsoluteTracking ); // Get HMD raw yaw - double hmdYaw = quaternion::getYaw( hmdQuaternion ); + double const hmdYaw = quaternion::getYaw( hmdQuaternion ); // Get angle between HMD position and nearest point on // wall - double hmdPositionToWallYaw = static_cast( + double const hmdPositionToWallYaw = static_cast( std::atan2( poseHmd.mDeviceToAbsoluteTracking.m[0][3] - chaperoneQuad.nearestPoint.v[0], poseHmd.mDeviceToAbsoluteTracking.m[2][3] - chaperoneQuad.nearestPoint.v[2] ) ); // Get angle between HMD and wall - double hmdToWallYaw = reduceAngle<>( + double const hmdToWallYaw = reduceAngle<>( hmdYaw - hmdPositionToWallYaw, -M_PI, M_PI ); do @@ -396,7 +393,7 @@ void RotationTabController::doAutoTurn( // If the closest corner shares a wall with the last // wall we turned at, turn relative to that corner - bool cornerShared + bool const cornerShared = m_autoTurnWallActive[circularIndex( i, true, chaperoneDistances.size() )] || m_autoTurnWallActive[circularIndex( @@ -468,10 +465,11 @@ void RotationTabController::doAutoTurn( = parent->chaperoneUtils().getCorner( circularIndex( middleCornerIdx, !turnLeft, cornerCnt ) ); - double newWallAngle = static_cast( std::atan2( - middleCorner.v[0] - newWallCorner.v[0], - middleCorner.v[2] - newWallCorner.v[2] ) ); - double touchingWallAngle + double const newWallAngle + = static_cast( std::atan2( + middleCorner.v[0] - newWallCorner.v[0], + middleCorner.v[2] - newWallCorner.v[2] ) ); + double const touchingWallAngle = static_cast( std::atan2( middleCorner.v[0] - touchingWallCorner.v[0], middleCorner.v[2] - touchingWallCorner.v[2] ) ); @@ -667,14 +665,13 @@ void RotationTabController::setAutoTurnEnabled( bool value, bool notify ) { if ( !value ) { - ovr_overlay_wrapper::setOverlayFromQImage( - m_autoturnValues.overlayHandle, - *m_autoturnValues.noautoturnImg ); + ovr_overlay_wrapper::setOverlayFromQImage( m_overlayHandle, + *m_noautoturnImg ); } else { - ovr_overlay_wrapper::setOverlayFromQImage( - m_autoturnValues.overlayHandle, *m_autoturnValues.autoturnImg ); + ovr_overlay_wrapper::setOverlayFromQImage( m_overlayHandle, + *m_autoturnImg ); } vr::VROverlay()->SetOverlayAlpha( getNotificationOverlayHandle(), diff --git a/src/tabcontrollers/RotationTabController.h b/src/tabcontrollers/RotationTabController.h index ca20fe31..73b13a31 100644 --- a/src/tabcontrollers/RotationTabController.h +++ b/src/tabcontrollers/RotationTabController.h @@ -4,13 +4,9 @@ #include #include #include -#include #include -#include #include -#include "../utils/FrameRateUtils.h" #include "../utils/ChaperoneUtils.h" -#include "../settings/settings_object.h" #include "MoveCenterTabController.h" class QQuickWindow; @@ -97,16 +93,13 @@ class RotationTabController : public QObject private: OverlayController* parent; - struct - { - vr::VROverlayHandle_t overlayHandle = vr::k_ulOverlayHandleInvalid; - std::unique_ptr autoturnImg; - std::unique_ptr noautoturnImg; - } m_autoturnValues; + vr::VROverlayHandle_t m_overlayHandle = vr::k_ulOverlayHandleInvalid; + std::unique_ptr m_autoturnImg; + std::unique_ptr m_noautoturnImg; virtual vr::VROverlayHandle_t getNotificationOverlayHandle() { - return m_autoturnValues.overlayHandle; + return m_overlayHandle; } // Variables @@ -140,24 +133,23 @@ class RotationTabController : public QObject void eventLoopTick( vr::TrackedDevicePose_t* devicePoses ); - float boundsVisibility() const; - - bool autoTurnEnabled() const; - float autoTurnActivationDistance() const; - float autoTurnDeactivationDistance() const; - bool autoTurnUseCornerAngle() const; - bool autoTurnShowNotification() const; - double cordDetangleAngle() const; - double minCordTangle() const; - int autoTurnSpeed() const; - AutoTurnModes autoTurnModeType() const; - int autoTurnMode() const; - bool vestibularMotionEnabled() const; - double vestibularMotionRadius() const; - bool viewRatchettingEnabled() const; - double viewRatchettingPercent() const; - -public slots: + [[nodiscard]] float boundsVisibility() const; + + [[nodiscard]] bool autoTurnEnabled() const; + [[nodiscard]] float autoTurnActivationDistance() const; + [[nodiscard]] float autoTurnDeactivationDistance() const; + [[nodiscard]] bool autoTurnUseCornerAngle() const; + [[nodiscard]] bool autoTurnShowNotification() const; + [[nodiscard]] double cordDetangleAngle() const; + [[nodiscard]] double minCordTangle() const; + [[nodiscard]] int autoTurnSpeed() const; + [[nodiscard]] AutoTurnModes autoTurnModeType() const; + [[nodiscard]] int autoTurnMode() const; + [[nodiscard]] bool vestibularMotionEnabled() const; + [[nodiscard]] double vestibularMotionRadius() const; + [[nodiscard]] bool viewRatchettingEnabled() const; + [[nodiscard]] double viewRatchettingPercent() const; + void setAutoTurnEnabled( bool value, bool notify = true ); void setAutoTurnShowNotification( bool value, bool notify = true ); void setAutoTurnActivationDistance( float value, bool notify = true ); @@ -192,12 +184,16 @@ public slots: // Would be nice to do but the standard doesn't allow // for floating point non-types. +// XXX: clang-tidy on github actions needs this +// NOLINTNEXTLINE(altera-id-dependent-backward-branch) template inline T reduceAngle( T angle, T min, T max ) { + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) while ( angle >= max ) { angle -= ( max - min ); } + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) while ( angle < min ) { angle += ( max - min ); diff --git a/src/tabcontrollers/SettingsTabController.cpp b/src/tabcontrollers/SettingsTabController.cpp index 699b04d0..3702a7da 100644 --- a/src/tabcontrollers/SettingsTabController.cpp +++ b/src/tabcontrollers/SettingsTabController.cpp @@ -4,6 +4,7 @@ #include #include "../overlaycontroller.h" #include "../utils/update_rate.h" +#include "openvr/ovr_settings_wrapper.h" // application namespace namespace advsettings @@ -40,26 +41,26 @@ bool SettingsTabController::autoStartEnabled() const bool SettingsTabController::nativeChaperoneToggle() { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_CollisionBounds_Section, vr::k_pch_CollisionBounds_EnableDriverImport, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return !( p.second ); + return !( pair.second ); } return false; } bool SettingsTabController::oculusSdkToggle() { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_BlockOculusSDKOnAllLaunches_Bool, "" ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return ( p.second ); + return ( pair.second ); } return false; } diff --git a/src/tabcontrollers/SettingsTabController.h b/src/tabcontrollers/SettingsTabController.h index 24ee6850..08239874 100644 --- a/src/tabcontrollers/SettingsTabController.h +++ b/src/tabcontrollers/SettingsTabController.h @@ -2,8 +2,6 @@ #pragma once #include -#include "../utils/FrameRateUtils.h" -#include "../openvr/ovr_settings_wrapper.h" class QQuickWindow; // application namespace @@ -34,11 +32,10 @@ class SettingsTabController : public QObject void dashboardLoopTick(); - bool autoStartEnabled() const; + [[nodiscard]] bool autoStartEnabled() const; bool nativeChaperoneToggle(); bool oculusSdkToggle(); -public slots: void setAutoStartEnabled( bool value, bool notify = true ); void setNativeChaperoneToggle( bool value, bool notify = true ); void setOculusSdkToggle( bool value, bool notify = true ); diff --git a/src/tabcontrollers/StatisticsTabController.cpp b/src/tabcontrollers/StatisticsTabController.cpp index 765a1921..67d1ca17 100644 --- a/src/tabcontrollers/StatisticsTabController.cpp +++ b/src/tabcontrollers/StatisticsTabController.cpp @@ -12,6 +12,7 @@ void StatisticsTabController::initStage2( OverlayController* var_parent ) void StatisticsTabController::eventLoopTick( vr::TrackedDevicePose_t* devicePoses, + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) float leftSpeed, float rightSpeed ) { @@ -29,7 +30,7 @@ void StatisticsTabController::eventLoopTick( } m_cumStats = pStats; - auto& m = devicePoses->mDeviceToAbsoluteTracking.m; + auto& mat = devicePoses->mDeviceToAbsoluteTracking.m; // Hmd Distance // if ( lastPosTimer == 0 ) @@ -44,18 +45,18 @@ void StatisticsTabController::eventLoopTick( } else { - float delta = static_cast( std::sqrt( - std::pow( m[0][3] - lastHmdPos[0], + float const delta = static_cast( std::sqrt( + std::pow( mat[0][3] - lastHmdPos[0], 2 ) /*+ std::pow(m[1][3] - lastHmdPos[1], 2)*/ - + std::pow( m[2][3] - lastHmdPos[2], 2 ) ) ); + + std::pow( mat[2][3] - lastHmdPos[2], 2 ) ) ); if ( delta >= 0.01f ) { m_hmdDistanceMoved += static_cast( delta ); } } - lastHmdPos[0] = m[0][3]; - lastHmdPos[1] = m[1][3]; - lastHmdPos[2] = m[2][3]; + lastHmdPos[0] = mat[0][3]; + lastHmdPos[1] = mat[1][3]; + lastHmdPos[2] = mat[2][3]; } else { @@ -74,7 +75,7 @@ void StatisticsTabController::eventLoopTick( } // HMD Rotation // - double spaceHmdYawTotal + double const spaceHmdYawTotal = parent->m_moveCenterTabController.getHmdYawTotal(); m_hmdRotation = static_cast( spaceHmdYawTotal / ( 2.0 * M_PI ) ); @@ -130,18 +131,16 @@ unsigned StatisticsTabController::timedOut() const float StatisticsTabController::totalReprojectedRatio() const { - float totalFrames = static_cast( + float const totalFrames = static_cast( ( m_cumStats.m_nNumFramePresents - m_totalRatioPresentedOffset ) ); - float reprojectedFrames = static_cast( ( + float const reprojectedFrames = static_cast( ( m_cumStats.m_nNumReprojectedFrames - m_totalRatioReprojectedOffset ) ); if ( totalFrames != 0.0f ) { return reprojectedFrames / totalFrames; } - else - { - return 0.0; - } + + return 0.0; } void StatisticsTabController::statsDistanceResetClicked() diff --git a/src/tabcontrollers/StatisticsTabController.h b/src/tabcontrollers/StatisticsTabController.h index 524b7bd9..a23c84cb 100644 --- a/src/tabcontrollers/StatisticsTabController.h +++ b/src/tabcontrollers/StatisticsTabController.h @@ -33,7 +33,7 @@ class StatisticsTabController : public QObject int64_t rotationCounter = 0; float lastYaw = -1.0f; unsigned lastPosTimer = 0; - float lastHmdPos[3]; + std::array lastHmdPos; bool lastHmdPosValid = false; float m_hmdRotation = 0.0f; @@ -57,18 +57,17 @@ class StatisticsTabController : public QObject float leftSpeed, float rightSpeed ); - float hmdDistanceMoved() const; - float hmdRotations() const; - float rightControllerMaxSpeed() const; - float leftControllerMaxSpeed() const; + [[nodiscard]] float hmdDistanceMoved() const; + [[nodiscard]] float hmdRotations() const; + [[nodiscard]] float rightControllerMaxSpeed() const; + [[nodiscard]] float leftControllerMaxSpeed() const; - unsigned presentedFrames() const; - unsigned droppedFrames() const; - unsigned reprojectedFrames() const; - unsigned timedOut() const; - float totalReprojectedRatio() const; + [[nodiscard]] unsigned presentedFrames() const; + [[nodiscard]] unsigned droppedFrames() const; + [[nodiscard]] unsigned reprojectedFrames() const; + [[nodiscard]] unsigned timedOut() const; + [[nodiscard]] float totalReprojectedRatio() const; -public slots: void statsDistanceResetClicked(); void statsRotationResetClicked(); void statsLeftControllerSpeedResetClicked(); diff --git a/src/tabcontrollers/SteamVRTabController.cpp b/src/tabcontrollers/SteamVRTabController.cpp index 2bbf87b1..b46b0087 100644 --- a/src/tabcontrollers/SteamVRTabController.cpp +++ b/src/tabcontrollers/SteamVRTabController.cpp @@ -4,7 +4,14 @@ #include #include "../overlaycontroller.h" #include "../utils/update_rate.h" +#include "openvr.h" +#include "openvr/ovr_application_wrapper.h" +#include "openvr/ovr_settings_wrapper.h" +#include "openvr/ovr_system_wrapper.h" +#include "settings/settings.h" #include +#include +#include QT_USE_NAMESPACE @@ -49,12 +56,12 @@ void SteamVRTabController::synchSteamVR() bool SteamVRTabController::performanceGraph() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_Perf_Section, vr::k_pch_Perf_PerfGraphInHMD_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_performanceGraphToggle; } @@ -77,12 +84,12 @@ void SteamVRTabController::setPerformanceGraph( const bool value, bool SteamVRTabController::noHMD() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_RequireHmd_String ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_noHMD; } @@ -104,13 +111,13 @@ void SteamVRTabController::setNoHMD( const bool value, const bool notify ) bool SteamVRTabController::multipleDriver() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_multipleDriverToggle; } @@ -134,12 +141,12 @@ void SteamVRTabController::setMultipleDriver( const bool value, bool SteamVRTabController::noFadeToGrid() const { - auto p = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, - vr::k_pch_SteamVR_DoNotFadeToGrid ); + auto pair = ovr_settings_wrapper::getBool( + vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_DoNotFadeToGrid ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_noFadeToGridToggle; } @@ -162,12 +169,12 @@ void SteamVRTabController::setNoFadeToGrid( const bool value, bool SteamVRTabController::controllerPower() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_Power_Section, vr::k_pch_Power_AutoLaunchSteamVROnButtonPress ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_controllerPower; } @@ -191,13 +198,13 @@ void SteamVRTabController::setControllerPower( const bool value, bool SteamVRTabController::systemButton() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_SendSystemButtonToAllApps_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_systemButtonToggle; } @@ -221,13 +228,13 @@ void SteamVRTabController::setSystemButton( const bool value, bool SteamVRTabController::dnd() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_Notifications_Section, vr::k_pch_Notifications_DoNotDisturb_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_dnd; } @@ -253,12 +260,12 @@ void SteamVRTabController::setDND( const bool value, const bool notify ) bool SteamVRTabController::cameraActive() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_Camera_Section, vr::k_pch_Camera_EnableCamera_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_cameraActive; } @@ -281,13 +288,13 @@ void SteamVRTabController::setCameraActive( const bool value, bool SteamVRTabController::cameraBounds() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_Camera_Section, vr::k_pch_Camera_EnableCameraForCollisionBounds_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_cameraBounds; } @@ -311,12 +318,12 @@ void SteamVRTabController::setCameraBounds( const bool value, bool SteamVRTabController::cameraCont() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_Camera_Section, vr::k_pch_Camera_ShowOnController_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_cameraCont; } @@ -355,7 +362,7 @@ void SteamVRTabController::searchRXTX() hmdIndex = device; continue; } - m_deviceList.push_back( DeviceInfo{ device } ); + m_deviceList.emplace_back(); GatherDeviceInfo( m_deviceList.back() ); } @@ -371,9 +378,9 @@ void SteamVRTabController::searchRXTX() { count++; } - for ( auto c : dongleList ) + for ( auto cha : dongleList ) { - if ( c == ';' ) + if ( cha == ';' ) { count++; } @@ -397,13 +404,12 @@ void SteamVRTabController::searchRXTX() { continue; } - m_deviceList.push_back( DeviceInfo{} ); + m_deviceList.emplace_back(); AddUnPairedDevice( m_deviceList.back(), dSN.toStdString() ); // TODO create } } } - return; } void SteamVRTabController::AddUnPairedDevice( DeviceInfo& device, @@ -432,24 +438,25 @@ void SteamVRTabController::AddUnPairedDevice( DeviceInfo& device, void SteamVRTabController::GatherDeviceInfo( DeviceInfo& device ) { - std::string cd = ovr_system_wrapper::getStringTrackedProperty( - device.index, vr::Prop_ConnectedWirelessDongle_String ) - .second; - if ( cd.empty() || cd == " " ) + std::string condev + = ovr_system_wrapper::getStringTrackedProperty( + device.index, vr::Prop_ConnectedWirelessDongle_String ) + .second; + if ( condev.empty() || condev == " " ) { - cd = "n/a"; + condev = "n/a"; device.dongleType = "n/a"; } else { m_dongleCountCur++; - if ( cd.find( "-RYB" ) != std::string::npos - || cd.find( "-LYM" ) != std::string::npos ) + if ( condev.find( "-RYB" ) != std::string::npos + || condev.find( "-LYM" ) != std::string::npos ) { device.dongleType = "Headset"; } // TODO 1yx SN - else if ( std::regex_match( cd, std::regex( "(.*)(-[0-9]YX)" ) ) ) + else if ( std::regex_match( condev, std::regex( "(.*)(-[0-9]YX)" ) ) ) { device.dongleType = "Tundra Dongle"; } @@ -458,18 +465,19 @@ void SteamVRTabController::GatherDeviceInfo( DeviceInfo& device ) device.dongleType = "Standard Dongle"; } } - device.conDongle = cd; + device.conDongle = condev; - std::string dd = ovr_system_wrapper::getStringTrackedProperty( - device.index, vr::Prop_SerialNumber_String ) - .second; - if ( dd.empty() || dd == " " ) + std::string devicenumber = ovr_system_wrapper::getStringTrackedProperty( + device.index, vr::Prop_SerialNumber_String ) + .second; + if ( devicenumber.empty() || devicenumber == " " ) { - dd = "n/a"; + devicenumber = "n/a"; } - device.txName = dd; + device.txName = devicenumber; - auto devClass = ovr_system_wrapper::getDeviceClass( device.index ); + vr::TrackedDeviceClass const devClass + = ovr_system_wrapper::getDeviceClass( device.index ); if ( devClass == vr::TrackedDeviceClass_HMD || devClass == vr::TrackedDeviceClass_Controller || devClass == vr::TrackedDeviceClass_GenericTracker ) @@ -484,9 +492,9 @@ void SteamVRTabController::GatherDeviceInfo( DeviceInfo& device ) device.deviceName = "Lighthouse"; } } - int role = ovr_system_wrapper::getInt32TrackedProperty( - device.index, vr::Prop_ControllerRoleHint_Int32 ) - .second; + int const role = ovr_system_wrapper::getInt32TrackedProperty( + device.index, vr::Prop_ControllerRoleHint_Int32 ) + .second; if ( role == 1 ) { device.deviceName += " (L)"; @@ -499,7 +507,7 @@ void SteamVRTabController::GatherDeviceInfo( DeviceInfo& device ) void SteamVRTabController::launchBindingUI() { - vr::VRActionSetHandle_t actionHandle = 0; + vr::VRActionSetHandle_t const actionHandle = 0; vr::VRInputValueHandle_t inputHandle = 0; auto error2 = vr::VRInput()->GetInputSourceHandle( "/user/hand/right", @@ -524,9 +532,9 @@ void SteamVRTabController::launchBindingUI() } void SteamVRTabController::restartSteamVR() { - QString cmd = QString( "cmd.exe /C restartvrserver.bat \"" ) - + parent->getVRRuntimePathUrl().toLocalFile() - + QString( "\"" ); + QString const cmd = QString( "cmd.exe /C restartvrserver.bat \"" ) + + parent->getVRRuntimePathUrl().toLocalFile() + + QString( "\"" ); qInfo() << "SteamVR Restart Command: " << cmd; QProcess::startDetached( cmd ); } @@ -536,38 +544,38 @@ Q_INVOKABLE unsigned SteamVRTabController::getRXTXCount() return static_cast( m_deviceList.size() ); } -Q_INVOKABLE QString SteamVRTabController::getTXList( int i ) +Q_INVOKABLE QString SteamVRTabController::getTXList( int index ) { - return QString::fromStdString( m_deviceList[i].txName ); + return QString::fromStdString( m_deviceList[index].txName ); } -Q_INVOKABLE QString SteamVRTabController::getDeviceName( int i ) +Q_INVOKABLE QString SteamVRTabController::getDeviceName( int index ) { - return QString::fromStdString( m_deviceList[i].deviceName ); + return QString::fromStdString( m_deviceList[index].deviceName ); } -Q_INVOKABLE QString SteamVRTabController::getRXList( int i ) +Q_INVOKABLE QString SteamVRTabController::getRXList( int index ) { - return QString::fromStdString( m_deviceList[i].conDongle ); + return QString::fromStdString( m_deviceList[index].conDongle ); } -Q_INVOKABLE QString SteamVRTabController::getDongleType( int i ) +Q_INVOKABLE QString SteamVRTabController::getDongleType( int index ) { - return QString::fromStdString( m_deviceList[i].dongleType ); + return QString::fromStdString( m_deviceList[index].dongleType ); } Q_INVOKABLE QString SteamVRTabController::getDongleUsage() { return QString::fromStdString( std::to_string( m_dongleCountCur ) + "/" + std::to_string( m_dongleCountMax ) ); } -Q_INVOKABLE void SteamVRTabController::pairDevice( QString sn ) +Q_INVOKABLE void SteamVRTabController::pairDevice( QString serialNumber ) { - if ( !isSteamVRTracked( sn ) ) + if ( !isSteamVRTracked( serialNumber ) ) { - qWarning() << sn.toStdString() + qWarning() << serialNumber.toStdString() << " Is Not a SteamVR Dongle, skipping Pair"; return; } - m_last_pair_sn = sn; + m_last_pair_sn = serialNumber; auto req = QNetworkRequest(); req.setUrl( QUrl( "ws://127.0.0.1:27062" ) ); req.setRawHeader( @@ -587,11 +595,10 @@ Q_INVOKABLE void SteamVRTabController::pairDevice( QString sn ) &QWebSocket::textMessageReceived, this, &SteamVRTabController::onMsgRec ); - return; } -bool SteamVRTabController::isSteamVRTracked( QString sn ) +bool SteamVRTabController::isSteamVRTracked( QString serialNumber ) { - return m_unparsedDongleString.contains( sn ); + return m_unparsedDongleString.contains( serialNumber ); } void SteamVRTabController::onConnected() { @@ -601,7 +608,7 @@ void SteamVRTabController::onConnected() "\"returnAddress\":\"OVRAS_pair\", " "\"serial\":\""; messageout.append( m_last_pair_sn ); - messageout.append( QString::fromStdString( "\", \"timeoutSeconds\":15}" ) ); + messageout.append( QString::fromStdString( R"(", "timeoutSeconds":15})" ) ); emit pairStatusChanged( QString( "Pairing..." ) ); if ( m_last_pair_sn == "" ) { @@ -633,8 +640,10 @@ std::vector SteamVRTabController::getDongleSerialList( std::string deviceString ) { std::vector dongleList; + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) size_t pos = 0; + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) while ( ( pos = deviceString.find( ',' ) ) != std::string::npos ) { dongleList.push_back( @@ -645,17 +654,16 @@ std::vector deviceString.erase( 0, pos + 1 ); continue; } - else + + pos = deviceString.find( ',' ); + if ( pos == std::string::npos ) { - pos = deviceString.find( ',' ); - if ( pos == std::string::npos ) - { - break; - } - dongleList.push_back( - QString::fromStdString( deviceString.substr( 0, pos ) ) ); break; } + dongleList.push_back( + QString::fromStdString( deviceString.substr( 0, pos ) ) ); + break; + break; } return dongleList; @@ -665,9 +673,9 @@ std::vector void SteamVRTabController::getBindingUrlReq( std::string appID ) { m_lastAppID = appID; - std::string urls + std::string const urls = "http://localhost:27062/input/getactions.json?app_key=" + appID; - QUrl url = QUrl( urls.c_str() ); + QUrl const url = QUrl( urls.c_str() ); QNetworkRequest request; request.setUrl( url ); // This is Important as otherwise Valve's VRWebServerWillIgnore the Request @@ -681,42 +689,40 @@ void SteamVRTabController::getBindingUrlReq( std::string appID ) this, SLOT( onGetBindingUrlResponse( QNetworkReply* ) ) ); m_networkManagerUrl.get( request ); - return; } void SteamVRTabController::onGetBindingUrlResponse( QNetworkReply* reply ) { - QString data = QString::fromUtf8( reply->readAll() ); + QString const data = QString::fromUtf8( reply->readAll() ); if ( data.size() < 2 ) { return; } - std::string controllerName = ovr_system_wrapper::getControllerName(); - if ( controllerName == "" ) + std::string const controllerName = ovr_system_wrapper::getControllerName(); + if ( controllerName.empty() ) { qWarning() << "No Controller Detected Skipping Bindings"; return; } - json jsonfull = json::parse( data.toStdString() ); + nlohmann::json jsonfull = nlohmann::json::parse( data.toStdString() ); // qInfo () << "URL RESPOSNE XXXXXXX"; // qInfo () << jsonfull.dump().c_str(); - std::string filepath + std::string const filepath = jsonfull["current_binding_url"][controllerName].get(); qInfo() << "binding url at " << filepath; // TODO perhaps some form of error checking if packet wrong? reply->close(); getBindingDataReq( filepath, m_lastAppID, controllerName ); - return; } void SteamVRTabController::getBindingDataReq( std::string steamURL, std::string appID, std::string ctrlType ) { - std::string urls = "http://localhost:27062/input/" - "loadbindingfromurl.json?binding_url=" - + steamURL + "&controller_type=" + ctrlType - + "&app_key=" + appID; - QUrl url = QUrl( urls.c_str() ); + std::string const urls = "http://localhost:27062/input/" + "loadbindingfromurl.json?binding_url=" + + steamURL + "&controller_type=" + ctrlType + + "&app_key=" + appID; + QUrl const url = QUrl( urls.c_str() ); QNetworkRequest request; request.setUrl( url ); // This is Important as otherwise Valve's VRWebServerWillIgnore the Request @@ -730,19 +736,18 @@ void SteamVRTabController::getBindingDataReq( std::string steamURL, this, SLOT( onGetBindingDataResponse( QNetworkReply* ) ) ); m_networkManagerBind.get( request ); - return; } void SteamVRTabController::onGetBindingDataResponse( QNetworkReply* reply ) { - json output = ""; - QString data = QString::fromUtf8( reply->readAll() ); + nlohmann::json output = ""; + QString const data = QString::fromUtf8( reply->readAll() ); if ( data.size() < 2 ) { return; } // qWarning () << "DATA RESPONSE"; // qWarning () << data.toStdString(); - json jsonfull = json::parse( data.toStdString() ); + nlohmann::json jsonfull = nlohmann::json::parse( data.toStdString() ); if ( !jsonfull.contains( "success" ) ) { qCritical() << "Binding Data Packet Mal-Formed?"; @@ -754,44 +759,43 @@ void SteamVRTabController::onGetBindingDataResponse( QNetworkReply* reply ) } reply->close(); output = jsonfull["binding_config"]; - std::string sceneAppID = ovr_application_wrapper::getSceneAppID(); + std::string const sceneAppID = ovr_application_wrapper::getSceneAppID(); if ( sceneAppID == "error" ) { qCritical() << "aborting bind save, could not find scene app ID"; return; } - std::string ctrl = ovr_system_wrapper::getControllerName(); + std::string const ctrl = ovr_system_wrapper::getControllerName(); saveBind( m_lastAppID, sceneAppID, ctrl, output, m_setDefault ); - return; } bool SteamVRTabController::saveBind( std::string appID, std::string sceneAppID, std::string ctrlType, - json binds, + nlohmann::json binds, bool def ) { m_setDefault = false; - QFileInfo fi( + QFileInfo const fileInfo( QString::fromStdString( settings::initializeAndGetSettingsPath() ) ); - QDir directory = fi.absolutePath(); - QString Fn; + QDir const directory = fileInfo.absolutePath(); + QString fileName; if ( def ) { - Fn = QString::fromStdString( "defovl" + appID + "ctrl" + ctrlType - + ".json" ); + fileName = QString::fromStdString( "defovl" + appID + "ctrl" + ctrlType + + ".json" ); } else { - Fn = QString::fromStdString( "ovl" + appID + "scene" + sceneAppID - + "ctrl" + ctrlType + ".json" ); + fileName = QString::fromStdString( "ovl" + appID + "scene" + sceneAppID + + "ctrl" + ctrlType + ".json" ); } - QString absPath = directory.absolutePath() + "/" + Fn; + QString const absPath = directory.absolutePath() + "/" + fileName; QFile bindFile( absPath ); bindFile.open( QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text ); - QByteArray qba = binds.dump().c_str(); + QByteArray const qba = binds.dump().c_str(); bindFile.write( qba ); bindFile.flush(); bindFile.close(); @@ -800,7 +804,7 @@ bool SteamVRTabController::saveBind( std::string appID, qInfo() << ( def ? "Default " : ( sceneAppID + " " ) ) + "Binding File saved at:" << absPath.toStdString(); - std::string jsonstring = binds.dump().c_str(); + std::string const jsonstring = binds.dump(); qInfo() << jsonstring; return true; } @@ -811,72 +815,66 @@ bool SteamVRTabController::customBindExists( std::string appID, std::string sceneAppID, std::string ctrl ) { - if ( appID == "" ) + if ( appID.empty() ) { appID = m_lastAppID; } - if ( sceneAppID == "" ) + if ( sceneAppID.empty() ) { sceneAppID = ovr_application_wrapper::getSceneAppID(); } - if ( ctrl == "" ) + if ( ctrl.empty() ) { ctrl = ovr_system_wrapper::getControllerName(); } - QFileInfo fi( QString::fromStdString( + QFileInfo const fileInfo( QString::fromStdString( settings::initializeAndGetSettingsPath() + "ovl" + appID + "scene" + sceneAppID + "ctrl" + ctrl + ".json" ) ); - if ( fi.exists() ) - { - return true; - } - return false; + return fileInfo.exists(); } bool SteamVRTabController::defBindExists( std::string appID, std::string ctrl ) { - if ( appID == "" ) + if ( appID.empty() ) { appID = m_lastAppID; } - if ( ctrl == "" ) + if ( ctrl.empty() ) { ctrl = ovr_system_wrapper::getControllerName(); } - QFileInfo fi( QString::fromStdString( + QFileInfo const fileInfo( QString::fromStdString( settings::initializeAndGetSettingsPath() + "defovl" + appID + "ctrl" + ctrl + ".json" ) ); - if ( fi.exists() ) - { - return true; - } - return false; + return fileInfo.exists(); } void SteamVRTabController::applyBindingReq( std::string appID ) { - std::string ctrlType = ovr_system_wrapper::getControllerName(); - QFileInfo fi( + std::string const ctrlType = ovr_system_wrapper::getControllerName(); + QFileInfo const fileInfo( QString::fromStdString( settings::initializeAndGetSettingsPath() ) ); - QDir directory = fi.absolutePath(); - QString Fn; - std::string sceneAppID = ovr_application_wrapper::getSceneAppID(); - if ( sceneAppID == "" ) + QDir const directory = fileInfo.absolutePath(); + QString fileName; + std::string const sceneAppID = ovr_application_wrapper::getSceneAppID(); + if ( sceneAppID.empty() ) { qCritical() << "NO Scene App Detected unable to apply bindings"; return; } // TODO check forward slash compatibility with linux - Fn = QString::fromStdString( "ovl" + appID + "scene" + sceneAppID + "ctrl" - + ctrlType + ".json" ); - if ( !QFileInfo::exists( fi.absolutePath() + QString( "/" ) + Fn ) ) + fileName = QString::fromStdString( "ovl" + appID + "scene" + sceneAppID + + "ctrl" + ctrlType + ".json" ); + if ( !QFileInfo::exists( fileInfo.absolutePath() + QString( "/" ) + + fileName ) ) { qInfo() << "No Specific Binding Detected for: " + appID + "for Scene: " + sceneAppID + " Checking Default"; - Fn = QString::fromStdString( "defovl" + appID + "ctrl" + ctrlType - + ".json" ); - if ( !QFileInfo::exists( fi.absolutePath() + QString( "/" ) + Fn ) ) + fileName = QString::fromStdString( "defovl" + appID + "ctrl" + ctrlType + + ".json" ); + if ( !QFileInfo::exists( fileInfo.absolutePath() + QString( "/" ) + + fileName ) ) { qInfo() << "No Def Binding Detected for: " + appID + " Not Adjusting Bindings"; @@ -884,12 +882,12 @@ void SteamVRTabController::applyBindingReq( std::string appID ) } } // TODO possible linux compatibility issue - QString absPath = directory.absolutePath() + "/" + Fn; - QUrl urlized = QUrl::fromLocalFile( absPath ); + QString const absPath = directory.absolutePath() + "/" + fileName; + QUrl const urlized = QUrl::fromLocalFile( absPath ); // std::string filePath = "file:///" + absPath.toStdString(); - std::string url = "http://localhost:27062/input/selectconfig.action"; + std::string const url = "http://localhost:27062/input/selectconfig.action"; // qInfo () << urlized.toEncoded().toStdString(); - QUrl urls = QUrl( url.c_str() ); + QUrl const urls = QUrl( url.c_str() ); QNetworkRequest request; request.setUrl( urls ); qInfo() << "Attempting to Apply Binding at: " @@ -903,9 +901,9 @@ void SteamVRTabController::applyBindingReq( std::string appID ) QByteArray( "Referer" ), QByteArray( "http://localhost:27062/dashboard/controllerbinding.html" ) ); - QByteArray data - = ( "{\"app_key\":\"" + appID + "\",\"controller_type\":\"" + ctrlType - + "\",\"url\":\"" + QByteArray const data + = ( R"({"app_key":")" + appID + R"(","controller_type":")" + ctrlType + + R"(","url":")" + urlized.toEncoded( QUrl::EncodeSpaces | QUrl::EncodeReserved ) .toStdString() + "\"}" ) @@ -921,8 +919,8 @@ void SteamVRTabController::applyBindingReq( std::string appID ) void SteamVRTabController::onApplyBindingResponse( QNetworkReply* reply ) { - json output = ""; - QString data = QString::fromUtf8( reply->readAll() ); + nlohmann::json const output = ""; + QString const data = QString::fromUtf8( reply->readAll() ); if ( data.size() < 2 ) { return; @@ -930,7 +928,7 @@ void SteamVRTabController::onApplyBindingResponse( QNetworkReply* reply ) // qInfo () << "APPLY RESPONSE"; // qInfo () << data.toStdString(); reply->close(); - json jsonfull = json::parse( data.toStdString() ); + nlohmann::json jsonfull = nlohmann::json::parse( data.toStdString() ); if ( !jsonfull.contains( "success" ) ) { qCritical() << "Apply Binding Packet Mal-Formed?"; @@ -942,13 +940,12 @@ void SteamVRTabController::onApplyBindingResponse( QNetworkReply* reply ) qCritical() << "Binding Failed To Apply"; } qInfo() << "New Binding Applied"; - return; } void SteamVRTabController::setBindingQMLWrapper( QString appID, bool def ) { m_setDefault = def; - std::string aID = appID.toStdString(); + std::string const aID = appID.toStdString(); getBindingUrlReq( aID ); } @@ -970,38 +967,38 @@ void SteamVRTabController::setPerAppBindEnabled( bool value, bool notify ) void SteamVRTabController::applyAllCustomBindings() { - QFileInfo fi( + QFileInfo const fileInfo( QString::fromStdString( settings::initializeAndGetSettingsPath() ) ); - QDir directory = fi.absolutePath(); - QStringList bindings = directory.entryList( QStringList() << "*.json" - << "*.JSON", - QDir::Files ); + QDir const directory = fileInfo.absolutePath(); + QStringList const bindings = directory.entryList( QStringList() << "*.json" + << "*.JSON", + QDir::Files ); std::set appIDs; - std::regex r1( "ovl(.*)scene" ); - std::regex r2( "defovl(.*)ctrl" ); - foreach ( QString filename, bindings ) + std::regex const reg1( "ovl(.*)scene" ); + std::regex const reg2( "defovl(.*)ctrl" ); + foreach ( QString const filename, bindings ) { - std::smatch m; - std::string s = filename.toStdString(); + std::smatch mat; + std::string const sfilename = filename.toStdString(); - if ( regex_search( s, m, r1 ) ) + if ( regex_search( sfilename, mat, reg1 ) ) { - if ( m.size() == 2 ) + if ( mat.size() == 2 ) { - appIDs.insert( m[1].str() ); + appIDs.insert( mat[1].str() ); continue; } } - if ( regex_search( s, m, r2 ) ) + if ( regex_search( sfilename, mat, reg2 ) ) { - if ( m.size() == 2 ) + if ( mat.size() == 2 ) { - appIDs.insert( m[1].str() ); + appIDs.insert( mat[1].str() ); continue; } } } - foreach ( std::string appID, appIDs ) + foreach ( std::string const appID, appIDs ) { applyBindingReq( appID ); } diff --git a/src/tabcontrollers/SteamVRTabController.h b/src/tabcontrollers/SteamVRTabController.h index ce0ad0bd..f5047e94 100644 --- a/src/tabcontrollers/SteamVRTabController.h +++ b/src/tabcontrollers/SteamVRTabController.h @@ -1,27 +1,17 @@ #pragma once +#include "../../third-party/nlhomann/json.hpp" +#include +#include +#include +#include #include -#include "../utils/FrameRateUtils.h" -#include "../openvr/ovr_settings_wrapper.h" -#include "../openvr/ovr_application_wrapper.h" -#include "../openvr/lh_console_util.h" #include #include -#include "../openvr/lh_console_util.h" -#include -#include "../openvr/ovr_system_wrapper.h" -#include -#include #include -#include -#include -#include "../../third-party/nlhomann/json.hpp" -#include -#include -#include +#include -using namespace nlohmann; class QQuickWindow; // application namespace namespace advsettings @@ -33,12 +23,12 @@ class OverlayController; struct DeviceInfo { int index = -1; - std::string conDongle = ""; - std::string txName = ""; - std::string deviceName = ""; - std::string hand = ""; + std::string conDongle; + std::string txName; + std::string deviceName; + std::string hand; std::string dongleType = "n/a"; - std::string serialNumber = ""; + std::string serialNumber; bool hasName = false; }; @@ -102,9 +92,12 @@ class SteamVRTabController : public QObject void AddUnPairedDevice( DeviceInfo& device, std::string donSN ); void synchSteamVR(); std::vector getDongleSerialList( std::string deviceString ); - bool isSteamVRTracked( QString sn ); + bool isSteamVRTracked( QString serialnum ); void applyBindingReq( std::string appID ); + QNetworkProxy m_proxy; + QWebSocket m_webSocket; + public: void initStage1(); void initStage2( OverlayController* parent ); @@ -112,21 +105,18 @@ class SteamVRTabController : public QObject void eventLoopTick(); void dashboardLoopTick(); - bool performanceGraph() const; - bool noFadeToGrid() const; - bool multipleDriver() const; - bool systemButton() const; - bool dnd() const; - bool controllerPower() const; - bool noHMD() const; - - bool cameraActive() const; - bool cameraBounds() const; - bool cameraCont() const; - QNetworkProxy m_proxy; - QWebSocket m_webSocket; + [[nodiscard]] bool performanceGraph() const; + [[nodiscard]] bool noFadeToGrid() const; + [[nodiscard]] bool multipleDriver() const; + [[nodiscard]] bool systemButton() const; + [[nodiscard]] bool dnd() const; + [[nodiscard]] bool controllerPower() const; + [[nodiscard]] bool noHMD() const; + + [[nodiscard]] bool cameraActive() const; + [[nodiscard]] bool cameraBounds() const; + [[nodiscard]] bool cameraCont() const; - bool m_adjustBinding = true; void getBindingUrlReq( std::string appID ); void getBindingDataReq( std::string steamURL, std::string appID, @@ -141,10 +131,10 @@ class SteamVRTabController : public QObject bool saveBind( std::string appID, std::string sceneAppID, std::string ctrlType, - json binds, + nlohmann::json binds, bool def = false ); - bool perAppBindEnabled() const; + [[nodiscard]] bool perAppBindEnabled() const; void applyAllCustomBindings(); Q_INVOKABLE void searchRXTX(); @@ -152,16 +142,15 @@ class SteamVRTabController : public QObject Q_INVOKABLE void launchBindingUI(); Q_INVOKABLE unsigned getRXTXCount(); - Q_INVOKABLE QString getTXList( int i ); - Q_INVOKABLE QString getRXList( int i ); - Q_INVOKABLE QString getDeviceName( int i ); - Q_INVOKABLE QString getDongleType( int i ); + Q_INVOKABLE QString getTXList( int index ); + Q_INVOKABLE QString getRXList( int index ); + Q_INVOKABLE QString getDeviceName( int index ); + Q_INVOKABLE QString getDongleType( int index ); Q_INVOKABLE QString getDongleUsage(); - Q_INVOKABLE void pairDevice( QString sn ); + Q_INVOKABLE void pairDevice( QString serialnum ); Q_INVOKABLE void updateRXTXList(); Q_INVOKABLE void setBindingQMLWrapper( QString appID, bool def = false ); -public slots: void onConnected(); void onDisconnect(); void onMsgRec( QString Msg ); diff --git a/src/tabcontrollers/UtilitiesTabController.cpp b/src/tabcontrollers/UtilitiesTabController.cpp index 46310ecd..b2bfe716 100644 --- a/src/tabcontrollers/UtilitiesTabController.cpp +++ b/src/tabcontrollers/UtilitiesTabController.cpp @@ -5,12 +5,14 @@ #include #include "../overlaycontroller.h" #include "../keyboard_input/input_sender.h" +#include "../keyboard_input/keyboard_input.h" #include "../settings/settings.h" #include "../utils/update_rate.h" +#include "../media_keys/media_keys.h" +#include #include "openvr/ovr_overlay_wrapper.h" -#include +#include "openvr/ovr_system_wrapper.h" #include -#include // application namespace namespace advsettings @@ -250,12 +252,13 @@ QString getBatteryIconPath( int batteryState ) vr::VROverlayHandle_t UtilitiesTabController::createBatteryOverlay( vr::TrackedDeviceIndex_t index, - unsigned style ) + BatteryOverlayStyle style ) { vr::VROverlayHandle_t handle = vr::k_ulOverlayHandleInvalid; - std::string batteryKey = std::string( application_strings::applicationKey ) - + ".battery." + std::to_string( index ); - vr::VROverlayError overlayError = vr::VROverlay()->CreateOverlay( + std::string const batteryKey + = std::string( application_strings::applicationKey ) + ".battery." + + std::to_string( index ); + vr::VROverlayError const overlayError = vr::VROverlay()->CreateOverlay( batteryKey.c_str(), batteryKey.c_str(), &handle ); if ( overlayError == vr::VROverlayError_None ) { @@ -274,7 +277,7 @@ vr::VROverlayHandle_t UtilitiesTabController::createBatteryOverlay( ovr_overlay_wrapper::setOverlayFromQImage( handle, *m_batteryImgs[0] ); vr::VROverlay()->SetOverlayWidthInMeters( handle, 0.045f ); vr::HmdMatrix34_t notificationTransform; - if ( style == 1 ) + if ( style == BatteryOverlayStyle_Tundra ) { notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, { 0.0f, -1.0f, 0.0f, 0.0081f }, @@ -302,14 +305,14 @@ vr::VROverlayHandle_t UtilitiesTabController::createBatteryOverlay( void UtilitiesTabController::destroyBatteryOverlays() { - for ( auto& el : m_batteryOverlayHandles ) + for ( auto& boh : m_batteryOverlayHandles ) { - if ( el == 0 ) + if ( boh == 0 ) { continue; } - auto err = vr::VROverlay()->DestroyOverlay( el ); - el = 0; + auto err = vr::VROverlay()->DestroyOverlay( boh ); + boh = 0; if ( err != vr::VROverlayError_None ) { qCritical() << "Could not Delete Battery Overlay: " @@ -322,70 +325,75 @@ void UtilitiesTabController::handleTrackerBatOvl() { // attach battery overlay to all tracked devices that aren't a // controller or hmd - for ( vr::TrackedDeviceIndex_t i = 0; i < vr::k_unMaxTrackedDeviceCount; - i++ ) + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) + int const max = vr::k_unMaxTrackedDeviceCount; + // NOLINTNEXTLINE(altera-id-dependent-backward-branch) + for ( int index = 0; index < max; index++ ) { - vr::ETrackedDeviceClass deviceClass - = vr::VRSystem()->GetTrackedDeviceClass( i ); + vr::ETrackedDeviceClass const deviceClass + = vr::VRSystem()->GetTrackedDeviceClass( index ); if ( deviceClass == vr::ETrackedDeviceClass::TrackedDeviceClass_GenericTracker ) { - if ( m_batteryOverlayHandles[i] == 0 ) + if ( m_batteryOverlayHandles[index] == 0 ) { auto type = ovr_system_wrapper::getStringTrackedProperty( - i, vr::Prop_RenderModelName_String ); - unsigned style = 0; - if ( type.first == ovr_system_wrapper::SystemError::NoError ) - { - if ( type.second.find( "tundra" ) != std::string::npos ) - { - style = 1; - } - } - - qInfo() << "Creating battery overlay for device " << i; - m_batteryOverlayHandles[i] = createBatteryOverlay( i, style ); - m_batteryVisible[i] = true; + index, vr::Prop_RenderModelName_String ); + auto style + = type.first == ovr_system_wrapper::SystemError::NoError + && type.second.find( "tundra" ) + != std::string::npos + ? BatteryOverlayStyle_Tundra + : BatteryOverlayStyle_Default; + + qInfo() << "Creating battery overlay for device " << index; + m_batteryOverlayHandles[index] + = createBatteryOverlay( index, style ); + m_batteryVisible[index] = true; } - bool shouldShow = vr::VROverlay()->IsDashboardVisible(); + bool const shouldShow = vr::VROverlay()->IsDashboardVisible(); - if ( shouldShow != m_batteryVisible[i] ) + if ( shouldShow != m_batteryVisible[index] ) { if ( shouldShow ) { - vr::VROverlay()->ShowOverlay( m_batteryOverlayHandles[i] ); + vr::VROverlay()->ShowOverlay( + m_batteryOverlayHandles[index] ); } else { - vr::VROverlay()->HideOverlay( m_batteryOverlayHandles[i] ); + vr::VROverlay()->HideOverlay( + m_batteryOverlayHandles[index] ); } - m_batteryVisible[i] = shouldShow; + m_batteryVisible[index] = shouldShow; } - bool hasBatteryStatus + bool const hasBatteryStatus = vr::VRSystem()->GetBoolTrackedDeviceProperty( - i, + index, vr::ETrackedDeviceProperty:: Prop_DeviceProvidesBatteryStatus_Bool ); if ( hasBatteryStatus ) { - float battery = vr::VRSystem()->GetFloatTrackedDeviceProperty( - i, - vr::ETrackedDeviceProperty:: - Prop_DeviceBatteryPercentage_Float ); - int batteryState = static_cast( + float const battery + = vr::VRSystem()->GetFloatTrackedDeviceProperty( + index, + vr::ETrackedDeviceProperty:: + Prop_DeviceBatteryPercentage_Float ); + int const batteryState = static_cast( ceil( static_cast( battery * 5 ) ) ); - if ( batteryState != m_batteryState[i] ) + if ( batteryState != m_batteryState[index] ) { - qInfo() << "Updating battery overlay for device " << i - << " to " << batteryState << "(" << battery << ")" - << QString::number( m_batteryOverlayHandles[i] ); + qInfo() + << "Updating battery overlay for device " << index + << " to " << batteryState << "(" << battery << ")" + << QString::number( m_batteryOverlayHandles[index] ); ovr_overlay_wrapper::setOverlayFromQImage( - m_batteryOverlayHandles[i], + m_batteryOverlayHandles[index], *m_batteryImgs[batteryState] ); - m_batteryState[i] = batteryState; + m_batteryState[index] = batteryState; } } } diff --git a/src/tabcontrollers/UtilitiesTabController.h b/src/tabcontrollers/UtilitiesTabController.h index 4bd57d13..8bdf8d84 100644 --- a/src/tabcontrollers/UtilitiesTabController.h +++ b/src/tabcontrollers/UtilitiesTabController.h @@ -6,9 +6,6 @@ #include #include #include -#include "src/keyboard_input/keyboard_input.h" -#include "src/media_keys/media_keys.h" -#include "../utils/FrameRateUtils.h" class QQuickWindow; // application namespace @@ -17,6 +14,12 @@ namespace advsettings // forward declaration class OverlayController; +typedef enum eBatteryOverlayStyle +{ + BatteryOverlayStyle_Default, + BatteryOverlayStyle_Tundra +} BatteryOverlayStyle; + class UtilitiesTabController : public QObject { Q_OBJECT @@ -31,13 +34,14 @@ class UtilitiesTabController : public QObject unsigned settingsUpdateCounter = 0; std::array, 6> m_batteryImgs; - vr::VROverlayHandle_t m_batteryOverlayHandles[vr::k_unMaxTrackedDeviceCount] - = { 0 }; - int m_batteryState[vr::k_unMaxTrackedDeviceCount]; - bool m_batteryVisible[vr::k_unMaxTrackedDeviceCount]; + std::array + m_batteryOverlayHandles = { 0 }; + std::array m_batteryState; + std::array m_batteryVisible; void handleTrackerBatOvl(); vr::VROverlayHandle_t createBatteryOverlay( vr::TrackedDeviceIndex_t index, - unsigned style = 0 ); + BatteryOverlayStyle style + = BatteryOverlayStyle_Default ); void destroyBatteryOverlays(); public: @@ -45,10 +49,9 @@ class UtilitiesTabController : public QObject void eventLoopTick(); - bool vrcDebug() const; - bool trackerOvlEnabled() const; + [[nodiscard]] bool vrcDebug() const; + [[nodiscard]] bool trackerOvlEnabled() const; -public slots: void sendKeyboardInput( QString input ); void sendKeyboardEnter(); void sendKeyboardAltTab(); diff --git a/src/tabcontrollers/VideoTabController.cpp b/src/tabcontrollers/VideoTabController.cpp index 8a6165d0..6d4650c7 100644 --- a/src/tabcontrollers/VideoTabController.cpp +++ b/src/tabcontrollers/VideoTabController.cpp @@ -6,7 +6,10 @@ #include "../settings/settings.h" #include "../overlaycontroller.h" #include "../utils/update_rate.h" +#include "openvr/ovr_overlay_wrapper.h" +#include "openvr/ovr_settings_wrapper.h" #include +#include namespace advsettings { @@ -45,10 +48,11 @@ void VideoTabController::synchSteamVR() void VideoTabController::initBrightnessOverlay() { - std::string notifKey = std::string( application_strings::applicationKey ) - + ".brightnessoverlay"; + std::string const notifKey + = std::string( application_strings::applicationKey ) + + ".brightnessoverlay"; - vr::VROverlayError overlayError = vr::VROverlay()->CreateOverlay( + vr::VROverlayError const overlayError = vr::VROverlay()->CreateOverlay( notifKey.c_str(), notifKey.c_str(), &m_brightnessOverlayHandle ); if ( overlayError == vr::VROverlayError_None ) { @@ -57,7 +61,7 @@ void VideoTabController::initBrightnessOverlay() notifIcon ); vr::VROverlay()->SetOverlayWidthInMeters( m_brightnessOverlayHandle, k_overlayWidth ); - vr::HmdMatrix34_t notificationTransform + vr::HmdMatrix34_t const notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, { 0.0f, 1.0f, 0.0f, 0.00f }, { 0.0f, 0.0f, 1.0f, k_hmdDistance } } }; @@ -79,10 +83,10 @@ void VideoTabController::initBrightnessOverlay() void VideoTabController::initColorOverlay() { - std::string notifKey + std::string const notifKey = std::string( application_strings::applicationKey ) + ".coloroverlay"; - vr::VROverlayError overlayError = vr::VROverlay()->CreateOverlay( + vr::VROverlayError const overlayError = vr::VROverlay()->CreateOverlay( notifKey.c_str(), notifKey.c_str(), &m_colorOverlayHandle ); if ( overlayError == vr::VROverlayError_None ) { @@ -93,7 +97,7 @@ void VideoTabController::initColorOverlay() k_overlayWidth ); // position it just slightly further out so we don't have to worry // about render order. - vr::HmdMatrix34_t notificationTransform + vr::HmdMatrix34_t const notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, { 0.0f, 1.0f, 0.0f, 0.00f }, { 0.0f, 0.0f, 1.0f, ( k_hmdDistance - 0.01f ) } } }; @@ -373,7 +377,7 @@ void VideoTabController::setColorOverlayOpacity( float value, bool notify ) void VideoTabController::synchGain( bool setValue ) { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; auto red = vr::VRSettings()->GetFloat( vr::k_pch_SteamVR_Section, @@ -453,8 +457,11 @@ void VideoTabController::setColorRed( float value, bool notify, bool keepValue ) if ( isOverlayMethodActive() ) { - vr::VROverlayError overlayError = vr::VROverlay()->SetOverlayColor( - m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); + vr::VROverlayError const overlayError + = vr::VROverlay()->SetOverlayColor( m_colorOverlayHandle, + colorRed(), + colorGreen(), + colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { qCritical() << "Could not set Red for color overlay: " @@ -464,7 +471,7 @@ void VideoTabController::setColorRed( float value, bool notify, bool keepValue ) } else { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetFloat( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_HmdDisplayColorGainR_Float, @@ -503,8 +510,11 @@ void VideoTabController::setColorGreen( float value, if ( isOverlayMethodActive() ) { - vr::VROverlayError overlayError = vr::VROverlay()->SetOverlayColor( - m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); + vr::VROverlayError const overlayError + = vr::VROverlay()->SetOverlayColor( m_colorOverlayHandle, + colorRed(), + colorGreen(), + colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { qCritical() << "Could not set Green for color overlay: " @@ -514,7 +524,7 @@ void VideoTabController::setColorGreen( float value, } else { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetFloat( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_HmdDisplayColorGainG_Float, @@ -552,8 +562,11 @@ void VideoTabController::setColorBlue( float value, } if ( isOverlayMethodActive() ) { - vr::VROverlayError overlayError = vr::VROverlay()->SetOverlayColor( - m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); + vr::VROverlayError const overlayError + = vr::VROverlay()->SetOverlayColor( m_colorOverlayHandle, + colorRed(), + colorGreen(), + colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { qCritical() << "Could not set Blue for color overlay: " @@ -563,7 +576,7 @@ void VideoTabController::setColorBlue( float value, } else { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetFloat( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_HmdDisplayColorGainB_Float, @@ -589,7 +602,7 @@ void VideoTabController::setColorBlue( float value, void VideoTabController::resetGain() { - vr::EVRSettingsError vrSettingsError; + vr::EVRSettingsError vrSettingsError = {}; vr::VRSettings()->SetFloat( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_HmdDisplayColorGainR_Float, 1.0f, @@ -626,15 +639,16 @@ void VideoTabController::resetGain() } } -void VideoTabController::setColor( float R, - float G, - float B, +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) +void VideoTabController::setColor( float Red, + float Green, + float Blue, bool notify, bool keepValue ) { - setColorRed( R, notify, keepValue ); - setColorGreen( G, notify, keepValue ); - setColorBlue( B, notify, keepValue ); + setColorRed( Red, notify, keepValue ); + setColorGreen( Green, notify, keepValue ); + setColorBlue( Blue, notify, keepValue ); } /* @@ -647,23 +661,23 @@ void VideoTabController::setColor( float R, float VideoTabController::superSampling() const { - auto p = ovr_settings_wrapper::getFloat( + auto pair = ovr_settings_wrapper::getFloat( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_SupersampleScale_Float ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_superSampling; } bool VideoTabController::allowSupersampleOverride() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_SupersampleManualOverride_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_allowSupersampleOverride; } @@ -718,11 +732,11 @@ void VideoTabController::setAllowSupersampleOverride( const bool value, bool VideoTabController::motionSmoothing() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_MotionSmoothing_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_motionSmoothing; } @@ -745,12 +759,12 @@ void VideoTabController::setMotionSmoothing( const bool value, bool VideoTabController::allowSupersampleFiltering() const { - auto p = ovr_settings_wrapper::getBool( + auto pair = ovr_settings_wrapper::getBool( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_AllowSupersampleFiltering_Bool ); - if ( p.first == ovr_settings_wrapper::SettingsError::NoError ) + if ( pair.first == ovr_settings_wrapper::SettingsError::NoError ) { - return p.second; + return pair.second; } return m_allowSupersampleFiltering; } @@ -780,19 +794,19 @@ void VideoTabController::setAllowSupersampleFiltering( const bool value, void VideoTabController::addVideoProfile( const QString name ) { VideoProfile* profile = nullptr; - for ( auto& p : videoProfiles ) + for ( auto& pro : videoProfiles ) { - if ( p.profileName.compare( name.toStdString() ) == 0 ) + if ( pro.profileName.compare( name.toStdString() ) == 0 ) { - profile = &p; + profile = &pro; break; } } if ( !profile ) { - auto i = videoProfiles.size(); + auto index = videoProfiles.size(); videoProfiles.emplace_back(); - profile = &videoProfiles[i]; + profile = &videoProfiles[index]; } profile->profileName = name.toStdString(); @@ -863,12 +877,10 @@ QString VideoTabController::getVideoProfileName( const unsigned index ) { if ( index >= videoProfiles.size() ) { - return QString(); - } - else - { - return QString::fromStdString( videoProfiles[index].profileName ); + return {}; } + + return QString::fromStdString( videoProfiles[index].profileName ); } /*------------------------------------------*/ diff --git a/src/tabcontrollers/VideoTabController.h b/src/tabcontrollers/VideoTabController.h index 8e9fd506..8c30c26a 100644 --- a/src/tabcontrollers/VideoTabController.h +++ b/src/tabcontrollers/VideoTabController.h @@ -4,9 +4,6 @@ #include #include #include -#include "../openvr/ovr_settings_wrapper.h" -#include "../openvr/ovr_overlay_wrapper.h" -#include "../utils/FrameRateUtils.h" #include "../settings/settings_object.h" class QQuickWindow; @@ -25,6 +22,7 @@ class OverlayController; struct VideoProfile : settings::ISettingsObject { + // NOLINTBEGIN(misc-non-private-member-variables-in-classes) std::string profileName; float supersampling = 1.0f; @@ -38,35 +36,36 @@ struct VideoProfile : settings::ISettingsObject float brightnessOpacityValue = 1.0f; bool overlayMethodState = false; float opacity = 0.0f; // TODO check + // NOLINTEND(misc-non-private-member-variables-in-classes) - virtual settings::SettingsObjectData saveSettings() const override + [[nodiscard]] settings::SettingsObjectData saveSettings() const override { - settings::SettingsObjectData o; + settings::SettingsObjectData sod; - o.addValue( profileName ); - o.addValue( static_cast( supersampling ) ); + sod.addValue( profileName ); + sod.addValue( static_cast( supersampling ) ); - o.addValue( anisotropicFiltering ); - o.addValue( motionSmooth ); - o.addValue( supersampleOverride ); + sod.addValue( anisotropicFiltering ); + sod.addValue( motionSmooth ); + sod.addValue( supersampleOverride ); - o.addValue( static_cast( colorRed ) ); - o.addValue( static_cast( colorGreen ) ); - o.addValue( static_cast( colorBlue ) ); + sod.addValue( static_cast( colorRed ) ); + sod.addValue( static_cast( colorGreen ) ); + sod.addValue( static_cast( colorBlue ) ); - o.addValue( brightnessToggle ); + sod.addValue( brightnessToggle ); - o.addValue( static_cast( brightnessOpacityValue ) ); + sod.addValue( static_cast( brightnessOpacityValue ) ); - o.addValue( overlayMethodState ); + sod.addValue( overlayMethodState ); // TODO add opacity Toggle? - o.addValue( static_cast( opacity ) ); + sod.addValue( static_cast( opacity ) ); - return o; + return sod; } - virtual void loadSettings( settings::SettingsObjectData& obj ) override + void loadSettings( settings::SettingsObjectData& obj ) override { profileName = obj.getNextValueOrDefault( "" ); supersampling = static_cast( obj.getNextValueOrDefault( 1.0 ) ); @@ -89,7 +88,7 @@ struct VideoProfile : settings::ISettingsObject opacity = static_cast( obj.getNextValueOrDefault( 1.0 ) ); } - virtual std::string settingsName() const override + [[nodiscard]] std::string settingsName() const override { return "VideoTabController::VideoProfile"; } @@ -152,9 +151,9 @@ class VideoTabController : public QObject unsigned int m_videoDashboardUpdateCounter = 47; - void setColor( float R, - float G, - float B, + void setColor( float Red, + float Green, + float Blue, bool notify = true, bool keepValue = false ); void resetGain(); @@ -187,22 +186,22 @@ class VideoTabController : public QObject } public: - float brightnessOpacityValue() const; - bool brightnessEnabled() const; + [[nodiscard]] float brightnessOpacityValue() const; + [[nodiscard]] bool brightnessEnabled() const; // Color overlay Getters - bool colorOverlayEnabled() const; - float colorRed() const; - float colorGreen() const; - float colorBlue() const; + [[nodiscard]] bool colorOverlayEnabled() const; + [[nodiscard]] float colorRed() const; + [[nodiscard]] float colorGreen() const; + [[nodiscard]] float colorBlue() const; - float colorOverlayOpacity() const; + [[nodiscard]] float colorOverlayOpacity() const; - bool allowSupersampleOverride() const; - float superSampling() const; - bool motionSmoothing() const; - bool allowSupersampleFiltering() const; - bool isOverlayMethodActive() const; + [[nodiscard]] bool allowSupersampleOverride() const; + [[nodiscard]] float superSampling() const; + [[nodiscard]] bool motionSmoothing() const; + [[nodiscard]] bool allowSupersampleFiltering() const; + [[nodiscard]] bool isOverlayMethodActive() const; void initStage1(); void initStage2(); @@ -215,7 +214,6 @@ class VideoTabController : public QObject Q_INVOKABLE int getVideoProfileCount(); Q_INVOKABLE QString getVideoProfileName( unsigned index ); -public slots: void setBrightnessEnabled( bool value, bool notify = true, bool keepValue = false ); diff --git a/src/tabcontrollers/audiomanager/AudioManager.h b/src/tabcontrollers/audiomanager/AudioManager.h index 0a16948c..f0a53f22 100644 --- a/src/tabcontrollers/audiomanager/AudioManager.h +++ b/src/tabcontrollers/audiomanager/AudioManager.h @@ -11,8 +11,9 @@ class AudioTabController; class AudioDevice { public: - AudioDevice( const std::string id, const std::string name ) - : m_id( id ), m_name( name ) + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) + AudioDevice( const std::string dev_id, const std::string name ) + : m_id( dev_id ), m_name( name ) { } @@ -38,12 +39,14 @@ class AudioManager virtual void init( AudioTabController* controller ) = 0; - virtual void setPlaybackDevice( const std::string& id, bool notify = true ) + virtual void setPlaybackDevice( const std::string& dev_id, + bool notify = true ) = 0; virtual std::string getPlaybackDevName() = 0; virtual std::string getPlaybackDevId() = 0; - virtual void setMirrorDevice( const std::string& id, bool notify = true ) + virtual void setMirrorDevice( const std::string& dev_id, + bool notify = true ) = 0; virtual bool isMirrorValid() = 0; virtual std::string getMirrorDevName() = 0; @@ -53,7 +56,8 @@ class AudioManager virtual bool getMirrorMuted() = 0; virtual bool setMirrorMuted( bool value ) = 0; - virtual void setMicDevice( const std::string& id, bool notify = true ) = 0; + virtual void setMicDevice( const std::string& dev_id, bool notify = true ) + = 0; virtual bool isMicValid() = 0; virtual std::string getMicDevName() = 0; virtual std::string getMicDevId() = 0; diff --git a/src/tabcontrollers/audiomanager/AudioManagerDummy.cpp b/src/tabcontrollers/audiomanager/AudioManagerDummy.cpp index 7d979184..e4dc813c 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerDummy.cpp +++ b/src/tabcontrollers/audiomanager/AudioManagerDummy.cpp @@ -1,23 +1,17 @@ #include "AudioManagerDummy.h" -// Used to get the compiler to shut up about C4100: unreferenced formal -// parameter. The cast is to get GCC to shut up about it. -#define UNREFERENCED_PARAMETER( P ) static_cast( ( P ) ) - // application namespace namespace advsettings { -void AudioManagerDummy::init( AudioTabController* controller ) +void AudioManagerDummy::init( AudioTabController* /*controller*/ ) { // noop - UNREFERENCED_PARAMETER( controller ); } -void AudioManagerDummy::setPlaybackDevice( const std::string& id, bool notify ) +void AudioManagerDummy::setPlaybackDevice( const std::string& /*dev_id*/, + bool /*notify*/ ) { // noop - UNREFERENCED_PARAMETER( id ); - UNREFERENCED_PARAMETER( notify ); } std::string AudioManagerDummy::getPlaybackDevName() @@ -30,11 +24,10 @@ std::string AudioManagerDummy::getPlaybackDevId() return "dummy"; } -void AudioManagerDummy::setMirrorDevice( const std::string& id, bool notify ) +void AudioManagerDummy::setMirrorDevice( const std::string& /*dev_id*/, + bool /*notify*/ ) { // noop - UNREFERENCED_PARAMETER( id ); - UNREFERENCED_PARAMETER( notify ); } bool AudioManagerDummy::isMirrorValid() @@ -57,9 +50,8 @@ float AudioManagerDummy::getMirrorVolume() return 0; } -bool AudioManagerDummy::setMirrorVolume( float value ) +bool AudioManagerDummy::setMirrorVolume( float /*value*/ ) { - UNREFERENCED_PARAMETER( value ); return false; } @@ -68,9 +60,8 @@ bool AudioManagerDummy::getMirrorMuted() return true; } -bool AudioManagerDummy::setMirrorMuted( bool value ) +bool AudioManagerDummy::setMirrorMuted( bool /*value*/ ) { - UNREFERENCED_PARAMETER( value ); return false; } @@ -79,11 +70,10 @@ bool AudioManagerDummy::isMicValid() return false; } -void AudioManagerDummy::setMicDevice( const std::string& id, bool notify ) +void AudioManagerDummy::setMicDevice( const std::string& /*dev_id*/, + bool /*notify*/ ) { // noop - UNREFERENCED_PARAMETER( id ); - UNREFERENCED_PARAMETER( notify ); } std::string AudioManagerDummy::getMicDevName() @@ -101,9 +91,8 @@ float AudioManagerDummy::getMicVolume() return 0; } -bool AudioManagerDummy::setMicVolume( float value ) +bool AudioManagerDummy::setMicVolume( float /*value*/ ) { - UNREFERENCED_PARAMETER( value ); return false; } @@ -112,9 +101,8 @@ bool AudioManagerDummy::getMicMuted() return true; } -bool AudioManagerDummy::setMicMuted( bool value ) +bool AudioManagerDummy::setMicMuted( bool /*value*/ ) { - UNREFERENCED_PARAMETER( value ); return false; } diff --git a/src/tabcontrollers/audiomanager/AudioManagerDummy.h b/src/tabcontrollers/audiomanager/AudioManagerDummy.h index 185e7c3d..a9243a2a 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerDummy.h +++ b/src/tabcontrollers/audiomanager/AudioManagerDummy.h @@ -9,35 +9,34 @@ namespace advsettings class AudioManagerDummy : public AudioManager { public: - virtual void init( AudioTabController* controller ) override; + void init( AudioTabController* controller ) override; - virtual void setPlaybackDevice( const std::string& id, - bool notify = true ) override; - virtual std::string getPlaybackDevName() override; - virtual std::string getPlaybackDevId() override; + void setPlaybackDevice( const std::string& dev_id, + bool notify = true ) override; + std::string getPlaybackDevName() override; + std::string getPlaybackDevId() override; - virtual void setMirrorDevice( const std::string& id, - bool notify = true ) override; - virtual bool isMirrorValid() override; - virtual std::string getMirrorDevName() override; - virtual std::string getMirrorDevId() override; - virtual float getMirrorVolume() override; - virtual bool setMirrorVolume( float value ) override; - virtual bool getMirrorMuted() override; - virtual bool setMirrorMuted( bool value ) override; + void setMirrorDevice( const std::string& dev_id, + bool notify = true ) override; + bool isMirrorValid() override; + std::string getMirrorDevName() override; + std::string getMirrorDevId() override; + float getMirrorVolume() override; + bool setMirrorVolume( float value ) override; + bool getMirrorMuted() override; + bool setMirrorMuted( bool value ) override; - virtual bool isMicValid() override; - virtual void setMicDevice( const std::string& id, - bool notify = true ) override; - virtual std::string getMicDevName() override; - virtual std::string getMicDevId() override; - virtual float getMicVolume() override; - virtual bool setMicVolume( float value ) override; - virtual bool getMicMuted() override; - virtual bool setMicMuted( bool value ) override; + bool isMicValid() override; + void setMicDevice( const std::string& dev_id, bool notify = true ) override; + std::string getMicDevName() override; + std::string getMicDevId() override; + float getMicVolume() override; + bool setMicVolume( float value ) override; + bool getMicMuted() override; + bool setMicMuted( bool value ) override; - virtual std::vector getRecordingDevices() override; - virtual std::vector getPlaybackDevices() override; + std::vector getRecordingDevices() override; + std::vector getPlaybackDevices() override; }; } // namespace advsettings diff --git a/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp b/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp index 07f693c0..b8f0b9b1 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp +++ b/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp @@ -1,10 +1,648 @@ #include "AudioManagerPulse.h" -#include "AudioManagerPulse_internal.h" #include "../AudioTabController.h" -// Used to get the compiler to shut up about C4100: unreferenced formal -// parameter. The cast is to get GCC to shut up about it. -#define UNREFERENCED_PARAMETER( P ) static_cast( ( P ) ) +#include +#include +#include +#include +#include +#include "AudioManager.h" + +namespace advsettings +{ +using std::string; + +enum PulseAudioIsLastMeaning : std::uint8_t +{ + Error, + RealDevice, + PreviousDeviceWasLastReal, +}; + +enum PulseAudioLoopControl : std::uint8_t +{ + Stop, + Run, +}; + +struct +{ + pa_mainloop* mainLoop; + pa_mainloop_api* api; + pa_context* context; +} pulseAudioPointers; + +struct +{ + std::string defaultSinkOutputDeviceId; + std::string defaultSourceInputDeviceId; + + std::string originalDefaultOutputDeviceId; + std::string originalDefaultInputDeviceId; + + float originalDefaultOutputDeviceVolume; + float originalDefaultInputDeviceVolume; + + std::vector sinkOutputDevices; + std::vector sourceInputDevices; + + pa_sink_info currentDefaultSinkInfo; + pa_source_info currentDefaultSourceInfo; +} pulseAudioData; + +namespace +{ + PulseAudioLoopControl loopControl = PulseAudioLoopControl::Run; +} // namespace + +void customPulseLoop() +{ + while ( loopControl == PulseAudioLoopControl::Run ) + { + constexpr auto noReturnValue = nullptr; + constexpr auto blockForEvents = 1; + pa_mainloop_iterate( + pulseAudioPointers.mainLoop, blockForEvents, noReturnValue ); + } + + loopControl = PulseAudioLoopControl::Run; +} + +// Error function +void dumpPulseAudioState() +{ + qCritical() << "____"; + + qCritical() << "Dumping PulseAudio state: "; + qCritical() << "mainLoop: " << pulseAudioPointers.mainLoop; + qCritical() << "api: " << pulseAudioPointers.api; + qCritical() << "context: " << pulseAudioPointers.context; + + qCritical() << ""; + + qCritical() << "Data:"; + qCritical() << "\tdefaultSinkOutputDeviceId: " + << pulseAudioData.defaultSinkOutputDeviceId; + qCritical() << "\tdefaultSourceInputDeviceId: " + << pulseAudioData.defaultSourceInputDeviceId; + + qCritical() << ""; + + qCritical() << "\tcurrentDefaultSinkInfo name: " + << pulseAudioData.currentDefaultSinkInfo.name; + qCritical() << "\tcurrentDefaultSourceInfo name: " + << pulseAudioData.currentDefaultSourceInfo.name; + + qCritical() << ""; + + qCritical() << "sinkOutputDevices: "; + if ( pulseAudioData.sinkOutputDevices.empty() ) + qCritical() << "\tOutput devices size zero."; + for ( const auto& device : pulseAudioData.sinkOutputDevices ) + { + qCritical() << "\tDevice Name: " << device.name(); + qCritical() << "\tDevice Id: " << device.id(); + } + + qCritical() << ""; + + qCritical() << "sourceInputDevices: "; + if ( pulseAudioData.sourceInputDevices.empty() ) + qCritical() << "\tInput devices size zero."; + for ( const auto& device : pulseAudioData.sourceInputDevices ) + { + qCritical() << "\tDevice Name: " << device.name(); + qCritical() << "\tDevice Id: " << device.id(); + } + + qCritical() << "____"; +} + +PulseAudioIsLastMeaning getIsLastMeaning( const int isLast ) noexcept +{ + if ( isLast < 0 ) + { + qCritical() << "Error in isLast."; + dumpPulseAudioState(); + return PulseAudioIsLastMeaning::Error; + } + + if ( isLast > 0 ) + { + return PulseAudioIsLastMeaning::PreviousDeviceWasLastReal; + } + + return PulseAudioIsLastMeaning::RealDevice; +} + +std::string getDeviceName( pa_proplist* prop_list ) +{ + if ( !prop_list ) + { + qCritical() << "proplist not valid."; + } + + constexpr auto deviceDescription = "device.description"; + if ( !pa_proplist_contains( prop_list, deviceDescription ) ) + { + qCritical() << "proplist does not contain '" << deviceDescription + << "'."; + return "ERROR"; + } + + return { pa_proplist_gets( prop_list, deviceDescription ) }; +} + +template void deviceCallback( const T* info, const int isLast ) +{ + static_assert( + std::is_same_v || std::is_same_v, + "Function should only be used with pa_source_info or pa_sink_info." ); + + const auto deviceState = getIsLastMeaning( isLast ); + if ( deviceState == PulseAudioIsLastMeaning::PreviousDeviceWasLastReal ) + { + loopControl = PulseAudioLoopControl::Stop; + return; + } + if ( deviceState == PulseAudioIsLastMeaning::Error ) + { + qCritical() << "Error in deviceCallback function."; + dumpPulseAudioState(); + loopControl = PulseAudioLoopControl::Stop; + return; + } + + if constexpr ( std::is_same_v ) + { + if ( info->name == pulseAudioData.defaultSourceInputDeviceId ) + { + pulseAudioData.currentDefaultSourceInfo = *info; + } + + /* + qDebug() << "Adding device to input: '" << i->name << "', '" + << getDeviceName( i->proplist ) << "'."; + */ + pulseAudioData.sourceInputDevices.push_back( + AudioDevice( info->name, getDeviceName( info->proplist ) ) ); + } + + else if constexpr ( std::is_same_v ) + { + if ( info->name == pulseAudioData.defaultSinkOutputDeviceId ) + { + pulseAudioData.currentDefaultSinkInfo = *info; + } + + /* + qDebug() << "Adding device to output: '" << i->name << "', '" + << getDeviceName( i->proplist ) << "'."; + */ + pulseAudioData.sinkOutputDevices.push_back( + AudioDevice( info->name, getDeviceName( info->proplist ) ) ); + } +} + +void setInputDevicesCallback( pa_context* /*ctx*/, + const pa_source_info* info, + int isLast, + void* /*userdata*/ ) +{ + deviceCallback( info, isLast ); +} + +void setOutputDevicesCallback( pa_context* /*ctx*/, + const pa_sink_info* out_info, + int isLast, + void* /*userdata*/ ) +{ + deviceCallback( out_info, isLast ); +} + +void getDefaultDevicesCallback( pa_context* /*ctx*/, + const pa_server_info* out_info, + void* /*userdata*/ ) +{ + if ( !out_info ) + { + qCritical() << "i == 0"; + pulseAudioData.defaultSinkOutputDeviceId = "DDO:ERROR"; + pulseAudioData.defaultSourceInputDeviceId = "DDI:ERROR"; + return; + } + + // Copy because we don't know how long the pa_server_info* lives for + pulseAudioData.defaultSinkOutputDeviceId.assign( + out_info->default_sink_name ); + pulseAudioData.defaultSourceInputDeviceId.assign( + out_info->default_source_name ); + + loopControl = PulseAudioLoopControl::Stop; + + /* + qDebug() << "getDefaultDevicesCallback done with sink output device: '" + << pulseAudioData.defaultSinkOutputDeviceId + << "' and source input '" + << pulseAudioData.defaultSourceInputDeviceId << "'."; + */ +} + +void stateCallbackFunction( pa_context* ctx, void* /*userdata*/ ) +{ + switch ( pa_context_get_state( ctx ) ) + { + case PA_CONTEXT_TERMINATED: + qCritical() << "PA_CONTEXT_TERMINATED in stateCallbackFunction"; + dumpPulseAudioState(); + return; + case PA_CONTEXT_CONNECTING: + qDebug() << "PA_CONTEXT_CONNECTING"; + return; + case PA_CONTEXT_AUTHORIZING: + qDebug() << "PA_CONTEXT_AUTHORIZING"; + return; + case PA_CONTEXT_SETTING_NAME: + qDebug() << "PA_CONTEXT_SETTING_NAME"; + return; + case PA_CONTEXT_UNCONNECTED: + qDebug() << "PA_CONTEXT_UNCONNECTED"; + return; + case PA_CONTEXT_FAILED: + qDebug() << "PA_CONTEXT_FAILED"; + return; + + case PA_CONTEXT_READY: + qDebug() << "PA_CONTEXT_READY"; + loopControl = PulseAudioLoopControl::Stop; + return; + } +} + +void updateAllPulseData() +{ + constexpr auto noCustomUserdata = nullptr; + + pa_context_get_server_info( pulseAudioPointers.context, + getDefaultDevicesCallback, + noCustomUserdata ); + customPulseLoop(); + + pulseAudioData.sinkOutputDevices.clear(); + pa_context_get_sink_info_list( pulseAudioPointers.context, + setOutputDevicesCallback, + noCustomUserdata ); + customPulseLoop(); + + pulseAudioData.sourceInputDevices.clear(); + pa_context_get_source_info_list( + pulseAudioPointers.context, setInputDevicesCallback, noCustomUserdata ); + customPulseLoop(); + + qDebug() << "updateAllPulseData done."; +} + +void successCallback( pa_context* /*ctx*/, int success, void* successVariable ) +{ + if ( successVariable != nullptr ) + { + *static_cast( successVariable ) = success; + } + + if ( !success ) + { + qCritical() << "Non successful callback operation."; + dumpPulseAudioState(); + } + + loopControl = PulseAudioLoopControl::Stop; +} + +void setPlaybackDeviceInternal( const std::string& dev_id ) +{ + updateAllPulseData(); + + auto success = false; + pa_context_set_default_sink( + pulseAudioPointers.context, dev_id.c_str(), successCallback, &success ); + + customPulseLoop(); + + if ( !success ) + { + qCritical() << "setPlaybackDeviceInternal failed to set default sink " + "for device '" + << dev_id << "'."; + } + + qDebug() << "setPlaybackDeviceInternal done with id: " << dev_id; +} + +std::string getCurrentDefaultPlaybackDeviceName() +{ + updateAllPulseData(); + + for ( const auto& dev : pulseAudioData.sinkOutputDevices ) + { + if ( dev.id() == pulseAudioData.defaultSinkOutputDeviceId ) + { + qDebug() << "getCurrentDefaultPlaybackDeviceName done with " + << dev.name(); + return dev.name(); + } + } + qCritical() << "Unable to find default playback device."; + + return "ERROR"; +} + +std::string getCurrentDefaultPlaybackDeviceId() +{ + updateAllPulseData(); + + qDebug() << "getCurrentDefaultPlaybackDeviceId done with " + << pulseAudioData.defaultSinkOutputDeviceId; + + return pulseAudioData.defaultSinkOutputDeviceId; +} + +std::string getCurrentDefaultRecordingDeviceName() +{ + updateAllPulseData(); + + for ( const auto& dev : pulseAudioData.sourceInputDevices ) + { + if ( dev.id() == pulseAudioData.defaultSourceInputDeviceId ) + { + qDebug() << "getCurrentDefaultRecordingDeviceName done with: " + << dev.name(); + return dev.name(); + } + } + qCritical() << "Unable to find default playback device."; + + return "ERROR"; +} + +std::string getCurrentDefaultRecordingDeviceId() +{ + updateAllPulseData(); + + qDebug() << "getCurrentDefaultRecordingDeviceId done with " + << pulseAudioData.defaultSourceInputDeviceId; + + return pulseAudioData.defaultSourceInputDeviceId; +} + +std::vector returnRecordingDevices() +{ + updateAllPulseData(); + + return pulseAudioData.sourceInputDevices; +} + +std::vector returnPlaybackDevices() +{ + updateAllPulseData(); + + return pulseAudioData.sinkOutputDevices; +} + +bool isMicrophoneValid() +{ + updateAllPulseData(); + + const auto valid = !pulseAudioData.defaultSourceInputDeviceId.empty(); + + return valid; +} + +float getMicrophoneVolume() +{ + updateAllPulseData(); + + const auto linearVolume = pa_sw_volume_to_linear( + pa_cvolume_avg( &pulseAudioData.currentDefaultSourceInfo.volume ) ); + + return static_cast( linearVolume ); +} + +bool getMicrophoneMuted() +{ + updateAllPulseData(); + + return pulseAudioData.currentDefaultSourceInfo.mute; +} + +void sourceOutputCallback( pa_context* ctx, + const pa_source_output_info* info, + int isLast, + void* success ) +{ + const auto deviceState = getIsLastMeaning( isLast ); + if ( deviceState == PulseAudioIsLastMeaning::PreviousDeviceWasLastReal ) + { + loopControl = PulseAudioLoopControl::Stop; + return; + } + if ( deviceState == PulseAudioIsLastMeaning::Error ) + { + qCritical() << "Error in sourceOutputCallback function."; + dumpPulseAudioState(); + return; + } + + const auto sourceOutputIndex = info->index; + const auto sourceIndex = pulseAudioData.currentDefaultSourceInfo.index; + + qDebug() << "Attempting to move sourceOutputIndex: '" << sourceOutputIndex + << "' to sourceIndex '" << sourceIndex + << "' with source output name " << info->name << "."; + + pa_context_move_source_output_by_index( + ctx, sourceOutputIndex, sourceIndex, successCallback, success ); +} + +void setMicrophoneDevice( const std::string& dev_id ) +{ + qDebug() << "setMicrophoneDevice called with 'id': " << dev_id; + + updateAllPulseData(); + + auto success = false; + pa_context_set_default_source( + pulseAudioPointers.context, dev_id.c_str(), successCallback, &success ); + + customPulseLoop(); + + if ( !success ) + { + qCritical() << "Error setting microphone device for '" << dev_id + << "'."; + } + + updateAllPulseData(); + + pa_context_get_source_output_info_list( + pulseAudioPointers.context, sourceOutputCallback, &success ); + + customPulseLoop(); + + if ( !success ) + { + qCritical() << "Error in moving source outputs to new source."; + } + + updateAllPulseData(); + + qDebug() << "setMicrophoneDevice done."; +} + +bool setPlaybackVolume( const float volume ) +{ + qDebug() << "setPlaybackVolume called with 'volume': " << volume; + + updateAllPulseData(); + + auto pulseVolume = pulseAudioData.currentDefaultSinkInfo.volume; + const auto vol = pa_sw_volume_from_linear( static_cast( volume ) ); + + pa_cvolume_set( &pulseVolume, pulseVolume.channels, vol ); + + auto success = false; + pa_context_set_sink_volume_by_name( + pulseAudioPointers.context, + pulseAudioData.defaultSinkOutputDeviceId.c_str(), + &pulseVolume, + successCallback, + &success ); + + customPulseLoop(); + + if ( !success ) + { + qCritical() << "setPlaybackVolume failed to set volume '" << volume + << "' for device '" + << pulseAudioData.defaultSinkOutputDeviceId << "'."; + } + + qDebug() << "setPlaybackVolume done with 'success': " << success; + + return success; +} + +bool setMicrophoneVolume( const float volume ) +{ + qDebug() << "setMicrophoneVolume called with 'volume': " << volume; + + updateAllPulseData(); + + auto pulseVolume = pulseAudioData.currentDefaultSourceInfo.volume; + const auto vol = pa_sw_volume_from_linear( static_cast( volume ) ); + + pa_cvolume_set( &pulseVolume, pulseVolume.channels, vol ); + + auto success = false; + pa_context_set_source_volume_by_name( + pulseAudioPointers.context, + pulseAudioData.defaultSourceInputDeviceId.c_str(), + &pulseVolume, + successCallback, + &success ); + + customPulseLoop(); + + if ( !success ) + { + qCritical() << "seMicrophoneVolume failed to set volume '" << volume + << "' for device '" + << pulseAudioData.defaultSourceInputDeviceId << "'."; + } + + qDebug() << "setMicrophoneVolume done with 'success': " << success; + + return success; +} + +bool setMicMuteState( const bool muted ) +{ + qDebug() << "setMicMuteState called with 'muted': " << muted; + bool success = false; + + pa_context_set_source_mute_by_name( + pulseAudioPointers.context, + pulseAudioData.defaultSourceInputDeviceId.c_str(), + muted, + successCallback, + &success ); + + customPulseLoop(); + + if ( !success ) + { + qCritical() << "setMicMuteState failed to set muted '" << muted + << "' for device '" + << pulseAudioData.defaultSourceInputDeviceId << "'."; + } + + qDebug() << "setMicMuteState done with 'success': " << success; + + return success; +} + +void restorePulseAudioState() +{ + qDebug() << "restorePulseAudioState called."; + + setPlaybackDeviceInternal( pulseAudioData.originalDefaultOutputDeviceId ); + setPlaybackVolume( pulseAudioData.originalDefaultOutputDeviceVolume ); + + setMicrophoneDevice( pulseAudioData.originalDefaultInputDeviceId ); + setMicrophoneVolume( pulseAudioData.originalDefaultInputDeviceVolume ); + + qDebug() << "restorePulseAudioState done."; +} + +void initializePulseAudio() +{ + qDebug() << "initializePulseAudio called."; + + pulseAudioPointers.mainLoop = pa_mainloop_new(); + + pulseAudioPointers.api = pa_mainloop_get_api( pulseAudioPointers.mainLoop ); + + pulseAudioPointers.context + = pa_context_new( pulseAudioPointers.api, "openvr-advanced-settings" ); + + constexpr auto noCustomUserdata = nullptr; + pa_context_set_state_callback( + pulseAudioPointers.context, stateCallbackFunction, noCustomUserdata ); + + constexpr auto useDefaultServer = nullptr; + constexpr auto useDefaultSpawnApi = nullptr; + pa_context_connect( pulseAudioPointers.context, + useDefaultServer, + PA_CONTEXT_NOFLAGS, + useDefaultSpawnApi ); + customPulseLoop(); + + pulseAudioData.originalDefaultInputDeviceId + = getCurrentDefaultRecordingDeviceId(); + + pulseAudioData.originalDefaultInputDeviceVolume + = static_cast( pa_sw_volume_to_linear( pa_cvolume_avg( + &pulseAudioData.currentDefaultSourceInfo.volume ) ) ); + + pulseAudioData.originalDefaultOutputDeviceId + = getCurrentDefaultPlaybackDeviceId(); + + pulseAudioData.originalDefaultOutputDeviceVolume + = static_cast( pa_sw_volume_to_linear( + pa_cvolume_avg( &pulseAudioData.currentDefaultSinkInfo.volume ) ) ); + + qDebug() << "initializePulseAudio finished."; +} +} // namespace advsettings // application namespace namespace advsettings @@ -21,9 +659,10 @@ void AudioManagerPulse::init( AudioTabController* controller ) initializePulseAudio(); } -void AudioManagerPulse::setPlaybackDevice( const std::string& id, bool notify ) +void AudioManagerPulse::setPlaybackDevice( const std::string& dev_id, + bool notify ) { - setPlaybackDeviceInternal( id ); + setPlaybackDeviceInternal( dev_id ); if ( notify ) { @@ -41,11 +680,10 @@ std::string AudioManagerPulse::getPlaybackDevId() return getCurrentDefaultPlaybackDeviceId(); } -void AudioManagerPulse::setMirrorDevice( const std::string& id, bool notify ) +void AudioManagerPulse::setMirrorDevice( const std::string& /*dev_id*/, + bool /*notify*/ ) { // noop - UNREFERENCED_PARAMETER( id ); - UNREFERENCED_PARAMETER( notify ); } bool AudioManagerPulse::isMirrorValid() @@ -68,9 +706,8 @@ float AudioManagerPulse::getMirrorVolume() return 0; } -bool AudioManagerPulse::setMirrorVolume( float value ) +bool AudioManagerPulse::setMirrorVolume( float /*value*/ ) { - UNREFERENCED_PARAMETER( value ); return false; } @@ -79,9 +716,8 @@ bool AudioManagerPulse::getMirrorMuted() return true; } -bool AudioManagerPulse::setMirrorMuted( bool value ) +bool AudioManagerPulse::setMirrorMuted( bool /*value*/ ) { - UNREFERENCED_PARAMETER( value ); return false; } @@ -90,9 +726,9 @@ bool AudioManagerPulse::isMicValid() return isMicrophoneValid(); } -void AudioManagerPulse::setMicDevice( const std::string& id, bool notify ) +void AudioManagerPulse::setMicDevice( const std::string& dev_id, bool notify ) { - setMicrophoneDevice( id ); + setMicrophoneDevice( dev_id ); if ( notify ) { diff --git a/src/tabcontrollers/audiomanager/AudioManagerPulse.h b/src/tabcontrollers/audiomanager/AudioManagerPulse.h index 6583b148..589d527e 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerPulse.h +++ b/src/tabcontrollers/audiomanager/AudioManagerPulse.h @@ -8,36 +8,35 @@ namespace advsettings class AudioManagerPulse : public AudioManager { public: - virtual void init( AudioTabController* controller ) override; + void init( AudioTabController* controller ) override; ~AudioManagerPulse() override; - virtual void setPlaybackDevice( const std::string& id, - bool notify = true ) override; - virtual std::string getPlaybackDevName() override; - virtual std::string getPlaybackDevId() override; - - virtual void setMirrorDevice( const std::string& id, - bool notify = true ) override; - virtual bool isMirrorValid() override; - virtual std::string getMirrorDevName() override; - virtual std::string getMirrorDevId() override; - virtual float getMirrorVolume() override; - virtual bool setMirrorVolume( float value ) override; - virtual bool getMirrorMuted() override; - virtual bool setMirrorMuted( bool value ) override; - - virtual bool isMicValid() override; - virtual void setMicDevice( const std::string& id, - bool notify = true ) override; - virtual std::string getMicDevName() override; - virtual std::string getMicDevId() override; - virtual float getMicVolume() override; - virtual bool setMicVolume( float value ) override; - virtual bool getMicMuted() override; - virtual bool setMicMuted( bool value ) override; - - virtual std::vector getRecordingDevices() override; - virtual std::vector getPlaybackDevices() override; + void setPlaybackDevice( const std::string& dev_id, + bool notify = true ) override; + std::string getPlaybackDevName() override; + std::string getPlaybackDevId() override; + + void setMirrorDevice( const std::string& dev_id, + bool notify = true ) override; + bool isMirrorValid() override; + std::string getMirrorDevName() override; + std::string getMirrorDevId() override; + float getMirrorVolume() override; + bool setMirrorVolume( float value ) override; + bool getMirrorMuted() override; + bool setMirrorMuted( bool value ) override; + + bool isMicValid() override; + void setMicDevice( const std::string& dev_id, bool notify = true ) override; + std::string getMicDevName() override; + std::string getMicDevId() override; + float getMicVolume() override; + bool setMicVolume( float value ) override; + bool getMicMuted() override; + bool setMicMuted( bool value ) override; + + std::vector getRecordingDevices() override; + std::vector getPlaybackDevices() override; private: AudioTabController* m_controller; diff --git a/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h b/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h deleted file mode 100644 index a16faa62..00000000 --- a/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h +++ /dev/null @@ -1,656 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include "AudioManager.h" - -// Used to get the compiler to shut up about C4100: unreferenced formal -// parameter. The cast is to get GCC to shut up about it. -#define UNREFERENCED_PARAMETER( P ) static_cast( ( P ) ) - -namespace advsettings -{ -enum class PulseAudioIsLastMeaning -{ - Error, - RealDevice, - PreviousDeviceWasLastReal, -}; - -enum class PulseAudioLoopControl -{ - Stop, - Run, -}; - -struct -{ - pa_mainloop* mainLoop; - pa_mainloop_api* api; - pa_context* context; -} pulseAudioPointers; - -struct -{ - std::string defaultSinkOutputDeviceId; - std::string defaultSourceInputDeviceId; - - std::string originalDefaultOutputDeviceId; - std::string originalDefaultInputDeviceId; - - float originalDefaultOutputDeviceVolume; - float originalDefaultInputDeviceVolume; - - std::vector sinkOutputDevices; - std::vector sourceInputDevices; - - pa_sink_info currentDefaultSinkInfo; - pa_source_info currentDefaultSourceInfo; -} pulseAudioData; - -static PulseAudioLoopControl loopControl = PulseAudioLoopControl::Run; - -void customPulseLoop() -{ - while ( loopControl == PulseAudioLoopControl::Run ) - { - constexpr auto noReturnValue = nullptr; - constexpr auto blockForEvents = 1; - pa_mainloop_iterate( - pulseAudioPointers.mainLoop, blockForEvents, noReturnValue ); - } - - loopControl = PulseAudioLoopControl::Run; -} - -// Error function -void dumpPulseAudioState() -{ - qCritical() << "____"; - - qCritical() << "Dumping PulseAudio state: "; - qCritical() << "mainLoop: " << pulseAudioPointers.mainLoop; - qCritical() << "api: " << pulseAudioPointers.api; - qCritical() << "context: " << pulseAudioPointers.context; - - qCritical() << ""; - - qCritical() << "Data:"; - qCritical() << "\tdefaultSinkOutputDeviceId: " - << pulseAudioData.defaultSinkOutputDeviceId; - qCritical() << "\tdefaultSourceInputDeviceId: " - << pulseAudioData.defaultSourceInputDeviceId; - - qCritical() << ""; - - qCritical() << "\tcurrentDefaultSinkInfo name: " - << pulseAudioData.currentDefaultSinkInfo.name; - qCritical() << "\tcurrentDefaultSourceInfo name: " - << pulseAudioData.currentDefaultSourceInfo.name; - - qCritical() << ""; - - qCritical() << "sinkOutputDevices: "; - if ( pulseAudioData.sinkOutputDevices.size() == 0 ) - qCritical() << "\tOutput devices size zero."; - for ( const auto& device : pulseAudioData.sinkOutputDevices ) - { - qCritical() << "\tDevice Name: " << device.name(); - qCritical() << "\tDevice Id: " << device.id(); - } - - qCritical() << ""; - - qCritical() << "sourceInputDevices: "; - if ( pulseAudioData.sourceInputDevices.size() == 0 ) - qCritical() << "\tInput devices size zero."; - for ( const auto& device : pulseAudioData.sourceInputDevices ) - { - qCritical() << "\tDevice Name: " << device.name(); - qCritical() << "\tDevice Id: " << device.id(); - } - - qCritical() << "____"; -} - -PulseAudioIsLastMeaning getIsLastMeaning( const int isLast ) noexcept -{ - if ( isLast < 0 ) - { - qCritical() << "Error in isLast."; - dumpPulseAudioState(); - return PulseAudioIsLastMeaning::Error; - } - - if ( isLast > 0 ) - { - return PulseAudioIsLastMeaning::PreviousDeviceWasLastReal; - } - - return PulseAudioIsLastMeaning::RealDevice; -} - -std::string getDeviceName( pa_proplist* p ) -{ - if ( !p ) - { - qCritical() << "proplist not valid."; - } - - constexpr auto deviceDescription = "device.description"; - if ( !pa_proplist_contains( p, deviceDescription ) ) - { - qCritical() << "proplist does not contain '" << deviceDescription - << "'."; - return "ERROR"; - } - - std::string s; - s.assign( pa_proplist_gets( p, deviceDescription ) ); - - return s; -} - -template void deviceCallback( const T* i, const int isLast ) -{ - static_assert( - std::is_same::value - || std::is_same::value, - "Function should only be used with pa_source_info or pa_sink_info." ); - - const auto deviceState = getIsLastMeaning( isLast ); - if ( deviceState == PulseAudioIsLastMeaning::PreviousDeviceWasLastReal ) - { - loopControl = PulseAudioLoopControl::Stop; - return; - } - else if ( deviceState == PulseAudioIsLastMeaning::Error ) - { - qCritical() << "Error in deviceCallback function."; - dumpPulseAudioState(); - loopControl = PulseAudioLoopControl::Stop; - return; - } - - if constexpr ( std::is_same::value ) - { - if ( i->name == pulseAudioData.defaultSourceInputDeviceId ) - { - pulseAudioData.currentDefaultSourceInfo = *i; - } - - /* - qDebug() << "Adding device to input: '" << i->name << "', '" - << getDeviceName( i->proplist ) << "'."; - */ - pulseAudioData.sourceInputDevices.push_back( - AudioDevice( i->name, getDeviceName( i->proplist ) ) ); - } - - else if constexpr ( std::is_same::value ) - { - if ( i->name == pulseAudioData.defaultSinkOutputDeviceId ) - { - pulseAudioData.currentDefaultSinkInfo = *i; - } - - /* - qDebug() << "Adding device to output: '" << i->name << "', '" - << getDeviceName( i->proplist ) << "'."; - */ - pulseAudioData.sinkOutputDevices.push_back( - AudioDevice( i->name, getDeviceName( i->proplist ) ) ); - } -} - -void setInputDevicesCallback( pa_context* c, - const pa_source_info* i, - int isLast, - void* userdata ) -{ - UNREFERENCED_PARAMETER( userdata ); - UNREFERENCED_PARAMETER( c ); - - deviceCallback( i, isLast ); -} - -void setOutputDevicesCallback( pa_context* c, - const pa_sink_info* i, - int isLast, - void* userdata ) -{ - UNREFERENCED_PARAMETER( userdata ); - UNREFERENCED_PARAMETER( c ); - - deviceCallback( i, isLast ); -} - -void getDefaultDevicesCallback( pa_context* c, - const pa_server_info* i, - void* userdata ) -{ - UNREFERENCED_PARAMETER( c ); - UNREFERENCED_PARAMETER( userdata ); - - if ( !i ) - { - qCritical() << "i == 0"; - pulseAudioData.defaultSinkOutputDeviceId = "DDO:ERROR"; - pulseAudioData.defaultSourceInputDeviceId = "DDI:ERROR"; - return; - } - - // Copy because we don't know how long the pa_server_info* lives for - pulseAudioData.defaultSinkOutputDeviceId.assign( i->default_sink_name ); - pulseAudioData.defaultSourceInputDeviceId.assign( i->default_source_name ); - - loopControl = PulseAudioLoopControl::Stop; - - /* - qDebug() << "getDefaultDevicesCallback done with sink output device: '" - << pulseAudioData.defaultSinkOutputDeviceId - << "' and source input '" - << pulseAudioData.defaultSourceInputDeviceId << "'."; - */ -} - -void stateCallbackFunction( pa_context* c, void* userdata ) -{ - UNREFERENCED_PARAMETER( c ); - UNREFERENCED_PARAMETER( userdata ); - - switch ( pa_context_get_state( c ) ) - { - case PA_CONTEXT_TERMINATED: - qCritical() << "PA_CONTEXT_TERMINATED in stateCallbackFunction"; - dumpPulseAudioState(); - return; - case PA_CONTEXT_CONNECTING: - qDebug() << "PA_CONTEXT_CONNECTING"; - return; - case PA_CONTEXT_AUTHORIZING: - qDebug() << "PA_CONTEXT_AUTHORIZING"; - return; - case PA_CONTEXT_SETTING_NAME: - qDebug() << "PA_CONTEXT_SETTING_NAME"; - return; - case PA_CONTEXT_UNCONNECTED: - qDebug() << "PA_CONTEXT_UNCONNECTED"; - return; - case PA_CONTEXT_FAILED: - qDebug() << "PA_CONTEXT_FAILED"; - return; - - case PA_CONTEXT_READY: - qDebug() << "PA_CONTEXT_READY"; - loopControl = PulseAudioLoopControl::Stop; - return; - } -} - -void updateAllPulseData() -{ - constexpr auto noCustomUserdata = nullptr; - - pa_context_get_server_info( pulseAudioPointers.context, - getDefaultDevicesCallback, - noCustomUserdata ); - customPulseLoop(); - - pulseAudioData.sinkOutputDevices.clear(); - pa_context_get_sink_info_list( pulseAudioPointers.context, - setOutputDevicesCallback, - noCustomUserdata ); - customPulseLoop(); - - pulseAudioData.sourceInputDevices.clear(); - pa_context_get_source_info_list( - pulseAudioPointers.context, setInputDevicesCallback, noCustomUserdata ); - customPulseLoop(); - - qDebug() << "updateAllPulseData done."; -} - -void successCallback( pa_context* c, int success, void* successVariable ) -{ - UNREFERENCED_PARAMETER( c ); - - if ( successVariable != nullptr ) - { - *static_cast( successVariable ) = success; - } - - if ( !success ) - { - qCritical() << "Non successful callback operation."; - dumpPulseAudioState(); - } - - loopControl = PulseAudioLoopControl::Stop; -} - -void setPlaybackDeviceInternal( const std::string& id ) -{ - updateAllPulseData(); - - auto success = false; - pa_context_set_default_sink( - pulseAudioPointers.context, id.c_str(), successCallback, &success ); - - customPulseLoop(); - - if ( !success ) - { - qCritical() << "setPlaybackDeviceInternal failed to set default sink " - "for device '" - << id << "'."; - } - - qDebug() << "setPlaybackDeviceInternal done with id: " << id; -} - -std::string getCurrentDefaultPlaybackDeviceName() -{ - updateAllPulseData(); - - for ( const auto& dev : pulseAudioData.sinkOutputDevices ) - { - if ( dev.id() == pulseAudioData.defaultSinkOutputDeviceId ) - { - qDebug() << "getCurrentDefaultPlaybackDeviceName done with " - << dev.name(); - return dev.name(); - } - } - qCritical() << "Unable to find default playback device."; - - return "ERROR"; -} - -std::string getCurrentDefaultPlaybackDeviceId() -{ - updateAllPulseData(); - - qDebug() << "getCurrentDefaultPlaybackDeviceId done with " - << pulseAudioData.defaultSinkOutputDeviceId; - - return pulseAudioData.defaultSinkOutputDeviceId; -} - -std::string getCurrentDefaultRecordingDeviceName() -{ - updateAllPulseData(); - - for ( const auto& dev : pulseAudioData.sourceInputDevices ) - { - if ( dev.id() == pulseAudioData.defaultSourceInputDeviceId ) - { - qDebug() << "getCurrentDefaultRecordingDeviceName done with: " - << dev.name(); - return dev.name(); - } - } - qCritical() << "Unable to find default playback device."; - - return "ERROR"; -} - -std::string getCurrentDefaultRecordingDeviceId() -{ - updateAllPulseData(); - - qDebug() << "getCurrentDefaultRecordingDeviceId done with " - << pulseAudioData.defaultSourceInputDeviceId; - - return pulseAudioData.defaultSourceInputDeviceId; -} - -std::vector returnRecordingDevices() -{ - updateAllPulseData(); - - return pulseAudioData.sourceInputDevices; -} - -std::vector returnPlaybackDevices() -{ - updateAllPulseData(); - - return pulseAudioData.sinkOutputDevices; -} - -bool isMicrophoneValid() -{ - updateAllPulseData(); - - const auto valid = pulseAudioData.defaultSourceInputDeviceId != ""; - - return valid; -} - -float getMicrophoneVolume() -{ - updateAllPulseData(); - - const auto linearVolume = pa_sw_volume_to_linear( - pa_cvolume_avg( &pulseAudioData.currentDefaultSourceInfo.volume ) ); - - return static_cast( linearVolume ); -} - -bool getMicrophoneMuted() -{ - updateAllPulseData(); - - return pulseAudioData.currentDefaultSourceInfo.mute; -} - -void sourceOutputCallback( pa_context* c, - const pa_source_output_info* i, - int isLast, - void* success ) -{ - const auto deviceState = getIsLastMeaning( isLast ); - if ( deviceState == PulseAudioIsLastMeaning::PreviousDeviceWasLastReal ) - { - loopControl = PulseAudioLoopControl::Stop; - return; - } - else if ( deviceState == PulseAudioIsLastMeaning::Error ) - { - qCritical() << "Error in sourceOutputCallback function."; - dumpPulseAudioState(); - return; - } - - const auto sourceOutputIndex = i->index; - const auto sourceIndex = pulseAudioData.currentDefaultSourceInfo.index; - - qDebug() << "Attempting to move sourceOutputIndex: '" << sourceOutputIndex - << "' to sourceIndex '" << sourceIndex - << "' with source output name " << i->name << "."; - - pa_context_move_source_output_by_index( - c, sourceOutputIndex, sourceIndex, successCallback, &success ); -} - -void setMicrophoneDevice( const std::string& id ) -{ - qDebug() << "setMicrophoneDevice called with 'id': " << id; - - updateAllPulseData(); - - auto success = false; - pa_context_set_default_source( - pulseAudioPointers.context, id.c_str(), successCallback, &success ); - - customPulseLoop(); - - if ( !success ) - { - qCritical() << "Error setting microphone device for '" << id << "'."; - } - - updateAllPulseData(); - - pa_context_get_source_output_info_list( - pulseAudioPointers.context, sourceOutputCallback, &success ); - - customPulseLoop(); - - if ( !success ) - { - qCritical() << "Error in moving source outputs to new source."; - } - - updateAllPulseData(); - - qDebug() << "setMicrophoneDevice done."; -} - -bool setPlaybackVolume( const float volume ) -{ - qDebug() << "setPlaybackVolume called with 'volume': " << volume; - - updateAllPulseData(); - - auto pulseVolume = pulseAudioData.currentDefaultSinkInfo.volume; - const auto vol = pa_sw_volume_from_linear( static_cast( volume ) ); - - pa_cvolume_set( &pulseVolume, pulseVolume.channels, vol ); - - auto success = false; - pa_context_set_sink_volume_by_name( - pulseAudioPointers.context, - pulseAudioData.defaultSinkOutputDeviceId.c_str(), - &pulseVolume, - successCallback, - &success ); - - customPulseLoop(); - - if ( !success ) - { - qCritical() << "setPlaybackVolume failed to set volume '" << volume - << "' for device '" - << pulseAudioData.defaultSinkOutputDeviceId << "'."; - } - - qDebug() << "setPlaybackVolume done with 'success': " << success; - - return success; -} - -bool setMicrophoneVolume( const float volume ) -{ - qDebug() << "setMicrophoneVolume called with 'volume': " << volume; - - updateAllPulseData(); - - auto pulseVolume = pulseAudioData.currentDefaultSourceInfo.volume; - const auto vol = pa_sw_volume_from_linear( static_cast( volume ) ); - - pa_cvolume_set( &pulseVolume, pulseVolume.channels, vol ); - - auto success = false; - pa_context_set_source_volume_by_name( - pulseAudioPointers.context, - pulseAudioData.defaultSourceInputDeviceId.c_str(), - &pulseVolume, - successCallback, - &success ); - - customPulseLoop(); - - if ( !success ) - { - qCritical() << "seMicrophoneVolume failed to set volume '" << volume - << "' for device '" - << pulseAudioData.defaultSourceInputDeviceId << "'."; - } - - qDebug() << "setMicrophoneVolume done with 'success': " << success; - - return success; -} - -bool setMicMuteState( const bool muted ) -{ - qDebug() << "setMicMuteState called with 'muted': " << muted; - bool success = false; - - pa_context_set_source_mute_by_name( - pulseAudioPointers.context, - pulseAudioData.defaultSourceInputDeviceId.c_str(), - muted, - successCallback, - &success ); - - customPulseLoop(); - - if ( !success ) - { - qCritical() << "setMicMuteState failed to set muted '" << muted - << "' for device '" - << pulseAudioData.defaultSourceInputDeviceId << "'."; - } - - qDebug() << "setMicMuteState done with 'success': " << success; - - return success; -} - -void restorePulseAudioState() -{ - qDebug() << "restorePulseAudioState called."; - - setPlaybackDeviceInternal( pulseAudioData.originalDefaultOutputDeviceId ); - setPlaybackVolume( pulseAudioData.originalDefaultOutputDeviceVolume ); - - setMicrophoneDevice( pulseAudioData.originalDefaultInputDeviceId ); - setMicrophoneVolume( pulseAudioData.originalDefaultInputDeviceVolume ); - - qDebug() << "restorePulseAudioState done."; -} - -void initializePulseAudio() -{ - qDebug() << "initializePulseAudio called."; - - pulseAudioPointers.mainLoop = pa_mainloop_new(); - - pulseAudioPointers.api = pa_mainloop_get_api( pulseAudioPointers.mainLoop ); - - pulseAudioPointers.context - = pa_context_new( pulseAudioPointers.api, "openvr-advanced-settings" ); - - constexpr auto noCustomUserdata = nullptr; - pa_context_set_state_callback( - pulseAudioPointers.context, stateCallbackFunction, noCustomUserdata ); - - constexpr auto useDefaultServer = nullptr; - constexpr auto useDefaultSpawnApi = nullptr; - pa_context_connect( pulseAudioPointers.context, - useDefaultServer, - PA_CONTEXT_NOFLAGS, - useDefaultSpawnApi ); - customPulseLoop(); - - pulseAudioData.originalDefaultInputDeviceId - = getCurrentDefaultRecordingDeviceId(); - - pulseAudioData.originalDefaultInputDeviceVolume - = static_cast( pa_sw_volume_to_linear( pa_cvolume_avg( - &pulseAudioData.currentDefaultSourceInfo.volume ) ) ); - - pulseAudioData.originalDefaultOutputDeviceId - = getCurrentDefaultPlaybackDeviceId(); - - pulseAudioData.originalDefaultOutputDeviceVolume - = static_cast( pa_sw_volume_to_linear( - pa_cvolume_avg( &pulseAudioData.currentDefaultSinkInfo.volume ) ) ); - - qDebug() << "initializePulseAudio finished."; -} -} // namespace advsettings diff --git a/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp b/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp index 603383ec..2e347d20 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp +++ b/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp @@ -44,7 +44,7 @@ void AudioManagerWindows::init( AudioTabController* var_controller ) audioDeviceEnumerator = getAudioDeviceEnumerator(); if ( !audioDeviceEnumerator ) { - throw std::exception( "Could not create audio device enumerator" ); + throw std::runtime_error( "Could not create audio device enumerator" ); } playbackAudioDevice = getDefaultPlaybackDevice( audioDeviceEnumerator ); if ( !playbackAudioDevice ) diff --git a/src/utils/ChaperoneUtils.cpp b/src/utils/ChaperoneUtils.cpp index 884f1c33..e4bb07d2 100644 --- a/src/utils/ChaperoneUtils.cpp +++ b/src/utils/ChaperoneUtils.cpp @@ -1,40 +1,41 @@ #include "ChaperoneUtils.h" -#include + #include namespace utils { +// NOLINTBEGIN(readability-identifier-length) std::vector ChaperoneUtils::_getDistancesToChaperone( const vr::HmdVector3_t& x ) { std::vector result; - vr::HmdVector3_t* _cornersPtr = _corners.get(); for ( uint32_t i = 0; i < _quadsCount; i++ ) { - uint32_t i2 = ( i + 1 ) % _quadsCount; - vr::HmdVector3_t& r0 = _cornersPtr[i]; - vr::HmdVector3_t& r1 = _cornersPtr[i2]; - float u_x = r1.v[0] - r0.v[0]; - float u_z = r1.v[2] - r0.v[2]; - float r = ( ( x.v[0] - r0.v[0] ) * u_x + ( x.v[2] - r0.v[2] ) * u_z ) - / ( u_x * u_x + u_z * u_z ); + uint32_t const i2 = ( i + 1 ) % _quadsCount; + vr::HmdVector3_t const& r0 = _corners[i]; + vr::HmdVector3_t const& r1 = _corners[i2]; + float const u_x = r1.v[0] - r0.v[0]; + float const u_z = r1.v[2] - r0.v[2]; + float const r + = ( ( x.v[0] - r0.v[0] ) * u_x + ( x.v[2] - r0.v[2] ) * u_z ) + / ( u_x * u_x + u_z * u_z ); // int mode = 0; // 0 .. projected point on segment, 1 .. projected // point outside of segment (r0 closer than r1), 2 .. projected point // outside of segment (r1 closer than r0) - float d; - float x1_x; - float x1_z; + float d = NAN; + float x1_x = NAN; + float x1_z = NAN; if ( r < 0.0f || r > 1.0f ) { // projected point outside of segment float d_x = r0.v[0] - x.v[0]; float d_z = r0.v[2] - x.v[2]; // Crazy casts because clang sees the sqrt call as wanting a double. - float d1 = static_cast( + float const d1 = static_cast( sqrt( static_cast( d_x * d_x + d_z * d_z ) ) ); d_x = r1.v[0] - x.v[0]; d_z = r1.v[2] - x.v[2]; // Crazy casts because clang sees the sqrt call as wanting a double. - float d2 = static_cast( + float const d2 = static_cast( sqrt( static_cast( d_x * d_x + d_z * d_z ) ) ); if ( d1 < d2 ) { @@ -53,8 +54,8 @@ std::vector { // projected point on segment x1_x = r0.v[0] + r * u_x; x1_z = r0.v[2] + r * u_z; - float d_x = x1_x - x.v[0]; - float d_z = x1_z - x.v[2]; + float const d_x = x1_x - x.v[0]; + float const d_z = x1_z - x.v[2]; // Crazy casts because clang sees the sqrt call as wanting a double. d = static_cast( sqrt( static_cast( d_x * d_x + d_z * d_z ) ) ); @@ -67,11 +68,12 @@ std::vector result.push_back( computedQuad ); } return result; + // NOLINTEND(readability-identifier-length) } void ChaperoneUtils::loadChaperoneData( bool fromLiveBounds ) { - std::lock_guard lock( _mutex ); + std::lock_guard const lock( _mutex ); if ( fromLiveBounds ) { @@ -86,34 +88,30 @@ void ChaperoneUtils::loadChaperoneData( bool fromLiveBounds ) if ( _quadsCount > 0 ) { - std::unique_ptr quadsBuffer( - new vr::HmdQuad_t[_quadsCount] ); - vr::HmdQuad_t* quadsBufferPtr = quadsBuffer.get(); - _corners.reset( reinterpret_cast( - new vr::HmdQuad_t[_quadsCount] ) ); - vr::HmdVector3_t* _cornersPtr = _corners.get(); + std::vector quadsBuffer; + quadsBuffer.reserve( _quadsCount ); if ( fromLiveBounds ) { - vr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo( quadsBufferPtr, - &_quadsCount ); + vr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo( + quadsBuffer.data(), &_quadsCount ); } else { vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo( - quadsBufferPtr, &_quadsCount ); + quadsBuffer.data(), &_quadsCount ); } - for ( uint32_t i = 0; i < _quadsCount; i++ ) + for ( uint32_t index = 0; index < _quadsCount; index++ ) { - _cornersPtr[i] = quadsBufferPtr[i].vCorners[0]; - uint32_t i2 = ( i + 1 ) % _quadsCount; - if ( quadsBufferPtr[i].vCorners[3].v[0] - != quadsBufferPtr[i2].vCorners[0].v[0] - || quadsBufferPtr[i].vCorners[3].v[1] - != quadsBufferPtr[i2].vCorners[0].v[1] - || quadsBufferPtr[i].vCorners[3].v[2] - != quadsBufferPtr[i2].vCorners[0].v[2] - || quadsBufferPtr[i].vCorners[0].v[1] != 0.0f ) + _corners[index] = quadsBuffer[index].vCorners[0]; + uint32_t const index2 = ( index + 1 ) % _quadsCount; + if ( quadsBuffer[index].vCorners[3].v[0] + != quadsBuffer[index2].vCorners[0].v[0] + || quadsBuffer[index].vCorners[3].v[1] + != quadsBuffer[index2].vCorners[0].v[1] + || quadsBuffer[index].vCorners[3].v[2] + != quadsBuffer[index2].vCorners[0].v[2] + || quadsBuffer[index].vCorners[0].v[1] != 0.0f ) { _chaperoneWellFormed = false; } diff --git a/src/utils/ChaperoneUtils.h b/src/utils/ChaperoneUtils.h index 8e81948b..7e2cded7 100644 --- a/src/utils/ChaperoneUtils.h +++ b/src/utils/ChaperoneUtils.h @@ -1,21 +1,24 @@ #pragma once -#include #include #include #include #include #include +#include namespace utils { struct ChaperoneQuadData { + // NOLINTBEGIN(misc-non-private-member-variables-in-classes) float distance; vr::HmdVector3_t nearestPoint; - vr::HmdVector3_t corners[2]; + std::array corners; + // NOLINTEND(misc-non-private-member-variables-in-classes) - const vr::HmdVector3_t& closestCorner( const vr::HmdVector3_t& point ) const + [[nodiscard]] const vr::HmdVector3_t& + closestCorner( const vr::HmdVector3_t& point ) const { auto cornerDistanceA = std::pow( point.v[0] - corners[0].v[0], 2.0 ) + std::pow( point.v[2] - corners[0].v[2], 2.0 ); @@ -30,21 +33,22 @@ class ChaperoneUtils private: std::recursive_mutex _mutex; uint32_t _quadsCount = 0; - std::unique_ptr _corners; + std::vector _corners; bool _chaperoneWellFormed = true; std::vector _getDistancesToChaperone( const vr::HmdVector3_t& point ); public: - const vr::HmdVector3_t& getCorner( size_t i ) const noexcept + [[nodiscard]] const vr::HmdVector3_t& + getCorner( size_t index ) const noexcept { - return ( _corners.get() )[i]; + return _corners[index]; } - uint32_t quadsCount() const noexcept + [[nodiscard]] uint32_t quadsCount() const noexcept { return _quadsCount; } - bool isChaperoneWellFormed() const noexcept + [[nodiscard]] bool isChaperoneWellFormed() const noexcept { return _chaperoneWellFormed; } @@ -62,13 +66,11 @@ class ChaperoneUtils { if ( doLock ) { - std::lock_guard lock( _mutex ); - return _getDistancesToChaperone( point ); - } - else - { + std::lock_guard const lock( _mutex ); return _getDistancesToChaperone( point ); } + + return _getDistancesToChaperone( point ); } ChaperoneQuadData getDistanceToChaperone( const vr::HmdVector3_t& point, diff --git a/src/utils/FrameRateUtils.cpp b/src/utils/FrameRateUtils.cpp index 6df0779c..fa2cd597 100644 --- a/src/utils/FrameRateUtils.cpp +++ b/src/utils/FrameRateUtils.cpp @@ -1,6 +1,8 @@ #include "FrameRateUtils.h" -#include + #include +#include +#include namespace utils { @@ -10,8 +12,8 @@ namespace utils * */ unsigned int adjustUpdateRate( const unsigned int baseRefreshKey ) { - double updateRate; - vr::EVRSettingsError vrSettingsError; + double updateRate = NAN; + vr::EVRSettingsError vrSettingsError = {}; updateRate = static_cast( vr::VRSettings()->GetInt32( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_PreferredRefreshRate, @@ -27,8 +29,8 @@ unsigned int adjustUpdateRate( const unsigned int baseRefreshKey ) } // Assume Base 90 hz Refresh - double multiplier = updateRate / 90.0; - unsigned int adjustedRefreshKey = static_cast( + double const multiplier = updateRate / 90.0; + unsigned int const adjustedRefreshKey = static_cast( static_cast( baseRefreshKey ) * multiplier ); if ( adjustedRefreshKey < 45 ) { diff --git a/src/utils/Matrix.h b/src/utils/Matrix.h index a8d8ee9f..0ff4687b 100644 --- a/src/utils/Matrix.h +++ b/src/utils/Matrix.h @@ -12,13 +12,20 @@ constexpr vr::HmdMatrix34_t k_forwardUpMatrix { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, -1.0f, 0.0f, 0.0f } } }; +typedef enum eMatrixAxis +{ + MatrixAxis_X, + MatrixAxis_Y, + MatrixAxis_Z, +} MatrixAxis; + inline vr::HmdMatrix34_t& initRotationMatrix( vr::HmdMatrix34_t& matrix, - unsigned axisId, + MatrixAxis axisId, float angle ) { switch ( axisId ) { - case 0: // x-axis + case MatrixAxis_X: matrix.m[0][0] = 1.0f; matrix.m[0][1] = 0.0f; matrix.m[0][2] = 0.0f; @@ -32,7 +39,7 @@ inline vr::HmdMatrix34_t& initRotationMatrix( vr::HmdMatrix34_t& matrix, matrix.m[2][2] = std::cos( angle ); matrix.m[2][3] = 0.0f; break; - case 1: // y-axis + case MatrixAxis_Y: matrix.m[0][0] = std::cos( angle ); matrix.m[0][1] = 0.0f; matrix.m[0][2] = std::sin( angle ); @@ -46,7 +53,7 @@ inline vr::HmdMatrix34_t& initRotationMatrix( vr::HmdMatrix34_t& matrix, matrix.m[2][2] = std::cos( angle ); matrix.m[2][3] = 0.0f; break; - case 2: // z-axis + case MatrixAxis_Z: matrix.m[0][0] = std::cos( angle ); matrix.m[0][1] = -std::sin( angle ); matrix.m[0][2] = 0.0f; @@ -67,8 +74,8 @@ inline vr::HmdMatrix34_t& initRotationMatrix( vr::HmdMatrix34_t& matrix, } inline vr::HmdMatrix34_t& matMul33( vr::HmdMatrix34_t& result, - const vr::HmdMatrix34_t& a, - const vr::HmdMatrix34_t& b ) + const vr::HmdMatrix34_t& lhs, + const vr::HmdMatrix34_t& rhs ) { for ( unsigned i = 0; i < 3; i++ ) { @@ -77,7 +84,7 @@ inline vr::HmdMatrix34_t& matMul33( vr::HmdMatrix34_t& result, result.m[i][j] = 0.0f; for ( unsigned k = 0; k < 3; k++ ) { - result.m[i][j] += a.m[i][k] * b.m[k][j]; + result.m[i][j] += lhs.m[i][k] * rhs.m[k][j]; } } } @@ -85,30 +92,30 @@ inline vr::HmdMatrix34_t& matMul33( vr::HmdMatrix34_t& result, } inline vr::HmdVector3_t& matMul33( vr::HmdVector3_t& result, - const vr::HmdMatrix34_t& a, - const vr::HmdVector3_t& b ) + const vr::HmdMatrix34_t& lhs, + const vr::HmdVector3_t& rhs ) { for ( unsigned i = 0; i < 3; i++ ) { result.v[i] = 0.0f; for ( unsigned k = 0; k < 3; k++ ) { - result.v[i] += a.m[i][k] * b.v[k]; + result.v[i] += lhs.m[i][k] * rhs.v[k]; }; } return result; } inline vr::HmdVector3_t& matMul33( vr::HmdVector3_t& result, - const vr::HmdVector3_t& a, - const vr::HmdMatrix34_t& b ) + const vr::HmdVector3_t& lhs, + const vr::HmdMatrix34_t& rhs ) { for ( unsigned i = 0; i < 3; i++ ) { result.v[i] = 0.0f; for ( unsigned k = 0; k < 3; k++ ) { - result.v[i] += a.v[k] * b.m[k][i]; + result.v[i] += lhs.v[k] * rhs.m[k][i]; }; } return result; diff --git a/src/utils/paths.cpp b/src/utils/paths.cpp index 4d762e59..a2662ff2 100644 --- a/src/utils/paths.cpp +++ b/src/utils/paths.cpp @@ -33,7 +33,7 @@ optional binaryDirectoryFindFile( const string fileName ) const auto filePath = QDir( QString::fromStdString( *path ) + '/' + QString::fromStdString( fileName ) ); - QFileInfo file( filePath.path() ); + QFileInfo const file( filePath.path() ); if ( !file.exists() ) { @@ -60,7 +60,7 @@ optional settingsDirectory() std::optional verifyIconFilePath( std::string filename ) { - const auto notifIconPath = paths::binaryDirectoryFindFile( filename ); + auto notifIconPath = paths::binaryDirectoryFindFile( filename ); if ( !notifIconPath.has_value() ) { qCritical() << "Could not find icon \"" << filename << "\""; diff --git a/src/utils/setup.cpp b/src/utils/setup.cpp index 5b6b7332..392441dd 100644 --- a/src/utils/setup.cpp +++ b/src/utils/setup.cpp @@ -1,14 +1,21 @@ #include "setup.h" +#include "openvr/openvr_init.h" +#include "overlaycontroller.h" #include #include +#include +#include #ifdef ENABLE_DEBUG_LOGGING constexpr auto debugLoggingEnabled = true; #else constexpr auto debugLoggingEnabled = false; #endif +namespace +{ QtMessageHandler originalMessageHandler = nullptr; -static FILE* f; +FILE* logFile; +} // namespace // The default Qt message handler prints to stdout on X11 and to the debugger on // Windows. That is borderline useless for us, therefore we create our own @@ -17,9 +24,10 @@ void mainQtMessageHandler( QtMsgType type, const QMessageLogContext& context, const QString& msg ) { - QString message = qFormatLogMessage( type, context, msg ); - fprintf( f, "%s\n", qPrintable( message ) ); - fflush( f ); + if (!debugLoggingEnabled && type == QtDebugMsg) return; + QString const message = qFormatLogMessage( type, context, msg ); + ( void ) fprintf( logFile, "%s\n", qPrintable( message ) ); + ( void ) fflush( logFile ); if ( originalMessageHandler ) ( *originalMessageHandler )( type, context, msg ); } @@ -35,27 +43,28 @@ CommandLineOptions returnCommandLineParser( const MyQApplication& application ) parser.addHelpOption(); parser.addVersionOption(); - QCommandLineOption desktopMode( k_desktopMode, k_desktopModeDescription ); + QCommandLineOption const desktopMode( k_desktopMode, + k_desktopModeDescription ); parser.addOption( desktopMode ); - QCommandLineOption forceNoSound( k_forceNoSound, - k_forceNoSoundDescription ); + QCommandLineOption const forceNoSound( k_forceNoSound, + k_forceNoSoundDescription ); parser.addOption( forceNoSound ); - QCommandLineOption forceNoManifest( k_forceNoManifest, - k_forceNoManifestDescription ); + QCommandLineOption const forceNoManifest( k_forceNoManifest, + k_forceNoManifestDescription ); parser.addOption( forceNoManifest ); - QCommandLineOption forceInstallManifest( + QCommandLineOption const forceInstallManifest( k_forceInstallManifest, k_forceInstallManifestDescription ); parser.addOption( forceInstallManifest ); - QCommandLineOption forceRemoveManifest( k_forceRemoveManifest, - k_forceRemoveManifestDescription ); + QCommandLineOption const forceRemoveManifest( + k_forceRemoveManifest, k_forceRemoveManifestDescription ); parser.addOption( forceRemoveManifest ); - QCommandLineOption resetSettings( k_resetSettings, - k_resetSettingsDescription ); + QCommandLineOption const resetSettings( k_resetSettings, + k_resetSettingsDescription ); parser.addOption( resetSettings ); parser.process( application ); @@ -171,12 +180,12 @@ void reinstallApplicationManifest( const std::string manifestPath ) qInfo() << "Manifest Previously Installed"; // String size was arbitrarily chosen by original author. constexpr auto kStringSize = 1024; - char oldApplicationWorkingDir[kStringSize] = { 0 }; + std::array oldApplicationWorkingDir = { 0 }; auto app_error = vr::VRApplicationError_None; vr::VRApplications()->GetApplicationPropertyString( application_strings::applicationKey, vr::VRApplicationProperty_WorkingDirectory_String, - oldApplicationWorkingDir, + oldApplicationWorkingDir.data(), kStringSize, &app_error ); @@ -192,7 +201,7 @@ void reinstallApplicationManifest( const std::string manifestPath ) const auto oldManifestPath = QDir::toNativeSeparators( - QDir::cleanPath( QDir( oldApplicationWorkingDir ) + QDir::cleanPath( QDir( oldApplicationWorkingDir.data() ) .absoluteFilePath( kVRManifestName ) ) ) .toStdString(); removeApplicationManifest( oldManifestPath ); @@ -208,12 +217,12 @@ void forceRemoveApplicationManifest() { // String size was arbitrarily chosen by original author. constexpr auto kStringSize = 1024; - char oldApplicationWorkingDir[kStringSize] = { 0 }; + std::array oldApplicationWorkingDir = { 0 }; auto app_error = vr::VRApplicationError_None; vr::VRApplications()->GetApplicationPropertyString( application_strings::applicationKey, vr::VRApplicationProperty_WorkingDirectory_String, - oldApplicationWorkingDir, + oldApplicationWorkingDir.data(), kStringSize, &app_error ); @@ -229,7 +238,7 @@ void forceRemoveApplicationManifest() const auto oldManifestPath = QDir::toNativeSeparators( - QDir::cleanPath( QDir( oldApplicationWorkingDir ) + QDir::cleanPath( QDir( oldApplicationWorkingDir.data() ) .absoluteFilePath( kVRManifestName ) ) ) .toStdString(); removeApplicationManifest( oldManifestPath ); @@ -283,13 +292,16 @@ void forceRemoveApplicationManifest() } vr::VR_Shutdown(); + // NOLINTNEXTLINE(concurrency-mt-unsafe) exit( exit_code ); } } // namespace manifest void setUpLogging() { - f = fopen( "AdvancedSettings.log", "a" ); - qSetMessagePattern("[%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{time process}: %{message}"); + logFile = fopen( "AdvancedSettings.log", "ae" ); + qSetMessagePattern( + "[%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-" + "critical}C%{endif}%{if-fatal}F%{endif}] %{time process}: %{message}" ); originalMessageHandler = qInstallMessageHandler( mainQtMessageHandler ); } diff --git a/src/utils/setup.h b/src/utils/setup.h index 2730a22b..12d63c0f 100644 --- a/src/utils/setup.h +++ b/src/utils/setup.h @@ -1,5 +1,4 @@ #pragma once -#include "../overlaycontroller.h" #include #include #include @@ -7,10 +6,8 @@ #include #include #include -#include #include #include -#include "../openvr/openvr_init.h" enum ReturnErrorCode { @@ -48,7 +45,7 @@ class MyQApplication : public QApplication // Should look into replacements for this function if Qt 6 ever rolls // around. There are multiple suggestions for other solutions in the // provided link. - virtual bool notify( QObject* receiver, QEvent* event ) override + bool notify( QObject* receiver, QEvent* event ) override { try {