Compare commits

...
Author SHA1 Message Date
Sapphire aa4eacccdc Allow selecting which body part to use for tap resets 2026-04-30 20:09:13 -05:00
Sapphire 34ebf5ca8b TapDetection: Clean up isUserStatic 2026-04-30 19:54:53 -05:00
Sapphire 25ba150e51 Bindings provider bug fixes + reformat (#1823) 2026-04-27 00:06:35 +02:00
Hannah 789ba55af5 Bugfix for launch args (#1821) 2026-04-21 21:16:58 +02:00
Hannah 986f8fcbb2 Fix server startup command (#1820) 2026-04-21 20:08:23 +02:00
Sapphire 3288069ae5 Deactivate feeder bridge when using new driver, add bindings provider (#1806) 2026-04-21 19:12:05 +02:00
Ilia Ki 15ff70dda2 Reduce allowed list of Gestures PIDs (#1818) 2026-04-20 19:19:14 +02:00
lucas lelievre f6833ecb85 fix videos (#1819) 2026-04-20 19:18:37 +02:00
Sapphire 638bce86e6 v20.0-rc.1 fixes (#1816) 2026-04-20 15:04:50 +02:00
gale be77ff73d7 Allow passing excess CLI arguments to Electron (#1817) 2026-04-18 19:22:01 +02:00
Sapphire d79d93cd0e Don't trigger submit when receiving settings from server (#1815) 2026-04-17 21:24:09 +02:00
lucas lelievre c022a557ed Electon - Config loading fixing (#1814) 2026-04-17 20:59:47 +02:00
loucass003 1799483f26 Revert "Electon - Config loading fixing"
This reverts commit 52491f2c2b.
2026-04-17 20:20:17 +02:00
loucass003 52491f2c2b Electon - Config loading fixing 2026-04-17 20:19:01 +02:00
Ilia Kiandsctanf 60077307d5 Introduce VID/PID allow lists (#1792)
Co-authored-by: sctanf <[email protected]>
2026-04-16 19:07:46 +02:00
Butterscotch! 65d4520c10 Rework VRChat OSC address/port handling (#1701) 2026-04-16 19:06:10 +02:00
Butterscotch! 0d3254bc27 Fix BVH hierarchy (#1772) 2026-04-16 18:25:56 +02:00
96cddb52bb Steam (#1763)
Co-authored-by: loucass003 <[email protected]>
Co-authored-by: HannahPadd <[email protected]>
2026-04-16 15:00:19 +02:00
lucas lelievre 110e0ce840 Fix lint / compile issues and Form typings (#1813) 2026-04-16 14:44:39 +02:00
lucas lelievre cc364978a0 Fix ip num (#1812) 2026-04-16 12:18:19 +02:00
Sapphire 0ed7bf5838 Add warning when SteamVR hand trackers are erroneously enabled (#1776) 2026-04-16 11:35:40 +02:00
dependabot[bot] fdbc52a1b6 Bump pnpm/action-setup from 4 to 6 (#1809)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 10:50:40 +02:00
dependabot[bot] 112faacafd Bump softprops/action-gh-release from 2 to 3 (#1810)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 10:47:41 +02:00
loucass003 ae33eea790 Make sure everything combiles after solaxr fix 2026-04-16 10:44:59 +02:00
loucass003 b5a4cf7bac Fix solarxr 2026-04-16 08:38:31 +00:00
Aed 54fbaa7b0b spelling police at it again (#1807) 2026-04-16 09:47:00 +02:00
Sapphire 3343894a80 Fix version sorting for DIY firmware tool (#1803) 2026-04-16 09:45:46 +02:00
dependabot[bot] 7e0a06a7b8 Bump gradle/actions from 5 to 6 (#1800)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 09:45:23 +02:00
Collin 706489d42c Fix floor clip bug (#1799) 2026-04-16 09:45:08 +02:00
Sapphire e9a36313cc Remove unnecessary parts of glTF header when sending VRM to server (#1796) 2026-04-16 09:31:40 +02:00
dependabot[bot] e05d19b435 Bump actions/upload-artifact from 6 to 7 (#1790)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 09:30:39 +02:00
Aed 6b6abebca5 spelling police at it again (#1791) 2026-04-16 09:28:55 +02:00
Kitlith 319f69cdcd Fix udev vid/pid capitalization. (#1788) 2026-04-16 09:04:05 +02:00
Sapphire c46c536a1a RegEditLinux: Find VRChat install location for registry parsing (#1785) 2026-04-16 09:00:32 +02:00
sctanf a98772d3aa HID open fix (#1782) 2026-04-16 08:59:30 +02:00
Spazzwan 6c7e6a4f42 Adjust finger bone length subdivision to more naturally simulate fingers (#1781) 2026-04-16 08:58:55 +02:00
Sapphireandloucass003 f4646f1133 Send SteamVRTrackersSetting when changing tracker toggles (#1778)
Co-authored-by: loucass003 <[email protected]>
2026-04-16 08:56:22 +02:00
ShineBrightMeow 306510c1d9 Add ICM-55686 to Const (#1774) 2026-04-16 08:52:52 +02:00
Sapphire 1560c0a1ec Don't always advance to next Stay Aligned setup step on reset (#1775) 2026-04-16 08:52:34 +02:00
Sapphire 04aa882222 Re-request skeleton config on proportions import (#1777) 2026-04-16 08:43:16 +02:00
dependabot[bot] e4b3b93e35 Bump actions/download-artifact from 6 to 8 (#1769)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 08:42:18 +02:00
peelz 96b544f5e0 fix: use transaction id in reset response (#1767) 2026-04-16 08:41:55 +02:00
sctanf eca4eb770c HIDCommon scheduled TIMED_OUT (#1761) 2026-04-16 08:40:49 +02:00
sctanf 036a893c28 HIDCommon use button as tap (#1760) 2026-04-16 08:40:12 +02:00
sctanf 428d16f19a Allow 0% battery level (#1755) 2026-04-16 08:37:45 +02:00
c8538b5521 Onboarding Quiz (#1751)
Co-authored-by: Sapphire <[email protected]>
Co-authored-by: loucass003 <[email protected]>
Co-authored-by: lucas lelievre <[email protected]>
Co-authored-by: Hannah <[email protected]>
2026-04-16 08:34:40 +02:00
146 changed files with 6781 additions and 4362 deletions

No files matched your search

+2
View File
@@ -30,6 +30,8 @@
/server/src/main/java/dev/slimevr/tracking/processor/ @Erimelowo
/server/src/main/java/dev/slimevr/filtering/ @Erimelowo
/bindings-provider/ @ImSapphire
# Linux files
*.nix @loucass003
/flake.lock @loucass003
+64 -20
View File
@@ -13,6 +13,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
matrix-cpp: ${{ steps.set-matrix.outputs.matrix-cpp }}
steps:
- id: set-matrix
shell: bash
@@ -25,7 +26,44 @@ jobs:
else
RESULT=$(echo "$BASE" | jq -c '.')
fi
RESULT_CPP=$(echo "$RESULT" | jq -c '[ .[] | select ( (.platform != "macos") and ( (.platform != "windows") or (.os | endswith("-arm") | not) ) ) ]')
echo "matrix={\"include\":$RESULT}" >> "$GITHUB_OUTPUT"
echo "matrix-cpp={\"include\":$RESULT_CPP}" >> "$GITHUB_OUTPUT"
build-bindings-provider:
name: Build bindings provider for ${{ matrix.os }}
needs: [setup-matrix]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix-cpp) }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- if: matrix.platform == 'linux'
name: Install GCC
uses: egor-tensin/setup-gcc@v2
with:
version: 16
- name: Get CMake
uses: lukka/get-cmake@latest
- name: Configure
run: cmake -S bindings-provider/ -B bindings-provider/build -DCMAKE_BUILD_TYPE=Release
- name: Build
run: cmake --build bindings-provider/build --config Release -j6
- name: Upload artifact
uses: actions/upload-artifact@v7
with:
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
path: |
bindings-provider/build/slimevr-bindings-provider
bindings-provider/build/libopenvr_api.so
bindings-provider/build/Release/SlimeVR-Bindings-Provider.exe
bindings-provider/build/openvr_api.dll
gui-checks:
name: Gui Checks
runs-on: ubuntu-latest
@@ -37,7 +75,7 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
@@ -60,7 +98,7 @@ jobs:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
uses: gradle/actions/setup-gradle@v6
- name: Java Spotless Check
run: ./gradlew spotlessCheck --build-cache
@@ -81,13 +119,13 @@ jobs:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
uses: gradle/actions/setup-gradle@v6
- name: Build ShadowJar
run: ./gradlew :server:desktop:shadowJar --build-cache
- name: Test with Gradle
run: ./gradlew :server:desktop:test
- name: Upload Server Jar
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: server-jar
path: |
@@ -105,7 +143,7 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
@@ -118,14 +156,14 @@ jobs:
- name: Tar GUI Dist
run: tar -czf slimevr-gui-dist.tar.gz -C gui/out .
- name: Upload GUI Dist
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: gui-dist
path: slimevr-gui-dist.tar.gz
package-desktop:
name: Package Desktop (${{ matrix.platform }} - ${{ matrix.os }})
needs: [setup-matrix, build-server-jar, build-gui-frontend]
needs: [setup-matrix, build-server-jar, build-gui-frontend, build-bindings-provider]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
@@ -138,19 +176,25 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Download Server Jar
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: server-jar
path: server
- if: contains(fromJson(needs.setup-matrix.outputs.matrix-cpp).include.*.os, matrix.os)
name: Download bindings provider artifact
uses: actions/download-artifact@v8
with:
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
path: bindings-provider/build/${{ matrix.platform == 'windows' && 'win' || 'linux' }}-${{ endsWith(matrix.os, '-arm') && 'arm64' || 'x64' }}
- name: Download GUI Dist
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Extract GUI for Electron
@@ -168,8 +212,8 @@ jobs:
[ -z "$VERSION" ] && VERSION="0.0.0"
VERSION="${VERSION#v}"
echo "Building version: $VERSION"
cd gui
pnpm i
cd gui
pnpm exec electron-builder --${{ matrix.platform }} \
${{ matrix.platform == 'macos' && '--universal' || '' }} \
--config.extraMetadata.version="$VERSION" \
@@ -200,7 +244,7 @@ jobs:
echo "Collected files:"
ls -lh "$DEST_DIR"
- name: Upload For Release
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: release-${{ matrix.platform }}-${{ matrix.os }}
path: release-out/*
@@ -222,9 +266,9 @@ jobs:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
uses: gradle/actions/setup-gradle@v6
- name: Download GUI Dist
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Extract GUI for Android
@@ -241,7 +285,7 @@ jobs:
- name: Prepare APK
run: cp server/android/build/outputs/apk/release/*.apk ./SlimeVR-android.apk
- name: Upload APK
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: release-android
path: SlimeVR-android.apk
@@ -256,7 +300,7 @@ jobs:
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_GPLAY_KEY_PASSWD }}
- name: Upload the Google Play artifact
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
if: startsWith(github.ref, 'refs/tags/')
with:
# Artifact name
@@ -271,22 +315,22 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Download All Release Artifacts
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
pattern: release-*
path: release-out
merge-multiple: true
- name: Download Server Jar
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: server-jar
path: server
- name: Download GUI Dist
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
draft: true
generate_release_notes: true
@@ -20,13 +20,13 @@ jobs:
run: |
npx @slimevr/update-manifest-generator@latest
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@v7
with:
name: "update-manifest.json"
path: ./update-manifest.json
- name: Upload update-manifest.json to release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ secrets.UPDATE_MANIFEST_RELEASE_TAG }}
files: ./update-manifest.json
+3
View File
@@ -1,3 +1,6 @@
[submodule "solarxr-protocol"]
path = solarxr-protocol
url = https://github.com/SlimeVR/SolarXR-Protocol.git
[submodule "svr-bindings-provider/openvr"]
path = bindings-provider/openvr
url = https://github.com/ValveSoftware/openvr.git
+297
View File
@@ -0,0 +1,297 @@
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: true
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: DontAlign
AlignTrailingComments:
Kind: Never
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AllowShortNamespacesOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
- __capability
BinPackArguments: true
BinPackLongBracedList: true
BinPackParameters: BinPack
BitFieldColonSpacing: Both
BracedInitializerIndentWidth: -1
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: All
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTemplateCloser: false
BreakBeforeTernaryOperators: true
BreakBinaryOperations: Never
BreakConstructorInitializers: BeforeComma
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: MultiLine
ColumnLimit: 0
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
EnumTrailingComma: Leave
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExportBlock: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: true
AtStartOfFile: true
KeepFormFeed: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MainIncludeChar: Quote
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
OneLineFormatOffRegex: ''
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakBeforeMemberAccess: 150
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth: -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: Always
RemoveBracesLLVM: false
RemoveEmptyLinesInUnwrappedLines: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes:
Enabled: true
IgnoreCase: false
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterOperatorKeyword: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterNot: false
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: true
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TableGenBreakInsideDAGArg: DontBreak
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
WrapNamespaceBodyWithEmptyLines: Leave
...
+12
View File
@@ -0,0 +1,12 @@
# Garbage left behind on Windows
.vs/
out/
CMakeFiles/
vcpkg_installed/
src/resources/resources.hpp
CMakeCache.txt
build.ninja
*.cmake
*.dll
*.log
+78
View File
@@ -0,0 +1,78 @@
cmake_minimum_required(VERSION 3.26)
project(SlimeVR-Bindings-Provider)
set(SOLARXR_PROTOCOL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol")
set(FLATBUFFERS_GENERATED_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol/protocol/cpp")
# These are used to determine the OpenVR library path
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(PROCESSOR_ARCH "64")
else()
set(PROCESSOR_ARCH "32")
endif()
if(WIN32)
set(OPENVR_LIBRARY_NAME "openvr_api")
set(OPENVR_LIBRARY_EXT "dll")
set(PLATFORM_NAME "win")
elseif(APPLE)
set(OPENVR_LIBRARY_NAME "libopenvr_api")
set(OPENVR_LIBRARY_EXT "dylib")
set(PLATFORM_NAME "osx")
elseif(LINUX)
set(OPENVR_LIBRARY_NAME "libopenvr_api")
set(OPENVR_LIBRARY_EXT "so")
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
set(PLATFORM_NAME "linuxarm")
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
set(PLATFORM_NAME "linux")
else()
message(FATAL_ERROR "Unknown/unsupported CPU architecture")
endif()
else()
message(FATAL_ERROR "Unknown/unsupported platform")
endif()
set(OPENVR_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/openvr")
message(STATUS "OpenVR library search path: ${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}")
find_library(OPENVR_LIBRARY NAMES openvr_api REQUIRED PATHS "${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}/" NO_DEFAULT_PATH)
message(STATUS "Found OpenVR library at: ${OPENVR_LIBRARY}")
add_executable("${PROJECT_NAME}"
"${CMAKE_CURRENT_SOURCE_DIR}/src/paths.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/solarxr.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/vr_utils.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp"
)
set_target_properties("${PROJECT_NAME}" PROPERTIES CXX_STANDARD 23)
target_include_directories("${PROJECT_NAME}" PRIVATE "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/include" "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/" "${FLATBUFFERS_GENERATED_ROOT}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include" "${OPENVR_ROOT}/headers")
target_link_libraries("${PROJECT_NAME}" PRIVATE "${OPENVR_LIBRARY}")
if(LINUX)
set_target_properties("${PROJECT_NAME}" PROPERTIES OUTPUT_NAME slimevr-bindings-provider)
endif()
set(OPENVR_RUNTIME_LIBRARY "${OPENVR_ROOT}/bin/${PLATFORM_NAME}${PROCESSOR_ARCH}/${OPENVR_LIBRARY_NAME}.${OPENVR_LIBRARY_EXT}")
message(STATUS "Found OpenVR runtime library: ${OPENVR_RUNTIME_LIBRARY}")
configure_file("${OPENVR_RUNTIME_LIBRARY}" "${CMAKE_CURRENT_BINARY_DIR}/." COPYONLY)
# Embed the resources into resources.hpp
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
src/resources/manifest.vrmanifest
src/resources/action_manifest.json
src/resources/generic.json
src/resources/knuckles.json
src/resources/oculus_touch.json
src/resources/vive_controller.json
)
file(STRINGS src/resources/manifest.vrmanifest SVR_VRAPP_MANIFEST NEWLINE_CONSUME)
file(STRINGS src/resources/action_manifest.json SVR_VRAPP_ACTION_MANIFEST NEWLINE_CONSUME)
file(STRINGS src/resources/generic.json SVR_VRAPP_GENERIC_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/knuckles.json SVR_VRAPP_KNUCKLES_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/oculus_touch.json SVR_VRAPP_OCULUS_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/vive_controller.json SVR_VRAPP_VIVE_BINDS NEWLINE_CONSUME)
configure_file(src/resources/resources.hpp.in src/resources/resources.hpp @ONLY)
target_include_directories("${PROJECT_NAME}" PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/src")
+21
View File
@@ -0,0 +1,21 @@
#include "logger.hpp"
#include "paths.hpp"
#ifdef _WIN32
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#endif
Logger::Logger()
: log_stream(Paths::getLogPath() / "slimevr-bindings-provider.log",
std::ios::out | std::ios::app)
#ifdef _WIN32
, should_log_to_std_streams(GetConsoleWindow() != nullptr)
#endif
{
}
Logger &Logger::get() {
static Logger logger;
return logger;
}
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include <cassert>
#include <chrono>
#include <format>
#include <fstream>
#include <iomanip>
#include <iostream>
class Logger {
private:
std::ofstream log_stream;
#ifdef _WIN32
bool should_log_to_std_streams;
#endif
template <bool important, typename... Args>
void log(std::string_view suffix, std::format_string<Args...> fmt,
Args &&...args) {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
auto s = std::format(fmt, std::forward<Args>(args)...);
#ifdef _WIN32
if (should_log_to_std_streams) {
#endif
if constexpr (important)
std::cerr << suffix << ' ' << s << '\n';
else
std::cout << suffix << ' ' << s << '\n';
#ifdef _WIN32
}
#endif
log_stream << std::put_time(std::localtime(&time_t), "[%F %T]") //
<< ' ' << suffix << ' ' << s << '\n';
}
public:
Logger();
template <typename... Args>
void debug(std::format_string<Args...> fmt, Args &&...args) {
#ifndef NDEBUG
log<false>("[DEBUG]", fmt, std::forward<Args>(args)...);
#endif
}
template <typename... Args>
void info(std::format_string<Args...> fmt, Args &&...args) {
log<false>("[INFO]", fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void warning(std::format_string<Args...> fmt, Args &&...args) {
log<true>("[WARN]", fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::format_string<Args...> fmt, Args &&...args) {
log<true>("[ERROR]", fmt, std::forward<Args>(args)...);
}
void flush() {
#ifdef _WIN32
if (should_log_to_std_streams) {
#endif
std::cerr.flush();
std::cout.flush();
#ifdef _WIN32
}
#endif
log_stream.flush();
}
static Logger &get();
};
+288
View File
@@ -0,0 +1,288 @@
#include <cassert>
#include <csignal>
#include <map>
#include <optional>
#include <thread>
#include <tuple>
// These must be included before Windows.h because of some macro collisions.
#include "flatbuffers/flatbuffers.h"
#include "solarxr_protocol/generated/all_generated.h"
#include "logger.hpp"
#include "solarxr.hpp"
#include "vr_utils.hpp"
#include "openvr.h"
using namespace std::chrono_literals;
using namespace solarxr_protocol;
static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); }
static void onYawReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Yaw, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onFullReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Full, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onFeetMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto bodyParts = fbb.CreateVector(
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, bodyParts, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onToggleTracking(SolarXRConnection &conn) {
static bool shouldPause = false;
flatbuffers::FlatBufferBuilder fbb;
shouldPause = !shouldPause;
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::SetPauseTrackingRequest,
toggleReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
sig_atomic_t should_exit = 0;
static void signal_handler(int signal) {
Logger::get().info("Received signal {}", signal);
should_exit = 1;
}
int main() {
auto &logger = Logger::get();
try {
SolarXRConnection conn;
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{ nullptr,
shutdown_vr };
// On vrlink, VR_Init returns
// VRInitError_Driver_WirelessHmdNotConnected while the connection
// is initialising, so keep calling VR_Init until it ends up
// succeeding
vr::EVRInitError err{ vr::VRInitError_Driver_WirelessHmdNotConnected };
while (err == vr::VRInitError_Driver_WirelessHmdNotConnected) {
sys.reset(vr::VR_Init(&err, vr::VRApplication_Background));
if (err == vr::VRInitError_Driver_WirelessHmdNotConnected)
std::this_thread::sleep_for(500ms);
}
if (sys == nullptr or err != vr::VRInitError_None) {
logger.error("Failed to init OpenVR: {} ({})",
vr::VR_GetVRInitErrorAsSymbol(err),
vr::VR_GetVRInitErrorAsEnglishDescription(err));
return 1;
}
logger.info("Initialised OpenVR, HMD model '{}'",
VRUtils::getStringProp(vr::k_unTrackedDeviceIndex_Hmd,
vr::Prop_ModelNumber_String)
.value_or("<unknown>"));
vr::IVRApplications *app = vr::VRApplications();
vr::IVRInput *input = vr::VRInput();
auto [appManifestPath, actionManifestPath] = VRUtils::initialiseManifest();
if (auto err = app->AddApplicationManifest(appManifestPath.string().data(), true);
err != vr::VRApplicationError_None) {
logger.error("Failed to add application manifest: {}",
app->GetApplicationsErrorNameFromEnum(err));
return 1;
}
// SetActionManifestPath may return IPCError if vrserver is busy and takes
// too long to reply, so keep invoking until it succeeds
{
vr::EVRInputError err{};
constexpr int max_tries = 5;
int tries = 0;
while ((err = input->SetActionManifestPath(
actionManifestPath.string().data()))
== vr::VRInputError_IPCError
&& tries++ < max_tries) {
logger.debug("IPC error loading action manifest, retrying ({}/{})",
tries, max_tries);
std::this_thread::sleep_for(20ms);
}
if (err != vr::VRInputError_None) {
logger.error("Failed to set action manifest path: {}",
std::to_underlying(err));
return 1;
}
}
vr::VRActionSetHandle_t action_set;
if (auto err = input->GetActionSetHandle("/actions/main", &action_set);
err != vr::VRInputError_None) {
logger.error("Failed to get main action set handle: {}",
std::to_underlying(err));
return 1;
}
std::map<std::string, std::tuple<vr::VRActionHandle_t, std::function<void(SolarXRConnection &)>>>
actions{
{ "/actions/main/in/YawReset",
std::make_tuple(vr::k_ulInvalidActionHandle, onYawReset) },
{ "/actions/main/in/FullReset",
std::make_tuple(vr::k_ulInvalidActionHandle, onFullReset) },
{ "/actions/main/in/MountingCalibration",
std::make_tuple(vr::k_ulInvalidActionHandle,
onMountingCalibration) },
{ "/actions/main/in/FeetMountingCalibration",
std::make_tuple(vr::k_ulInvalidActionHandle,
onFeetMountingCalibration) },
{ "/actions/main/in/ToggleTracking",
std::make_tuple(vr::k_ulInvalidActionHandle, onToggleTracking) },
};
for (auto &[name, tuple] : actions) {
auto &[handle, _] = tuple;
if (auto err = input->GetActionHandle(name.c_str(), &handle);
err != vr::VRInputError_None || handle == vr::k_ulInvalidActionHandle) {
logger.warning("Failed to get action handle for action {}: {}", name,
std::to_underlying(err));
}
}
constexpr auto interval = 1000ms / 30;
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
while (!should_exit) {
vr::VREvent_t event{};
while (sys->PollNextEvent(&event, sizeof(event))) {
switch (event.eventType) {
case vr::VREvent_Quit:
logger.info("OpenVR runtime requested quit");
should_exit = 1;
break;
case vr::VREvent_Input_BindingLoadFailed: {
auto &loadData = event.data.inputBinding;
logger.debug("Binding load failed (ulAppContainer={} "
"pathMessage={} pathUrl={} pathControllerType={})",
loadData.ulAppContainer, loadData.pathMessage,
loadData.pathUrl, loadData.pathControllerType);
break;
}
case vr::VREvent_Input_BindingLoadSuccessful: {
auto &loadData = event.data.inputBinding;
logger.debug("Binding load successful (ulAppContainer={} "
"pathMessage={} pathUrl={} pathControllerType={})",
loadData.ulAppContainer, loadData.pathMessage,
loadData.pathUrl, loadData.pathControllerType);
break;
}
case vr::VREvent_Input_ActionManifestReloaded:
logger.debug("Action manifest reloaded");
break;
case vr::VREvent_Input_ActionManifestLoadFailed: {
auto &manifestData = event.data.actionManifest;
logger.debug(
"Action manifest load failed (pathAppKey={} pathMessage={} "
"pathMessageParam={} pathManifestPath={})",
manifestData.pathAppKey, manifestData.pathMessage,
manifestData.pathMessageParam, manifestData.pathManifestPath);
break;
}
default:
break;
}
}
if (!conn.connected()) {
logger.warning("Connection to SlimeVR lost, exiting");
break;
}
vr::VRActiveActionSet_t set{
.ulActionSet = action_set,
.ulRestrictedToDevice = vr::k_ulInvalidInputValueHandle,
.ulSecondaryActionSet = vr::k_ulInvalidActionSetHandle,
.nPriority = 0,
};
if (auto err = input->UpdateActionState(&set, sizeof(set), 1);
err != vr::VRInputError_None) {
logger.warning("Error when updating action states: {}",
std::to_underlying(err));
}
for (auto &[name, tuple] : actions) {
auto &[handle, callback] = tuple;
vr::InputDigitalActionData_t action_data{};
if (auto err = input->GetDigitalActionData(
handle, &action_data, sizeof(action_data),
vr::k_ulInvalidInputValueHandle);
err != vr::VRInputError_None) {
logger.warning("Failed to get action state for {} ({}): {}", name,
handle, std::to_underlying(err));
continue;
}
if (action_data.bActive && action_data.bChanged && action_data.bState) {
logger.debug("Action {} triggered", name);
callback(conn);
}
}
logger.flush();
std::this_thread::sleep_for(interval);
}
logger.info("Main loop done");
} catch (std::exception &ex) {
logger.error("Exception in main: {}", ex.what());
logger.flush();
return 1;
}
logger.flush();
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
#include "paths.hpp"
namespace fs = std::filesystem;
fs::path Paths::getDataPath() {
fs::path basePath{};
#if defined(__linux__)
if (const char *dataHomeOverride = getenv("XDG_DATA_HOME")) {
basePath = dataHomeOverride;
} else {
const char *homeDir = getenv("HOME");
if (homeDir == nullptr)
throw std::runtime_error("HOME is unset");
basePath = fs::path(homeDir) / ".local" / "share";
}
#elif defined(_WIN32)
{
const char *appData = getenv("APPDATA");
if (appData == nullptr)
throw std::runtime_error("APPDATA is unset");
basePath = appData;
}
#else
#error "Unsupported platform"
#endif
return basePath / "dev.slimevr.SlimeVR";
}
fs::path Paths::getLogPath() { return Paths::getDataPath() / "logs"; }
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <filesystem>
namespace Paths {
// Throws when path cannot be found
std::filesystem::path getDataPath() noexcept(false);
// Throws when path cannot be found
std::filesystem::path getLogPath() noexcept(false);
} // namespace Paths
@@ -0,0 +1,64 @@
{
"default_bindings": [
{
"controller_type": "generic",
"binding_url": "generic.json"
},
{
"controller_type": "oculus_touch",
"binding_url": "oculus_touch.json"
},
{
"controller_type": "knuckles",
"binding_url": "knuckles.json"
},
{
"controller_type": "vive_controller",
"binding_url": "vive_controller.json"
}
],
"actions": [
{
"name": "/actions/main/in/YawReset",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/FullReset",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/MountingCalibration",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/FeetMountingCalibration",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/ToggleTracking",
"requirement": "optional",
"type": "boolean"
}
],
"action_sets": [
{
"name": "/actions/main",
"usage": "leftright"
}
],
"localization": [
{
"language_tag": "en_us",
"/actions/main": "Utility Bindings",
"/actions/main/in/YawReset": "Yaw Reset",
"/actions/main/in/FullReset": "Full Reset",
"/actions/main/in/MountingCalibration": "Mounting Calibration",
"/actions/main/in/FeetMountingCalibration": "Feet Mounting Calibration",
"/actions/main/in/ToggleTracking": "Toggle Tracking"
}
]
}
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Generic",
"controller_type": "generic",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Knuckles",
"controller_type": "knuckles",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -0,0 +1,14 @@
{
"source": "builtin",
"applications": [{
"app_key": "dev.slimevr.BindingsProvider",
"is_dashboard_overlay": false,
"action_manifest_path": "action_manifest.json",
"strings": {
"en_us": {
"name": "SlimeVR Bindings Provider",
"description": "SlimeVR Bindings Provider"
}
}
}]
}
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Oculus Touch",
"controller_type": "oculus_touch",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -0,0 +1,8 @@
#pragma once
#cmakedefine SVR_VRAPP_MANIFEST R"(@SVR_VRAPP_MANIFEST@)"
#cmakedefine SVR_VRAPP_ACTION_MANIFEST R"(@SVR_VRAPP_ACTION_MANIFEST@)"
#cmakedefine SVR_VRAPP_GENERIC_BINDS R"(@SVR_VRAPP_GENERIC_BINDS@)"
#cmakedefine SVR_VRAPP_KNUCKLES_BINDS R"(@SVR_VRAPP_KNUCKLES_BINDS@)"
#cmakedefine SVR_VRAPP_OCULUS_BINDS R"(@SVR_VRAPP_OCULUS_BINDS@)"
#cmakedefine SVR_VRAPP_VIVE_BINDS R"(@SVR_VRAPP_VIVE_BINDS@)"
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Vive Wands",
"controller_type": "vive_controller",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
+163
View File
@@ -0,0 +1,163 @@
#include "solarxr.hpp"
#include "logger.hpp"
#include <stdexcept>
#if defined(__linux__)
#include <sys/socket.h>
#include <sys/un.h>
#elif defined(_WIN32)
#include <Windows.h>
#else
#error "Unsupported platform"
#endif
namespace fs = std::filesystem;
fs::path SolarXRConnection::getSocketPath() {
using namespace std::string_view_literals;
#if defined(__linux__)
#define MAKE_SOCKET_PATH(PATH) \
std::make_pair(PATH##sv, static_cast<const char *>(getenv(PATH)))
constexpr std::string_view socketName = "SlimeVRRpc";
std::array<std::pair<std::string_view, const char *>, 4> socketPaths{
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
MAKE_SOCKET_PATH("TMPDIR"),
{ "/tmp", "/tmp" }
};
#undef MAKE_SOCKET_PATH
for (auto [name, path] : socketPaths) {
if (path == nullptr) {
Logger::get().info(
"Skipping socket directory {} because it doesn't exist", name);
continue;
}
fs::path socketPath = fs::path(path) / socketName;
if (fs::exists(socketPath))
return socketPath;
Logger::get().info(
"Skipping socket directory {} because socket does not exist", name);
}
#elif defined(_WIN32)
throw std::logic_error(
"SolarXRConnection::getSocketPath should not be called on Windows");
#else
#error "Unsupported platform"
#endif
throw std::runtime_error("Failed to find socket directory");
}
SolarXRConnection::SolarXRConnection() {
#if defined(__linux__)
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, getSocketPath().string().data());
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
throw std::runtime_error(
std::format("Failed to create listen socket: {}", strerror(errno)));
}
if (connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
int e = errno;
close(fd);
throw std::runtime_error(std::format("Failed to connect to socket {}: {}",
addr.sun_path, strerror(e)));
}
#elif defined(_WIN32)
const char *pipeName = R"(\\.\pipe\SlimeVRRpc)";
if (!WaitNamedPipe(pipeName, 5000)) {
throw std::runtime_error("Timed out waiting for pipe");
}
pipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_EXISTING, 0, nullptr);
if (pipe == INVALID_HANDLE_VALUE) {
throw std::runtime_error(
std::format("Unable to open pipe (error={})", GetLastError()));
}
#else
#error "Unsupported platform"
#endif
}
SolarXRConnection::~SolarXRConnection() {
#if defined(__linux__)
if (fd != -1)
close(fd);
#elif defined(_WIN32)
if (pipe != INVALID_HANDLE_VALUE)
CloseHandle(pipe);
#else
#error "Unsupported platform"
#endif
}
bool SolarXRConnection::connected() {
#if defined(__linux__)
if (read(fd, nullptr, 0) == -1) {
return !(errno == EBADF || errno == EINVAL);
}
return true;
#elif defined(_WIN32)
if (!WriteFile(pipe, nullptr, 0, nullptr, nullptr)) {
int err = GetLastError();
// The documentation says it should return ERROR_BROKEN_PIPE
// when the write-end has been closed, but it seems to actually
// return ERROR_NO_DATA...
return !(err == ERROR_NO_DATA || err == ERROR_BROKEN_PIPE);
}
return true;
#else
#error "Unsupported platform"
#endif
}
void SolarXRConnection::sendMsg(flatbuffers::FlatBufferBuilder &fbb) {
// The server expects the total size of the buffer to be written at the
// start of the packet, including the first 4 bytes for the size
int size = fbb.GetSize() + 4;
// This may be wrong on mixed-endianness, but oh well...
if constexpr (std::endian::native != std::endian::little)
size = std::byteswap(size);
#if defined(__linux__)
if (write(fd, &size, sizeof(size)) == -1) {
Logger::get().warning("Failed to write message size to socket: {}",
strerror(errno));
return;
}
if (write(fd, fbb.GetBufferPointer(), fbb.GetSize()) == -1) {
Logger::get().warning("Failed to write message to socket: {}",
strerror(errno));
return;
}
#elif defined(_WIN32)
uint8_t tempBuf[2048];
if (fbb.GetSize() > 2048 - 4) {
Logger::get().warning("Message is too big for temporary buffer");
return;
}
*reinterpret_cast<int *>(&tempBuf[0]) = size;
memcpy(&tempBuf[4], fbb.GetBufferPointer(), fbb.GetSize());
if (!WriteFile(pipe, tempBuf, fbb.GetSize() + 4, nullptr, nullptr)) {
Logger::get().warning("Failed to write message to pipe (error={})",
GetLastError());
return;
}
#else
#error "Unsupported platform"
#endif
}
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <filesystem>
#if defined(_WIN32)
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#endif
#include "flatbuffers/flatbuffer_builder.h"
class SolarXRConnection {
private:
#if defined(__linux__)
int fd{ -1 };
#elif defined(_WIN32)
HANDLE pipe{ INVALID_HANDLE_VALUE };
#else
#error "Unsupported platform"
#endif
static std::filesystem::path getSocketPath();
public:
SolarXRConnection() noexcept(false);
~SolarXRConnection();
bool connected();
void sendMsg(flatbuffers::FlatBufferBuilder &fbb);
};
+72
View File
@@ -0,0 +1,72 @@
#include "vr_utils.hpp"
#include "logger.hpp"
#include "paths.hpp"
#include "resources/resources.hpp"
#include <array>
#include <fstream>
#include <string_view>
#include <utility>
namespace fs = std::filesystem;
std::optional<std::string>
VRUtils::getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
vr::ETrackedDeviceProperty prop) {
vr::IVRSystem *sys = vr::VRSystem();
vr::ETrackedPropertyError err{ vr::TrackedProp_Success };
uint32_t required_len = sys->GetStringTrackedDeviceProperty(deviceIndex, prop, nullptr, 0, &err);
if (err != vr::TrackedProp_BufferTooSmall) {
Logger::get().info(
"Failed to get size of string property {} for device {}: {}",
std::to_underlying(prop), deviceIndex,
sys->GetPropErrorNameFromEnum(err));
return std::nullopt;
}
std::string s(required_len - 1, '\0');
sys->GetStringTrackedDeviceProperty(deviceIndex, prop, s.data(), required_len,
&err);
if (err != vr::TrackedProp_Success) {
Logger::get().info("Failed to get string property {} for device {}: {}",
std::to_underlying(prop), deviceIndex,
sys->GetPropErrorNameFromEnum(err));
return std::nullopt;
}
return s;
}
std::tuple<fs::path, fs::path> VRUtils::initialiseManifest() {
fs::path manifestDir = Paths::getDataPath() / "bindings-provider";
std::error_code ec;
fs::create_directories(manifestDir, ec);
if (ec) {
throw std::runtime_error(
std::format("Failed to create manifest folder: {}", ec.message()));
}
using namespace std::string_view_literals;
// Make sure the vrmanifest and action manifest are 1st and 2nd respectively
// in the array
std::array requiredFiles{
std::make_pair("manifest.vrmanifest"sv, SVR_VRAPP_MANIFEST),
std::make_pair("action_manifest.json"sv, SVR_VRAPP_ACTION_MANIFEST),
std::make_pair("generic.json"sv, SVR_VRAPP_GENERIC_BINDS),
std::make_pair("knuckles.json"sv, SVR_VRAPP_KNUCKLES_BINDS),
std::make_pair("oculus_touch.json"sv, SVR_VRAPP_OCULUS_BINDS),
std::make_pair("vive_controller.json"sv, SVR_VRAPP_VIVE_BINDS),
};
for (auto &[name, contents] : requiredFiles) {
fs::path path = manifestDir / name;
if (!fs::exists(path)) {
std::ofstream stream(path);
stream << contents;
}
}
return { manifestDir / requiredFiles.at(0).first,
manifestDir / requiredFiles.at(1).first };
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <filesystem>
#include <optional>
#include <string>
#include <tuple>
#include "openvr.h"
namespace VRUtils {
std::optional<std::string> getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
vr::ETrackedDeviceProperty prop);
// Returns <app vrmanifest path, action manifest json path>
std::tuple<std::filesystem::path, std::filesystem::path> initialiseManifest();
} // namespace VRUtils
+1 -1
View File
@@ -15,7 +15,7 @@
runtimeLibs = pkgs: (with pkgs; [
jdk17
alsa-lib at-spi2-atk at-spi2-core cairo cups dbus expat
alsa-lib libpulseaudio at-spi2-atk at-spi2-core cairo cups dbus expat
gdk-pixbuf glib gtk3 libdrm libgbm libglvnd libnotify
libxkbcommon mesa nspr nss pango systemd vulkan-loader
wayland xorg.libX11 xorg.libXcomposite xorg.libXdamage
+8
View File
@@ -35,6 +35,10 @@ linux:
extraFiles:
- from: "../server/desktop/build/libs/slimevr.jar"
to: "."
- from: "../bindings-provider/build/linux-${arch}/slimevr-bindings-provider"
to: "."
- from: "../bindings-provider/build/linux-${arch}/libopenvr_api.so"
to: "."
- from: "./electron/resources/69-slimevr-devices.rules"
to: "."
icon: "./electron/resources/icons"
@@ -59,6 +63,10 @@ win:
- from: "../server/core/resources"
to: "."
filter: ["**/*"]
- from: "../bindings-provider/build/${os}-${arch}/Release/SlimeVR-Bindings-Provider.exe"
to: "."
- from: "../bindings-provider/build/${os}-${arch}/openvr_api.dll"
to: "."
mac:
target: dmg
+13 -3
View File
@@ -1,12 +1,22 @@
import { program } from "commander";
import { Option, program } from "commander";
program
.option('-p --path <path>', 'set launch path')
.option('-p, --path <path>', 'set launch path')
.option('-s, --steam', 'steam mode')
.option('-i, --install', 'run the driver installer')
.option(
'--skip-server-if-running',
'gui will not launch the server if it is already running'
)
.allowUnknownOption();
.allowUnknownOption()
// Allow passing arguments to Electron.
.allowExcessArguments();
if (process.platform === "linux") {
const noUdevOption = new Option('--no-udev', 'disable udev warning');
noUdevOption.negate = false;
program.addOption(noUdevOption)
}
program.parse(process.argv);
export const options = program.opts();
+56 -18
View File
@@ -16,26 +16,30 @@ import open from 'open';
import trayIcon from '../resources/icons/icon.png?asset';
import appleTrayIcon from '../resources/icons/Square30x30Logo.png?asset';
import { readFile, stat } from 'fs/promises';
import { pathToFileURL } from 'node:url';
import { getPlatform, handleIpc, isPortAvailable } from './utils';
import {
findServerJar,
findSystemJRE,
getExeFolder,
getGuiDataFolder,
getLogsFolder,
getServerDataFolder,
getWindowStateFile,
} from './paths';
import { stores } from './store';
import { initStores } from './store';
import { closeLogger, logger } from './logger';
import { writeFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { discordPresence } from './presence';
import { options } from './cli';
import { ServerStatusEvent } from 'electron/preload/interface';
import { mkdir } from 'node:fs/promises';
import { mkdir, writeFile } from 'node:fs/promises';
import { MenuItem } from 'electron/main';
type Stores = Awaited<ReturnType<typeof initStores>>;
let stores: Stores;
// Fixes colors looking washed on linux
// Might affect hdr
if (process.platform === 'linux') {
@@ -54,6 +58,7 @@ protocol.registerSchemesAsPrivileged([
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
},
},
]);
@@ -182,13 +187,11 @@ handleIpc(IPC_CHANNELS.GET_FOLDER, (e, folder) => {
return getGuiDataFolder();
case 'logs':
return getLogsFolder();
case 'exe':
return getExeFolder();
}
});
const windowStateFile = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
}).catch(() => null);
const defaultWindowState: {
width: number;
height: number;
@@ -200,7 +203,15 @@ const defaultWindowState: {
x: undefined,
y: undefined,
};
const windowState = windowStateFile ? JSON.parse(windowStateFile) : defaultWindowState;
const windowState = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
})
.then(data => JSON.parse(data))
.catch(() => {
logger.error('Failed to load window state, using defaults');
return defaultWindowState;
});
const MIN_WIDTH = 393;
const MIN_HEIGHT = 667;
@@ -233,7 +244,7 @@ function validateWindowState(state: typeof defaultWindowState) {
const saveWindowState = async () => {
await mkdir(dirname(getWindowStateFile()), { recursive: true });
writeFileSync(getWindowStateFile(), JSON.stringify(windowState));
await writeFile(getWindowStateFile(), JSON.stringify(windowState), { encoding: 'utf-8' });
};
function createWindow() {
@@ -393,9 +404,16 @@ const spawnServer = async () => {
logger.info({ javaBin, serverJar }, 'Found Java and server jar');
const platform = getPlatform();
const serverWorkdir = getServerDataFolder()
const serverProcess = spawn(javaBin, ['-Xmx128M', '-jar', serverJar, 'run'], {
cwd: serverWorkdir,
const serverArgs = ['-Xmx128M', '-jar', serverJar];
if (options.steam) serverArgs.push('--steam');
if (options.install) serverArgs.push('--install');
if (options.noUdev) serverArgs.push('--no-udev');
serverArgs.push('run');
const serverProcess = spawn(javaBin, serverArgs, {
cwd: sharedDir,
shell: false,
env:
platform === 'windows'
@@ -439,16 +457,36 @@ const spawnServer = async () => {
};
};
const createFolders = async () => {
await mkdir(getServerDataFolder(), { recursive: true });
await mkdir(getGuiDataFolder(), { recursive: true });
}
let isQuitting = false;
app.whenReady().then(async () => {
// Register protocol handler for app:// scheme to handle assets with leading slashes
protocol.handle('app', (request) => {
const url = request.url.slice('app://'.length);
const filePath = path.normalize(join(__dirname, '../renderer', url));
return net.fetch('file://' + filePath);
const { pathname } = new URL(request.url);
const filePath = path.normalize(join(__dirname, '../renderer', pathname));
return net.fetch(pathToFileURL(filePath).toString(), { headers: request.headers });
});
try {
await createFolders();
} catch (err) {
logger.error(err, 'Failed to initialize stores');
dialog.showErrorBox(
'SlimeVR',
'Failed to initialize application storage. Please make sure the application has write permissions to its data folder.'
);
app.quit();
return;
}
stores = await initStores();
checkEnvironmentVariables();
const server = await spawnServer();
@@ -467,8 +505,8 @@ app.whenReady().then(async () => {
logger.info('App quitting, saving...');
server?.close();
await server?.waitForExit();
stores.settings.save();
stores.cache.save();
await stores.settings.save();
await stores.cache.save();
discordPresence.destroy();
await saveWindowState();
await closeLogger();
+14 -2
View File
@@ -48,12 +48,21 @@ export const getLogsFolder = () => {
return join(getGuiDataFolder(), 'logs');
};
export const getExeFolder = () => {
return path.dirname(app.getPath('exe'));
};
export const getWindowStateFile = () =>
join(getServerDataFolder(), '.window-state.json');
const localJavaBin = (sharedDir: string) => {
const jre = join(sharedDir, 'jre/bin', javaBin);
return jre;
const platform = getPlatform();
switch (platform) {
case 'macos':
return join(sharedDir, '../../../../jre/Contents/Home/bin', javaBin);
default:
return join(sharedDir, 'jre/bin', javaBin);
}
};
const javaHomeBin = () => {
@@ -112,6 +121,9 @@ export const findServerJar = () => {
// For flatpack container
path.resolve('/app/share/slimevr/'),
path.resolve('/usr/share/slimevr/'),
// For macos on steam
path.resolve(`${app.getPath('exe')}/../../../../`),
];
return paths
.filter((p) => !!p)
+23 -20
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { access, mkdir, readFile, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { logger } from "./logger";
import { getGuiDataFolder } from "./paths";
@@ -10,25 +10,28 @@ export class CustomStore {
private filePath: string;
private debounceMs: number;
constructor(filePath: string, debounceMs: number = 2000) {
private constructor(filePath: string, debounceMs: number = 2000) {
this.filePath = filePath;
this.debounceMs = debounceMs;
this.load();
}
private load() {
static async create(filePath: string, debounceMs: number = 2000): Promise<CustomStore> {
const store = new CustomStore(filePath, debounceMs);
await store.load();
return store;
}
private async load(): Promise<void> {
try {
if (existsSync(this.filePath)) {
const raw = readFileSync(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
}
} catch (err) {
logger.error(err, `Failed to load store at ${this.filePath}`);
await access(this.filePath);
const raw = await readFile(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
} catch {
this.data = {};
logger.warn(`No existing store found at ${this.filePath}, starting with empty store.`);
}
}
/** Set a key and trigger the debounced auto-save */
set(key: string, value: unknown) {
this.data[key] = value;
this.triggerAutoSave();
@@ -54,14 +57,12 @@ export class CustomStore {
}, this.debounceMs);
}
save(): boolean {
async save(): Promise<boolean> {
try {
if (this.saveTimeout) clearTimeout(this.saveTimeout);
const dir = dirname(this.filePath);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
await mkdir(dirname(this.filePath), { recursive: true });
await writeFile(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
return true;
} catch (err) {
logger.error(err, 'Save failed', this.filePath);
@@ -70,7 +71,9 @@ export class CustomStore {
}
}
export const stores = {
settings: new CustomStore(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: new CustomStore(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
export async function initStores() {
return {
settings: await CustomStore.create(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: await CustomStore.create(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
}
+2 -1
View File
@@ -36,5 +36,6 @@ contextBridge.exposeInMainWorld('electronAPI', {
openLogsFolder: async () => ipcRenderer.invoke(IPC_CHANNELS.OPEN_FILE, await ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'logs')),
openFile: (path) => ipcRenderer.invoke(IPC_CHANNELS.OPEN_FILE, path),
ghGet: (req) => ipcRenderer.invoke(IPC_CHANNELS.GH_FETCH, req),
setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options)
setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options),
getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe')
} satisfies IElectronAPI);
+1
View File
@@ -56,6 +56,7 @@ export interface IElectronAPI {
openFile: (path: string) => void;
ghGet: <T extends GHGet>(options: T) => Promise<GHReturn[T['type']]>;
setPresence: (options: DiscordPresence) => void;
getInstallDir: () => Promise<string>;
}
declare global {
@@ -14,24 +14,24 @@
## QinHeng
# CH340
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="7522", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="7523", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7522", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", MODE="0660", TAG+="uaccess"
# CH341
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="5523", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="5523", MODE="0660", TAG+="uaccess"
# CH343
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="55D3", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="55d3", MODE="0660", TAG+="uaccess"
# CH9102x
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="55D4", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="55d4", MODE="0660", TAG+="uaccess"
## Silabs
# CP210x
SUBSYSTEMS=="usb", ATTRS{idVendor}=="10C4", ATTRS{idProduct}=="EA60", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", MODE="0660", TAG+="uaccess"
## Espressif
# ESP32-S3 / ESP32-C3 / ESP32-C5 / ESP32-C6 / ESP32-C61 / ESP32-H2 / ESP32-P4
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303A", ATTRS{idProduct}=="1001", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="1001", MODE="0660", TAG+="uaccess"
# ESP32-S2
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303A", ATTRS{idProduct}=="0002", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="0002", MODE="0660", TAG+="uaccess"
## FTDI
# FT232BM/L/Q, FT245BM/L/Q
+1 -1
View File
@@ -41,7 +41,7 @@ export interface IpcInvokeMap {
value?: unknown;
}) => Promise<unknown>;
[IPC_CHANNELS.OPEN_FILE]: (path: string) => void;
[IPC_CHANNELS.GET_FOLDER]: (folder: 'config' | 'logs') => string;
[IPC_CHANNELS.GET_FOLDER]: (folder: 'config' | 'logs' | 'exe') => string;
[IPC_CHANNELS.GH_FETCH]: <T extends GHGet>(
options: T
) => Promise<GHReturn[T['type']]>;
+3 -1
View File
@@ -68,8 +68,10 @@
"dmg-license": "^1.0.11",
"dotenv": "^16.4.5",
"electron": "^40.3.0",
"electron-builder": "^26.7.0",
"electron-builder": "^26.9.0",
"electron-vite": "^5.0.0",
"@eslint/eslintrc": "^3.3.5",
"@eslint/js": "^9.39.4",
"eslint": "^9.39.1",
"eslint-import-resolver-typescript": "^3.10.1",
"eslint-plugin-import": "^2.32.0",
+66 -5
View File
@@ -524,8 +524,10 @@ settings-general-steamvr-trackers-right_hand = Right hand
settings-general-steamvr-trackers-tracker_toggling = Automatic tracker assignment
settings-general-steamvr-trackers-tracker_toggling-description = Automatically handles toggling SteamVR trackers on or off depending on your current tracker assignments.
settings-general-steamvr-trackers-tracker_toggling-label = Automatic tracker assignment
settings-general-steamvr-trackers-hands-warning = <b>Warning:</b> hand trackers will override your controllers.
Are you sure?
settings-general-steamvr-trackers-hands-warning = <b>Warning:</b> Enabling the SteamVR hand trackers will disable inputs from real controllers.
This should only be enabled if you are using SlimeVR for hand tracking.
Are you sure you want to do this?
settings-general-steamvr-trackers-hands-warning-cancel = Cancel
settings-general-steamvr-trackers-hands-warning-done = Yes
@@ -669,7 +671,7 @@ settings-general-fk_settings-self_localization-description = Mocap Mode allows t
## Gesture control settings (tracker tapping)
settings-general-gesture_control = Gesture control
settings-general-gesture_control-subtitle = Tap based resets
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker. The tracker highest up on your torso is used for Yaw Reset, the tracker highest up on your left leg is used for Full Reset, and the tracker highest up on your right leg is used for Mounting Calibration. Taps must occur within the time limit of 0.3 seconds times the number of taps to be recognized.
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker. If the preferred body part is unset, or the preferred body part is not assigned to a connected tracker, the tracker highest up on your torso is used for Yaw Reset, the tracker highest up on your left leg is used for Full Reset, and the tracker highest up on your right leg is used for Mounting Calibration. Taps must occur within the time limit of 0.3 seconds times the number of taps to be recognized.
# This is a unit: 3 taps, 2 taps, 1 tap
# $amount (Number) - Amount of taps (touches to the tracker's case)
settings-general-gesture_control-taps = { $amount ->
@@ -682,13 +684,20 @@ settings-general-gesture_control-trackers = { $amount ->
[one] 1 tracker
*[other] { $amount } trackers
}
settings-general-gesture_control-part_select = Which tracker do you want to tap to trigger the reset?
settings-general-gesture_control-part_select-edit = Edit
settings-general-gesture_control-part_select-reset = Reset preference
settings-general-gesture_control-part_select-no_preference = No preference
settings-general-gesture_control-yawResetEnabled = Enable tap to yaw reset
settings-general-gesture_control-yawResetPart = Preferred tracker for yaw reset taps
settings-general-gesture_control-yawResetDelay = Yaw reset delay
settings-general-gesture_control-yawResetTaps = Taps for yaw reset
settings-general-gesture_control-fullResetEnabled = Enable tap to full reset
settings-general-gesture_control-fullResetPart = Preferred tracker for full reset taps
settings-general-gesture_control-fullResetDelay = Full reset delay
settings-general-gesture_control-fullResetTaps = Taps for full reset
settings-general-gesture_control-mountingResetEnabled = Enable tap to perform mounting calibration
settings-general-gesture_control-mountingResetPart = Preferred tracker for mounting calibration taps
settings-general-gesture_control-mountingResetDelay = Mounting calibration delay
settings-general-gesture_control-mountingResetTaps = Taps for mounting calibration
# The number of trackers that can have higher acceleration before a tap is rejected
@@ -934,8 +943,50 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Skip setup
onboarding-setup_warning-cancel = Continue setup
## Quiz
onboarding-quiz_continue = Continue
onboarding-quiz_back = Back
onboarding-quiz-more_sets_modal-title = Have you connected all of your trackers?
onboarding-quiz-more_sets_modal-desc = If you have sets of different models, we can connect them right now!
onboarding-quiz-more_sets_modal-confirm = I have connected all my trackers
onboarding-quiz-more_sets_modal-cancel = I want to connect more trackers
onboarding-quiz-slimeset-title = What type of trackers are you connecting?
onboarding-quiz-slimeset-description = If you have multiple sets, you will be asked again later in the process
onboarding-quiz-slimeset-official-sets = Official SlimeVR Trackers
onboarding-quiz-slimeset-thirdparty-sets = Third-party or DIY Trackers
onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 & V1.2
onboarding-quiz-slimeset-answer-butterfly = Butterfly
onboarding-quiz-slimeset-answer-wifi = WiFi-based Slime
onboarding-quiz-slimeset-answer-dongle = Dongle-based Slime
onboarding-quiz-usage-title = What are you using your trackers for?
onboarding-quiz-usage-description = If you plan on using SlimeVR for multiple purposes, you can change the affected settings later.
onboarding-quiz-usage-answer-VRC = VR Gaming (e.g. VRChat)
onboarding-quiz-usage-answer-mocap_vtubing = Mocap and VTubing
onboarding-quiz-runtime-title = Do you run games via SteamVR, or on the headset itself (standalone)?
onboarding-quiz-runtime-answer-steamvr = SteamVR
onboarding-quiz-runtime-answer-standalone = Standalone
onboarding-quiz-mocap_preferences-title = Mocap Preferences
onboarding-quiz-mocap_preferences-desc = Specify how you plan to use SlimeVR for mocap or VTubing
onboarding-quiz-mocap_preferences-playspace-title = What is your playspace?
onboarding-quiz-mocap_preferences-playspace-desc = If standing, SlimeVR will try to track walking movement instead of anchoring you in one spot.
onboarding-quiz-mocap_preferences-playspace-sitting = Sitting
onboarding-quiz-mocap_preferences-playspace-standing = Standing
onboarding-quiz-mocap_preferences-vrm_model-title = Do you have a VRM model? (Optional)
onboarding-quiz-mocap_preferences-vrm_model-desc = Loading a VRM model will improve tracking quality and compatibility with applications that use VMC.
onboarding-quiz-mocap_preferences-head_tracker-title = Are you wearing a tracker or VR headset on your head?
onboarding-quiz-mocap_preferences-head_tracker-yes = Yes
onboarding-quiz-mocap_preferences-head_tracker-no = No
onboarding-quiz-mocap_preferences-head_tracker_location-title = Where is your head tracker located?
onboarding-quiz-mocap_preferences-head_tracker_location-forehead = Forehead
onboarding-quiz-mocap_preferences-head_tracker_location-face = Face
## Wi-Fi setup
onboarding-wifi_creds-back = Go back to introduction
onboarding-wifi_creds-back-v2 = Go back
onboarding-wifi_creds-v2 = Trackers using Wi-Fi
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -980,6 +1031,11 @@ onboarding-reset_tutorial-2 = Tap the highlighted tracker { $taps } times to tri
You need to be in a pose like you are skiing as shown in the Automatic Mounting wizard, and you have a 3 second delay (configurable) before it gets triggered.
## Install info
install-info_udev-rules_modal_title = Hardware udev access rules not found
install-info_udev-rules_warning = Access rules via udev are required for serial console access & dongle connection. Paste the following command into your terminal to add the udev rules.
install-info_udev-rules_modal_button = Close
install-info_udev-rules_modal-dont-show-again_checkbox = Don't show again
## Setup start
onboarding-home = Welcome to SlimeVR
onboarding-home-start = Let's get set up!
@@ -1306,6 +1362,7 @@ onboarding-user_height-description = We need your height to calculate your body
onboarding-user_height-need_head_tracker = A headset and controllers with positional tracking are required to perform the calibration.
onboarding-user_height-calculate = Calculate my height automatically
onboarding-user_height-next_step = Continue and save
onboarding-user_height-prev_step = Back
onboarding-user_height-manual-proportions = Manual Proportions
onboarding-user_height-calibration-title = Calibration Progress
onboarding-user_height-calibration-RECORDING_FLOOR = Touch the floor with the tip of your controller
@@ -1468,6 +1525,7 @@ firmware_tool-flashing_step-description =
firmware_tool-flashing_step-warning-v2 = Do not unplug or turn off the tracker during the upload process unless told to, it may make your board unusable
firmware_tool-flashing_step-flash_more = Flash more trackers
firmware_tool-flashing_step-exit = Exit
firmware_tool-flashing_step-onboarding_continue = Continue
## firmware tool build status
firmware_tool-build-QUEUED = Waiting to build....
@@ -1601,8 +1659,11 @@ tracking_checklist-FULL_RESET-desc = Some trackers need a reset to be performed.
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR not running
tracking_checklist-STEAMVR_DISCONNECTED-desc = SteamVR is not running. Are you using it for VR?
tracking_checklist-STEAMVR_DISCONNECTED-open = Launch SteamVR
tracking_checklist-STEAMVR_HANDS_ENABLED = Hand trackers toggled on
tracking_checklist-STEAMVR_HANDS_ENABLED-desc = You have enabled the SteamVR virtual hand trackers. This will cause button inputs to not work in SteamVR and in games.
tracking_checklist-STEAMVR_HANDS_ENABLED-go = Disable them
tracking_checklist-TRACKERS_REST_CALIBRATION = Calibrate your trackers
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = You didn't perform tracker calibration. Please let your trackers (highlighted in yellow) rest on a stable surface for a few secconds.
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = You didn't perform tracker calibration. Please let your trackers (highlighted in yellow) rest on a stable surface for a few seconds.
tracking_checklist-TRACKER_ERROR = Trackers with Errors
tracking_checklist-TRACKER_ERROR-desc = Some of your trackers have an error. Please restart the trackers highlighted in yellow.
tracking_checklist-VRCHAT_SETTINGS = Configure VRChat settings
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

+19 -1
View File
@@ -11,16 +11,18 @@ import {
WebSocketApiContext,
} from './hooks/websocket-api';
import { OnboardingContextProvider } from './components/onboarding/OnboardingContextProvicer';
import { OnboardingContextProvider } from './components/onboarding/OnboardingContextProvider';
import { OnboardingLayout } from './components/onboarding/OnboardingLayout';
import { AutomaticProportionsPage } from './components/onboarding/pages/body-proportions/AutomaticProportions';
import { ManualProportionsPage } from './components/onboarding/pages/body-proportions/ManualProportions';
import { ConnectTrackersPage } from './components/onboarding/pages/ConnectTracker';
import { HomePage } from './components/onboarding/pages/Home';
import { ErrorCollectingConsentPage } from './components/onboarding/pages/ErrorCollectingConsent';
import { AutomaticMountingPage } from './components/onboarding/pages/mounting/AutomaticMounting';
import { ManualMountingPage } from './components/onboarding/pages/mounting/ManualMounting';
import { TrackersAssignPage } from './components/onboarding/pages/trackers-assign/TrackerAssignment';
import { WifiCredsPage } from './components/onboarding/pages/WifiCreds';
import { DonglePage } from './components/onboarding/pages/Dongle';
import { ConfigContextProvider } from './components/providers/ConfigContext';
import { SerialDetectionModal } from './components/SerialDetectionModal';
import { VRCOSCSettings } from './components/settings/pages/VRCOSCSettings';
@@ -50,9 +52,14 @@ import { StayAlignedSetup } from './components/onboarding/pages/stay-aligned/Sta
import { TrackingChecklistProvider } from './components/tracking-checklist/TrackingChecklistProvider';
import { HomeScreenSettings } from './components/settings/pages/HomeScreenSettings';
import { ChecklistPage } from './components/tracking-checklist/TrackingChecklist';
import { QuizSlimeSetQuestion } from './components/onboarding/pages/quiz/SlimeSetQuestion';
import { QuizUsageQuestion } from './components/onboarding/pages/quiz/UsageQuestion';
import { QuizRuntimeQuestion } from './components/onboarding/pages/quiz/RuntimeQuestion';
import { QuizMocapPosQuestion } from './components/onboarding/pages/quiz/MocapPreferencesQuestions';
import { ElectronContextC, provideElectron } from './hooks/electron';
import { AppLocalizationProvider } from './i18n/config';
import { openUrl } from './hooks/crossplatform';
import { UdevRulesModal } from './components/onboarding/UdevRulesModal';
export const GH_REPO = 'SlimeVR/SlimeVR-Server';
export const VersionContext = createContext('');
@@ -70,6 +77,7 @@ function Layout() {
<SerialDetectionModal />
<VersionUpdateModal />
<UnknownDeviceModal />
<UdevRulesModal />
<SentryRoutes>
<Route element={<AppLayout />}>
<Route
@@ -147,7 +155,17 @@ function Layout() {
}
>
<Route path="home" element={<HomePage />} />
<Route
path="error-collecting-consent"
element={<ErrorCollectingConsentPage />}
/>
<Route path="wifi-creds" element={<WifiCredsPage />} />
<Route path="quiz/slime-set" element={<QuizSlimeSetQuestion />} />
<Route path="quiz/usage" element={<QuizUsageQuestion />} />
<Route path="quiz/runtime" element={<QuizRuntimeQuestion />} />
<Route path="quiz/mocap-pos" element={<QuizMocapPosQuestion />} />
<Route path="dongle" element={<DonglePage />} />
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
<Route path="connect-trackers" element={<ConnectTrackersPage />} />
<Route path="trackers-assign" element={<TrackersAssignPage />} />
<Route path="mounting/choose" element={<MountingChoose />} />
+8 -3
View File
@@ -1,9 +1,10 @@
import { useLayoutEffect } from 'react';
import { useConfig } from './hooks/config';
import { Outlet, useNavigate } from 'react-router-dom';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
export function AppLayout() {
const { config } = useConfig();
const { pathname } = useLocation();
const navigate = useNavigate();
useLayoutEffect(() => {
@@ -28,10 +29,14 @@ export function AppLayout() {
}, [config]);
useLayoutEffect(() => {
if (config && !config.doneOnboarding) {
if (
config &&
!config.doneOnboarding &&
!pathname.startsWith('/onboarding/')
) {
navigate('/onboarding/home');
}
}, [config?.doneOnboarding]);
}, [config]);
return (
<>
-60
View File
@@ -1,60 +0,0 @@
import { Localized, useLocalization } from '@fluent/react';
import { BaseModal } from './commons/BaseModal';
import { Button } from './commons/Button';
import { Typography } from './commons/Typography';
export function ErrorConsentModal({
isOpen = true,
cancel,
accept,
}: {
/**
* Is the parent/sibling component opened?
*/
isOpen: boolean;
/**
* Function to trigger when you still want to close the app
*/
accept: () => void;
/**
* Function to trigger when cancelling app close
*/
cancel?: () => void;
}) {
const { l10n } = useLocalization();
return (
<BaseModal isOpen={isOpen} onRequestClose={cancel} closeable={false}>
<div className="flex flex-col gap-3">
<>
<div className="flex flex-col items-center gap-3 fill-accent-background-20">
<div className="flex flex-col items-center gap-2 max-w-[512px]">
<Typography variant="main-title">
{l10n.getString('error_collection_modal-title')}
</Typography>
<Localized
id={'error_collection_modal-description_v2'}
elems={{
b: <b />,
h1: <span className="text-lg font-bold" />,
}}
>
<Typography
variant="standard"
whitespace="whitespace-pre-line"
/>
</Localized>
</div>
</div>
<Button variant="primary" onClick={accept}>
{l10n.getString('error_collection_modal-confirm')}
</Button>
<Button variant="tertiary" onClick={cancel}>
{l10n.getString('error_collection_modal-cancel')}
</Button>
</>
</div>
</BaseModal>
);
}
+2 -1
View File
@@ -14,7 +14,8 @@
't t t' var(--topbar-h)
'n b s' var(--toolbar-h)
'n c s' calc(100% - var(--topbar-h) - var(--toolbar-h))
/ var(--navbar-w) calc(100% - var(--navbar-w) - var(--right-section-w)) var(--right-section-w);
/ var(--navbar-w) calc(100% - var(--navbar-w) - var(--right-section-w))
var(--right-section-w);
}
@screen nsm {
+1 -6
View File
@@ -22,7 +22,6 @@ import { GearIcon } from './commons/icon/GearIcon';
import { TrackersStillOnModal } from './TrackersStillOnModal';
import { useConfig } from '@/hooks/config';
import { TrayOrExitModal } from './TrayOrExitModal';
import { ErrorConsentModal } from './ErrorConsentModal';
import { useAtomValue } from 'jotai';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import { useElectron } from '@/hooks/electron';
@@ -72,6 +71,7 @@ export function TopBar({
await saveConfig();
electron.api.close();
};
const tryCloseApp = async (dontTray = false) => {
if (!electron.isElectron) throw 'no electron';
@@ -286,11 +286,6 @@ export function TopBar({
setConnectedTrackerWarning(false);
}}
/>
<ErrorConsentModal
isOpen={config?.errorTracking === null}
accept={() => setConfig({ errorTracking: true })}
cancel={() => setConfig({ errorTracking: false })}
/>
</>
);
}
@@ -0,0 +1,60 @@
import { useState } from 'react';
import { BaseModal } from './BaseModal';
import { Button, ButtonProps } from './Button';
export type ButtonConfirmModal = Omit<ButtonProps, 'onClick' | 'to'> & {
onConfirm: () => void;
onCancel: (reason: 'cancel' | 'backdrop') => void;
confirmLabel: string;
cancelLabel: string;
};
export function ButtonConfirmModal(props: ButtonConfirmModal) {
const {
onConfirm,
onCancel,
cancelLabel,
confirmLabel,
children,
...buttonProps
} = props;
const [isOpen, setOpen] = useState(false);
return (
<>
<BaseModal
isOpen={isOpen}
onRequestClose={() => {
setOpen(false);
onCancel('backdrop');
}}
appendClasses="w-full max-w-2xl"
>
<div className="flex flex-col justify-between gap-4">
{children}
<div className="flex w-full justify-between gap-2 xs:flex-row flex-col">
<Button
id={cancelLabel}
variant="tertiary"
onClick={() => {
setOpen(false);
onCancel('cancel');
}}
/>
<Button
id={confirmLabel}
variant="primary"
onClick={() => {
setOpen(false);
onConfirm();
}}
/>
</div>
</div>
</BaseModal>
<Button {...buttonProps} onClick={() => setOpen(true)} />
</>
);
}
+4 -4
View File
@@ -1,6 +1,6 @@
import classNames from 'classnames';
import { forwardRef, useMemo } from 'react';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
export const CHECKBOX_CLASSES = classNames(
'bg-background-50 border-background-50 cursor-pointer rounded-md w-5 h-5 text-accent-background-30 focus:border-accent-background-40 focus:ring-transparent focus:ring-offset-transparent focus:outline-transparent'
@@ -112,7 +112,7 @@ export const CheckboxInternal = forwardRef<
);
});
export function CheckBox({
export function CheckBox<T extends FieldValues = FieldValues>({
label,
variant = 'checkbox',
color = 'primary',
@@ -123,8 +123,8 @@ export function CheckBox({
disabled,
}: {
label: string;
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
variant?: 'checkbox' | 'toggle';
color?: 'primary' | 'secondary' | 'tertiary';
outlined?: boolean;
+6 -3
View File
@@ -10,6 +10,8 @@ import {
import {
Control,
FieldError,
FieldPath,
FieldValues,
useController,
UseControllerProps,
} from 'react-hook-form';
@@ -415,14 +417,15 @@ export function DropdownInside({
);
}
export function Dropdown({
export function Dropdown<T extends FieldValues = FieldValues>({
control,
name,
rules,
...props
}: DropdownProps & {
control: Control<any>;
rules?: UseControllerProps<any>['rules'];
control: Control<T>;
name: FieldPath<T>;
rules?: UseControllerProps<T, FieldPath<T>>['rules'];
}) {
const {
field: { value, onChange },
+12 -5
View File
@@ -7,7 +7,13 @@ import {
useRef,
useState,
} from 'react';
import { Control, Controller, UseControllerProps } from 'react-hook-form';
import {
Control,
Controller,
FieldPath,
FieldValues,
UseControllerProps,
} from 'react-hook-form';
import { FileIcon } from './icon/FileIcon';
import { UploadFileIcon } from './icon/UploadFileIcon';
import { Typography } from './Typography';
@@ -193,7 +199,7 @@ export const FileInputInside = forwardRef<
);
});
export const FileInput = ({
export const FileInput = <T extends FieldValues = FieldValues>({
control,
name,
label,
@@ -204,8 +210,9 @@ export const FileInput = ({
capture,
importedFileName,
}: {
rules: UseControllerProps<any>['rules'];
control: Control<any>;
rules: UseControllerProps<T, FieldPath<T>>['rules'];
control: Control<T>;
name: FieldPath<T>;
accept: string;
multiple?: boolean;
capture?: boolean | 'user' | 'environment';
@@ -214,7 +221,7 @@ export const FileInput = ({
**/
label?: string;
importedFileName: string | null;
} & InputProps &
} & Omit<InputProps, 'name'> &
Partial<HTMLInputElement>) => {
return (
<Controller
+7 -4
View File
@@ -4,6 +4,8 @@ import {
Control,
Controller,
FieldError,
FieldPath,
FieldValues,
UseControllerProps,
} from 'react-hook-form';
import { EyeIcon } from './icon/EyeIcon';
@@ -117,7 +119,7 @@ export const InputInside = forwardRef<
);
});
export const Input = ({
export const Input = <T extends FieldValues = FieldValues>({
type = 'text',
control,
name,
@@ -128,10 +130,11 @@ export const Input = ({
variant = 'primary',
rules,
}: {
rules?: UseControllerProps<any>['rules'];
control: Control<any>;
rules?: UseControllerProps<T, FieldPath<T>>['rules'];
control: Control<T>;
name: FieldPath<T>;
autocomplete?: boolean | string;
} & InputProps &
} & Omit<InputProps, 'name'> &
Partial<React.HTMLProps<HTMLInputElement>>) => {
return (
<Controller
@@ -1,10 +1,10 @@
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import { Button } from './Button';
import { Typography } from './Typography';
import { useCallback, useMemo } from 'react';
import { useLocaleConfig } from '@/i18n/config';
export function NumberSelector({
export function NumberSelector<T extends FieldValues = FieldValues>({
label,
valueLabelFormat,
control,
@@ -18,8 +18,8 @@ export function NumberSelector({
}: {
label?: string;
valueLabelFormat?: (value: number) => string;
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
min: number;
max: number;
step: number | ((value: number, add: boolean) => number);
+4 -4
View File
@@ -1,9 +1,9 @@
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import { Typography } from './Typography';
import { ReactNode } from 'react';
export function Radio({
export function Radio<T extends FieldValues = FieldValues>({
control,
name,
label,
@@ -14,8 +14,8 @@ export function Radio({
disabled,
...props
}: {
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
label?: string;
value: string;
description?: string | null;
+4 -4
View File
@@ -1,7 +1,7 @@
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
export function Range({
export function Range<T extends FieldValues = FieldValues>({
control,
name,
values,
@@ -11,8 +11,8 @@ export function Range({
// input props
...props
}: {
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
max: number;
min: number;
step: number;
@@ -1,6 +1,8 @@
import {
Control,
Controller,
FieldPath,
FieldValues,
RefCallBack,
UseControllerProps,
} from 'react-hook-form';
@@ -48,20 +50,20 @@ export function InnerSystemFileInput({
);
}
export function SystemFileInput({
export function SystemFileInput<T extends FieldValues = FieldValues>({
control,
rules,
name,
label,
directory = false,
}: {
rules: UseControllerProps<any>['rules'];
control: Control<any>;
rules: UseControllerProps<T, FieldPath<T>>['rules'];
control: Control<T>;
/**
* Use a translation key!
**/
label: string;
name: string;
name: FieldPath<T>;
directory?: boolean;
disabled?: boolean;
}) {
+4 -4
View File
@@ -1,7 +1,7 @@
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
export function ThemeSelector({
export function ThemeSelector<T extends FieldValues = FieldValues>({
control,
name,
value,
@@ -10,8 +10,8 @@ export function ThemeSelector({
colors,
...props
}: {
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
colors: string | undefined;
value: string;
} & React.HTMLProps<HTMLInputElement>) {
@@ -60,15 +60,15 @@ export function BatteryIcon({
/>
</mask>
<g mask="url(#mask0_4_39)" className={classNames(col, 'opacity-100')}>
<rect width={charging ? 18 : value * 18} height="9" />
<rect width={charging ? 18 : value > 2 ? 0 : value * 18} height="9" />
</g>
{charging && value <= 1 && (
{charging && (value <= 1 || value > 2) && (
<path
d="M 7.7638355,8.4189633 8.0112251,4.9834646 5.7712838,4.9834645 8.5644084,0.07977871 8.3170195,3.5152773 H 10.55696 Z"
fill="#081e30"
/>
)}
{charging && value > 1 && (
{charging && value > 1 && value <= 2 && (
<path
d="M 5.5342464,4.6225095 C 6.1777799,5.0106205 6.6131537,5.2516456 7.5253371,6.545223 8.4340868,4.4016445 8.7809738,3.661475 10.605195,1.5520288"
fill="none"
@@ -1,10 +1,19 @@
export function HeadsetIcon({ width = 24 }: { width?: number }) {
export function HeadsetIcon({
width = 24,
disabled = false,
}: {
width?: number;
disabled?: boolean;
}) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={width} viewBox="0 0 640 512">
<path
transform="scale(0.75, 0.75) translate(120, 96)"
d="M576 64H64C28.7 64 0 92.7 0 128v256c0 35.3 28.7 64 64 64h120.4c24.2 0 46.4-13.7 57.2-35.4l32-64c8.8-17.5 26.7-28.6 46.3-28.6s37.5 11.1 46.3 28.6l32 64c10.8 21.7 33 35.4 57.2 35.4H576c35.3 0 64-28.7 64-64V128c0-35.3-28.7-64-64-64zM96 240a64 64 0 11128 0 64 64 0 11-128 0zm384-64a64 64 0 110 128 64 64 0 110-128z"
/>
{disabled && (
<line x1="20" y1="20" x2="620" y2="492" stroke="red" strokeWidth="30" />
)}
</svg>
);
}
@@ -0,0 +1,12 @@
export function SittingIcon({ size = 24 }: { size?: number }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
>
<path d="M600-160H320q-33 0-56.5-23.5T240-240v-440h80v440h280v80ZM460-720q-33 0-56.5-23.5T380-800q0-33 23.5-56.5T460-880q33 0 56.5 23.5T540-800q0 33-23.5 56.5T460-720ZM640-80v-200H440q-33 0-56.5-23.5T360-360v-220q0-42 29-71t71-29q42 0 71 29t29 71v180h80q33 0 56.5 23.5T720-320v240h-80Z" />
</svg>
);
}
@@ -1,9 +1,9 @@
export function SteamIcon() {
export function SteamIcon({ size = 20 }) {
return (
<svg
width="20"
height="18"
viewBox="0 0 20 18"
width={size}
height={size}
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M17.6562 5.32031C17.6562 6.10938 17.3903 6.7832 16.8583 7.3418C16.3263 7.90039 15.6845 8.17969 14.933 8.17969C14.1815 8.17969 13.5398 7.90039 13.0078 7.3418C12.4758 6.7832 12.2098 6.10938 12.2098 5.32031C12.2098 4.53125 12.4758 3.85742 13.0078 3.29883C13.5398 2.74023 14.1815 2.46094 14.933 2.46094C15.6845 2.46094 16.3263 2.74023 16.8583 3.29883C17.3903 3.85742 17.6562 4.53125 17.6562 5.32031ZM9.0625 14.0156C9.0625 13.2031 8.79092 12.5117 8.24777 11.9414C7.70461 11.3711 7.04613 11.0859 6.27232 11.0859C6.07143 11.0859 5.87054 11.1094 5.66964 11.1562L6.83036 11.6484C7.40327 11.8906 7.81064 12.3066 8.05246 12.8965C8.29427 13.4863 8.29985 14.0781 8.0692 14.6719C7.83854 15.2734 7.44048 15.6992 6.875 15.9492C6.30952 16.1992 5.74405 16.2031 5.17857 15.9609C5.02232 15.8984 4.79167 15.8027 4.48661 15.6738C4.18155 15.5449 3.95461 15.4492 3.8058 15.3867C4.0439 15.8555 4.38244 16.2324 4.82143 16.5176C5.26042 16.8027 5.74405 16.9453 6.27232 16.9453C7.04613 16.9453 7.70461 16.6602 8.24777 16.0898C8.79092 15.5195 9.0625 14.8281 9.0625 14.0156ZM18.3259 5.33203C18.3259 4.34766 17.9929 3.50586 17.327 2.80664C16.6611 2.10742 15.8594 1.75781 14.9219 1.75781C13.9769 1.75781 13.1715 2.10742 12.5056 2.80664C11.8397 3.50586 11.5067 4.34766 11.5067 5.33203C11.5067 6.32422 11.8397 7.16797 12.5056 7.86328C13.1715 8.55859 13.9769 8.90625 14.9219 8.90625C15.8594 8.90625 16.6611 8.55859 17.327 7.86328C17.9929 7.16797 18.3259 6.32422 18.3259 5.33203ZM20 5.33203C20 6.80859 19.5033 8.06641 18.51 9.10547C17.5167 10.1445 16.3207 10.6641 14.9219 10.6641L10.0446 14.4023C9.95536 15.4102 9.54985 16.2617 8.82812 16.957C8.1064 17.6523 7.25446 18 6.27232 18C5.37202 18 4.57589 17.7031 3.88393 17.1094C3.19196 16.5156 2.75298 15.7656 2.56696 14.8594L0 13.7812V8.75391L4.34152 10.5938C4.92932 10.2188 5.57292 10.0312 6.27232 10.0312C6.36905 10.0312 6.49926 10.0391 6.66295 10.0547L9.83259 5.28516C9.84747 3.82422 10.3516 2.57812 11.3449 1.54688C12.3382 0.515625 13.5305 0 14.9219 0C16.3207 0 17.5167 0.521484 18.51 1.56445C19.5033 2.60742 20 3.86328 20 5.33203Z" />
@@ -7,7 +7,7 @@ import {
} from '@/hooks/firmware-tool';
import { useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import {
FirmwareUpdateStatus,
TrackerStatus as TrackerStatusEnum,
@@ -22,9 +22,9 @@ interface DeviceCardProps {
color?: string;
}
interface DeviceCardControlProps {
control?: Control<any>;
name?: string;
interface DeviceCardControlProps<T extends FieldValues = FieldValues> {
control?: Control<T>;
name?: FieldPath<T>;
progress?: number;
disabled?: boolean;
}
@@ -55,7 +55,7 @@ export function DeviceCardContent({ deviceNames, status }: DeviceCardProps) {
);
}
export function DeviceCardControl({
export function DeviceCardControl<T extends FieldValues = FieldValues>({
control,
name,
progress,
@@ -63,7 +63,7 @@ export function DeviceCardControl({
online = null,
color = 'bg-background-60',
...props
}: DeviceCardControlProps & DeviceCardProps) {
}: DeviceCardControlProps<T> & DeviceCardProps) {
const cardborder = useMemo(() => {
if (!props.status) return 'border-transparent';
@@ -36,7 +36,7 @@ export function FlashingStep({
const { l10n } = useLocalization();
const { selectedDevices, selectDevices, files, selectedDefault } =
useFirmwareTool();
const { state: onboardingState } = useOnboarding();
const { state: onboardingState, state } = useOnboarding();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [status, setStatus] = useState<{
[key: string]: {
@@ -203,15 +203,28 @@ export function FlashingStep({
onClick={() => goTo('FlashingMethod')}
/>
</Localized>
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
/>
</Localized>
{state.alonePage && (
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
/>
</Localized>
)}
{!state.alonePage && (
<Localized id="firmware_tool-flashing_step-onboarding_continue">
<Button
variant="primary"
onClick={() => {
clear();
nav('/onboarding/trackers-assign');
}}
/>
</Localized>
)}
</div>
</div>
</div>
@@ -10,6 +10,7 @@ import {
} from '@/firmware-tool-api/firmwareToolComponents';
import { useEffect, useMemo, useState } from 'react';
import { useSafeLocalization } from '@/i18n/config';
import semver from 'semver';
function Selector({
text,
@@ -142,16 +143,33 @@ export function SelectSourceSetep({
!source.availableBoards.includes(partialBoard.board) ||
source.source !== partialBoard.source,
name: source.version,
isBranch: source.branch == source.version,
});
return curr;
},
[] as { name: string; disabled: boolean; isBranch: boolean }[]
[] as { name: string; disabled: boolean }[]
)
.sort((a, b) => {
if (a.isBranch !== b.isBranch) return a.isBranch ? 1 : -1;
return a.name.localeCompare(b.name);
// safeguard against inf loop
if (a == b) return 0;
const versionA = semver.valid(a.name);
const versionB = semver.valid(b.name);
// if both are not valid versions:
// if one is main, push that higher
// otherwise, push up the one which is alphabetically sooner
if (versionA == null && versionB == null) {
if (a.name == 'main') return -1;
return a.name.localeCompare(b.name);
}
// if one isn't valid, push the one that's valid up
if ((versionA == null) != (versionB == null))
return versionA == null ? 1 : -1;
// if A is lower, push B up
return semver.lt(versionA!, versionB!) ? 1 : -1;
}),
};
}, [sources, partialBoard]);
@@ -58,7 +58,7 @@ const DeviceList = ({
control,
devices,
}: {
control: Control<any>;
control: Control<FirmwareUpdateForm>;
devices: DeviceDataT[];
}) => {
const { l10n } = useLocalization();
@@ -103,11 +103,13 @@ export function BodyAssignment({
rolesWithErrors = {},
highlightedRoles = [],
onlyAssigned = false,
showAssignedTracker = true,
dotSize,
}: {
assignMode: AssignMode | null;
mirror: boolean;
onlyAssigned?: boolean;
showAssignedTracker?: boolean;
rolesWithErrors?: Partial<Record<BodyPart, BodyPartError>>;
highlightedRoles?: BodyPart[];
onRoleSelected: (role: BodyPart) => void;
@@ -165,6 +167,7 @@ export function BodyAssignment({
{hasBodyPart(BodyPart.HEAD) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[BodyPart.HEAD]?.label}
td={trackerPartGrouped[BodyPart.HEAD]}
role={BodyPart.HEAD}
@@ -176,6 +179,7 @@ export function BodyAssignment({
{hasBodyPart(BodyPart.NECK) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[BodyPart.NECK]?.label}
td={trackerPartGrouped[BodyPart.NECK]}
role={BodyPart.NECK}
@@ -188,6 +192,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].shoulder) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].shoulder]?.label}
td={trackerPartGrouped[SIDES[left].shoulder]}
role={SIDES[left].shoulder}
@@ -199,6 +204,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].upperArm) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].upperArm]?.label}
td={trackerPartGrouped[SIDES[left].upperArm]}
role={SIDES[left].upperArm}
@@ -211,6 +217,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].lowerArm) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].lowerArm]?.label}
td={trackerPartGrouped[SIDES[left].lowerArm]}
role={SIDES[left].lowerArm}
@@ -222,6 +229,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].hand) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].hand]?.label}
td={trackerPartGrouped[SIDES[left].hand]}
role={SIDES[left].hand}
@@ -234,6 +242,7 @@ export function BodyAssignment({
{hasBodyPart(BodyPart.HIP) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[BodyPart.HIP]?.label}
td={trackerPartGrouped[BodyPart.HIP]}
onClick={() => onRoleSelected(BodyPart.HIP)}
@@ -246,6 +255,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].upperLeg) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].upperLeg]?.label}
td={trackerPartGrouped[SIDES[left].upperLeg]}
role={SIDES[left].upperLeg}
@@ -257,6 +267,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].lowerLeg) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].lowerLeg]?.label}
td={trackerPartGrouped[SIDES[left].lowerLeg]}
role={SIDES[left].lowerLeg}
@@ -268,6 +279,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[left].foot) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[left].foot]?.label}
td={trackerPartGrouped[SIDES[left].foot]}
role={SIDES[left].foot}
@@ -284,6 +296,7 @@ export function BodyAssignment({
{hasBodyPart(BodyPart.UPPER_CHEST) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[BodyPart.UPPER_CHEST]?.label}
td={trackerPartGrouped[BodyPart.UPPER_CHEST]}
role={BodyPart.UPPER_CHEST}
@@ -295,6 +308,7 @@ export function BodyAssignment({
{hasBodyPart(BodyPart.CHEST) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[BodyPart.CHEST]?.label}
td={trackerPartGrouped[BodyPart.CHEST]}
role={BodyPart.CHEST}
@@ -308,6 +322,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].shoulder) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].shoulder]?.label}
td={trackerPartGrouped[SIDES[right].shoulder]}
role={SIDES[right].shoulder}
@@ -319,6 +334,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].upperArm) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].upperArm]?.label}
td={trackerPartGrouped[SIDES[right].upperArm]}
role={SIDES[right].upperArm}
@@ -332,6 +348,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].lowerArm) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].lowerArm]?.label}
td={trackerPartGrouped[SIDES[right].lowerArm]}
role={SIDES[right].lowerArm}
@@ -343,6 +360,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].hand) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].hand]?.label}
td={trackerPartGrouped[SIDES[right].hand]}
onClick={() => onRoleSelected(SIDES[right].hand)}
@@ -355,6 +373,7 @@ export function BodyAssignment({
{hasBodyPart(BodyPart.WAIST) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[BodyPart.WAIST]?.label}
td={trackerPartGrouped[BodyPart.WAIST]}
onClick={() => onRoleSelected(BodyPart.WAIST)}
@@ -367,6 +386,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].upperLeg) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].upperLeg]?.label}
td={trackerPartGrouped[SIDES[right].upperLeg]}
role={SIDES[right].upperLeg}
@@ -378,6 +398,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].lowerLeg) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].lowerLeg]?.label}
td={trackerPartGrouped[SIDES[right].lowerLeg]}
role={SIDES[right].lowerLeg}
@@ -389,6 +410,7 @@ export function BodyAssignment({
{hasBodyPart(SIDES[right].foot) && (
<TrackerPartCard
onlyAssigned={onlyAssigned}
showAssignedTracker={showAssignedTracker}
roleError={rolesWithErrors[SIDES[right].foot]?.label}
td={trackerPartGrouped[SIDES[right].foot]}
role={SIDES[right].foot}
@@ -0,0 +1,113 @@
import { useState, useEffect } from 'react';
import { Button } from '@/components/commons/Button';
import { BaseModal } from '@/components/commons/BaseModal';
import { CheckboxInternal } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { useElectron } from '@/hooks/electron';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { RpcMessage, InstalledInfoResponseT } from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useLocalization } from '@fluent/react';
export function UdevRulesModal() {
const { config, setConfig } = useConfig();
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
const electron = useElectron();
const [udevContent, setUdevContent] = useState('');
const [isUdevInstalledResponse, setIsUdevInstalledResponse] = useState(true);
const [showUdevWarning, setShowUdevWarning] = useState(false);
const [dontShowThisSession, setDontShowThisSession] = useState(false);
const [dontShowAgain, setDontShowAgain] = useState(false);
const { l10n } = useLocalization();
const handleUdevContent = async () => {
if (electron.isElectron) {
const dir = await electron.api.getInstallDir();
const rulesPath = `${dir}/69-slimevr-devices.rules`;
setUdevContent(
`cat ${rulesPath} | sudo sh -c 'tee /etc/udev/rules.d/69-slimevr-devices.rules >/dev/null && udevadm control --reload-rules && udevadm trigger'`
);
}
};
useEffect(() => {
handleUdevContent();
}, []);
useEffect(() => {
if (!config) throw 'Invalid state!';
if (electron.isElectron) {
const isLinux = electron.data().os.type === 'linux';
const udevMissing = !isUdevInstalledResponse;
const notHiddenGlobally = !config.dontShowUdevModal;
const notHiddenThisSession = !dontShowThisSession;
const shouldShow =
isLinux && udevMissing && notHiddenGlobally && notHiddenThisSession;
setShowUdevWarning(shouldShow);
}
}, [config, isUdevInstalledResponse, dontShowThisSession]);
useEffect(() => {
sendRPCPacket(
RpcMessage.InstalledInfoRequest,
new InstalledInfoResponseT()
);
}, []);
useRPCPacket(
RpcMessage.InstalledInfoResponse,
({ isUdevInstalled }: InstalledInfoResponseT) => {
setIsUdevInstalledResponse(isUdevInstalled);
}
);
const handleModalClose = () => {
if (!config) throw 'Invalid State!';
setConfig({ dontShowUdevModal: dontShowAgain });
setDontShowThisSession(true);
};
const copyToClipboard = () => {
navigator.clipboard.writeText(udevContent);
};
return (
<BaseModal isOpen={showUdevWarning} appendClasses={'w-full max-w-2xl'}>
<div className="flex w-full h-full flex-col gap-4">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="install-info_udev-rules_modal_title"
/>
<Typography id="install-info_udev-rules_warning" />
</div>
<div className="relative w-full max-w-2xl">
<div className="absolute right-2 top-2">
<Button variant="secondary" onClick={copyToClipboard}>
Copy
</Button>
</div>
<div className="bg-background-80 rounded-lg overflow-auto p-2 w-full h-[300px]">
<pre className="text-wrap">{udevContent}</pre>
</div>
</div>
</div>
<div className="flex justify-between gap-2">
<CheckboxInternal
label={l10n.getString(
'install-info_udev-rules_modal-dont-show-again_checkbox'
)}
name="dismiss-udev-rules-checkbox"
onChange={(e) => setDontShowAgain(e.currentTarget.checked)}
/>
<Button
variant="primary"
onClick={handleModalClose}
id="install-info_udev-rules_modal_button"
/>
</div>
</div>
</BaseModal>
);
}
@@ -12,9 +12,9 @@
grid-template:
's t' var(--connect-tracker-layout-top)
's c' calc(100% - var(--connect-tracker-layout-top))
/ calc(var(--connect-tracker-layout-sidebar)) calc(100% - var(
--connect-tracker-layout-sidebar
));
/ calc(var(--connect-tracker-layout-sidebar)) calc(
100% - var(--connect-tracker-layout-sidebar)
);
@screen mobile {
grid-template:
@@ -26,6 +26,7 @@ import { connectedIMUTrackersAtom } from '@/store/app-store';
import { BaseModal } from '@/components/commons/BaseModal';
import { A } from '@/components/commons/A';
import { useTrackingChecklist } from '@/hooks/tracking-checklist';
import { MoreSetsConfirm } from './quiz/MoreSetsConfirm';
const statusLabelMap = {
[WifiProvisioningStatus.NONE]:
@@ -317,13 +318,15 @@ export function ConnectTrackersPage() {
? l10n.getString('onboarding-connect_tracker-back')
: l10n.getString('onboarding-previous_step')}
</Button>
<Button
variant="primary"
to={state.alonePage ? '/' : '/onboarding/trackers-assign'}
className="ml-auto"
>
{l10n.getString('onboarding-connect_tracker-next')}
</Button>
{state.alonePage && (
<Button
variant="primary"
to={'/'}
className="ml-auto"
id="onboarding-connect_tracker-next"
/>
)}
{!state.alonePage && <MoreSetsConfirm />}
</div>
</div>
<div style={{ gridArea: 't' }} className="flex items-center px-5 pt-5">
@@ -0,0 +1,57 @@
import { Localized } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { WarningBox } from '@/components/commons/TipBox';
import { MoreSetsConfirm } from './quiz/MoreSetsConfirm';
export function DongleSectionContent() {
const { state } = useOnboarding();
return (
<div className="flex flex-col gap-2">
<div className="flex gap-2 items-center">
<div className="bg-accent-background-30 rounded-full p-2 fill-background-10">
<USBIcon size={24} />
</div>
<Typography
variant="main-title"
id="onboarding-wifi_creds-dongle-title"
/>
</div>
<div className={classNames('flex flex-col gap-2 flex-grow p-2')}>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-wifi_creds-dongle-description"
/>
<Localized id="onboarding-wifi_creds-dongle-wip">
<WarningBox whitespace>WARNING</WarningBox>
</Localized>
</div>
<div className="flex px-2 p-6">
{state.alonePage && (
<Button
variant="primary"
to={'/'}
id="onboarding-wifi_creds-dongle-continue"
/>
)}
{!state.alonePage && <MoreSetsConfirm />}
</div>
</div>
);
}
export function DonglePage() {
const { applyProgress } = useOnboarding();
applyProgress(0.5);
return (
<div className="flex flex-col w-full h-full xs:justify-center items-center">
<DongleSectionContent />
</div>
);
}
@@ -0,0 +1,49 @@
import { Localized } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { useConfig } from '@/hooks/config';
export function ErrorCollectingConsentPage() {
const { setConfig } = useConfig();
const accept = () => {
setConfig({ errorTracking: true });
};
const cancel = () => {
setConfig({ errorTracking: false });
};
return (
<div className="flex items-center justify-center h-full flex-col gap-3 p-4">
<div className="max-w-2xl flex flex-col gap-4">
<div className="flex flex-col w-full gap-4">
<Typography variant="main-title" id="error_collection_modal-title" />
<Localized
id="error_collection_modal-description_v2"
elems={{
b: <b />,
h1: <span className="text-md font-bold" />,
}}
>
<Typography variant="standard" whitespace="whitespace-pre-line" />
</Localized>
</div>
<div className="flex flex-row gap-2 justify-between">
<Button
variant="tertiary"
to="/onboarding/wifi-creds"
onClick={cancel}
id="error_collection_modal-cancel"
/>
<Button
variant="primary"
to="/onboarding/wifi-creds"
onClick={accept}
id="error_collection_modal-confirm"
/>
</div>
</div>
</div>
);
}
+1 -1
View File
@@ -19,7 +19,7 @@ export function HomePage() {
<Typography variant="mobile-title">
{l10n.getString('onboarding-home')}
</Typography>
<Button variant="primary" to="/onboarding/wifi-creds">
<Button variant="primary" to="/onboarding/quiz/slime-set">
{l10n.getString('onboarding-home-start')}
</Button>
</div>
@@ -1,16 +1,14 @@
import { Localized, useLocalization } from '@fluent/react';
import { Localized } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { useWifiForm } from '@/hooks/wifi-form';
import { Button } from '@/components/commons/Button';
import { Input } from '@/components/commons/Input';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { WifiIcon } from '@/components/commons/icon/WifiIcon';
import { WarningBox } from '@/components/commons/TipBox';
import { DongleSectionContent } from './Dongle';
export function WifiCredsPage() {
const { l10n } = useLocalization();
const { applyProgress, state } = useOnboarding();
const { control, handleSubmit, submitWifiCreds, formState } = useWifiForm();
@@ -18,34 +16,12 @@ export function WifiCredsPage() {
return (
<div className="flex flex-col w-full h-full xs:justify-center items-center">
<div className="grid xs:grid-cols-2 gap-4 max-w-6xl p-4">
<div className="flex flex-col gap-2">
<div className="flex gap-2 items-center">
<div className="bg-accent-background-30 rounded-full p-2 fill-background-10">
<USBIcon size={24} />
</div>
<Typography
variant="main-title"
id="onboarding-wifi_creds-dongle-title"
/>
</div>
<div className={classNames('flex flex-col gap-2 flex-grow p-2')}>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-wifi_creds-dongle-description"
/>
<Localized id="onboarding-wifi_creds-dongle-wip">
<WarningBox whitespace>WARNING</WarningBox>
</Localized>
</div>
<div className="flex px-2 p-6">
<Button
variant="primary"
to={state.alonePage ? '/' : '/onboarding/trackers-assign'}
id="onboarding-wifi_creds-dongle-continue"
/>
</div>
</div>
<div
className={classNames('grid gap-4 max-w-6xl p-4', {
'xs:grid-cols-2': state.alonePage,
})}
>
{state.alonePage && <DongleSectionContent />}
<form
className="flex flex-col gap-2"
onSubmit={handleSubmit(submitWifiCreds)}
@@ -105,21 +81,22 @@ export function WifiCredsPage() {
/>
</Localized>
<div className="flex flex-row gap-3 justify-between">
<Button
variant="secondary"
className={state.alonePage ? 'opacity-0' : ''}
state={{ alonePage: state.alonePage }}
to={'/onboarding/trackers-assign'}
>
{l10n.getString('onboarding-wifi_creds-skip')}
</Button>
{!state.alonePage ? (
<Button
variant="secondary"
state={{ alonePage: state.alonePage }}
to={'/onboarding/quiz/slime-set'}
id="onboarding-wifi_creds-back-v2"
/>
) : (
<div />
)}
<Button
type="submit"
variant="primary"
disabled={!formState.isValid}
>
{l10n.getString('onboarding-wifi_creds-submit')}
</Button>
id="onboarding-wifi_creds-submit"
/>
</div>
</div>
</div>
@@ -185,6 +185,10 @@ function ImportExportButtons() {
parseConfigImport(config).forEach((req) =>
sendRPCPacket(RpcMessage.ChangeSkeletonConfigRequest, req)
);
sendRPCPacket(
RpcMessage.SkeletonConfigRequest,
new SkeletonConfigRequestT()
);
setImportState(ImportStatus.SUCCESS);
setTimeout(() => {
setImportState(ImportStatus.OK);
@@ -478,7 +478,7 @@ export function ScaledProportionsPage() {
<Button
variant="primary"
id="onboarding-user_height-next_step"
to="/"
to="/onboarding/quiz/usage"
/>
)}
</div>
@@ -23,7 +23,7 @@ export function AutomaticMountingPage() {
const { l10n } = useLocalization();
const { applyProgress, state } = useOnboarding();
applyProgress(0.7);
applyProgress(0.6);
return (
<>
@@ -28,7 +28,7 @@ export function ManualMountingPage() {
const [selectedRole, setSelectRole] = useState<BodyPart>(BodyPart.NONE);
applyProgress(0.7);
applyProgress(0.6);
const assignedTrackers = useAtomValue(assignedTrackersAtom);
@@ -13,7 +13,7 @@ export function MountingChoose() {
const [animated, setAnimated] = useState(false);
const [showWarning, setShowWarning] = useState(false);
applyProgress(0.65);
applyProgress(0.55);
return (
<>
@@ -0,0 +1,155 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { HumanIcon } from '@/components/commons/icon/HumanIcon';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useState } from 'react';
import { SittingIcon } from '@/components/commons/icon/SittingIcon';
import { VMCFileUpload } from '@/components/settings/pages/VMCSettings';
import { QuizButton } from './SlimeSetQuestion';
export function QuizMocapPosQuestion() {
const { applyProgress, setMocapPos, mocapPos, playspace, setPlayspace } =
useOnboarding();
const [headTracker, setHeadTracker] = useState(true);
applyProgress(0.9);
const canContinue = (!headTracker || mocapPos) && playspace;
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="onboarding-quiz-mocap_preferences-title"
/>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-quiz-mocap_preferences-desc"
/>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-head_tracker-title"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={headTracker}
onClick={() => setHeadTracker(true)}
icon={<HeadsetIcon width={50} />}
name="onboarding-quiz-mocap_preferences-head_tracker-yes"
/>
<QuizButton
active={!headTracker}
onClick={() => {
setHeadTracker(false);
setMocapPos(undefined);
}}
icon={<HeadsetIcon width={50} disabled />}
name="onboarding-quiz-mocap_preferences-head_tracker-no"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-vrm_model-title"
/>
<Typography id="onboarding-quiz-mocap_preferences-vrm_model-desc" />
</div>
<VMCFileUpload />
</div>
</div>
{headTracker && (
<>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-playspace-title"
/>
<Typography id="onboarding-quiz-mocap_preferences-playspace-desc" />
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={playspace === 'sitting'}
onClick={() => setPlayspace('sitting')}
icon={<SittingIcon size={50} />}
name="onboarding-quiz-mocap_preferences-playspace-sitting"
/>
<QuizButton
active={playspace === 'standing'}
onClick={() => setPlayspace('standing')}
icon={<HumanIcon width={50} />}
name="onboarding-quiz-mocap_preferences-playspace-standing"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-head_tracker_location-title"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={mocapPos === 'forehead'}
onClick={() => setMocapPos('forehead')}
icon={
<img
src="/images/quiz/quiz_mocap-pos_forehead.webp"
className="w-44"
/>
}
name="onboarding-quiz-mocap_preferences-head_tracker_location-forehead"
/>
<QuizButton
active={mocapPos === 'face'}
onClick={() => setMocapPos('face')}
icon={
<img
src="/images/quiz/quiz_mocap-pos_face.webp"
className="w-44"
/>
}
name="onboarding-quiz-mocap_preferences-head_tracker_location-face"
/>
</div>
</div>
</div>
</>
)}
<div className="flex justify-between pb-4">
<Button
variant="secondary"
id="onboarding-quiz_back"
to="/onboarding/quiz/usage"
/>
<Button
variant="primary"
id="onboarding-quiz_continue"
disabled={!canContinue}
to="/"
/>
</div>
</div>
</div>
);
}
@@ -0,0 +1,30 @@
import { ButtonConfirmModal } from '@/components/commons/ButtonConfirmModal';
import { Typography } from '@/components/commons/Typography';
import { useNavigate } from 'react-router-dom';
export function MoreSetsConfirm() {
const navigate = useNavigate();
return (
<ButtonConfirmModal
variant="primary"
className="ml-auto"
id="onboarding-connect_tracker-next"
cancelLabel="onboarding-quiz-more_sets_modal-cancel"
confirmLabel="onboarding-quiz-more_sets_modal-confirm"
onConfirm={() => navigate('/onboarding/trackers-assign')}
onCancel={(reason) => {
if (reason === 'cancel') navigate('/onboarding/quiz/slime-set');
}}
>
<Typography
variant="main-title"
id="onboarding-quiz-more_sets_modal-title"
/>
<Typography
variant="vr-accessible"
id="onboarding-quiz-more_sets_modal-desc"
/>
</ButtonConfirmModal>
);
}
@@ -0,0 +1,55 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { QuizButton } from './SlimeSetQuestion';
import { SteamIcon } from '@/components/commons/icon/SteamIcon';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/commons/Button';
export function QuizRuntimeQuestion() {
const { applyProgress, setVrcOSC, vrcOsc } = useOnboarding();
const nav = useNavigate();
applyProgress(0.9);
const next = (type: typeof vrcOsc) => {
setVrcOSC(type);
nav('/');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="onboarding-quiz-runtime-title" />
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={!vrcOsc}
onClick={() => next(false)}
icon={<SteamIcon size={50} />}
name="onboarding-quiz-runtime-answer-steamvr"
/>
<QuizButton
active={vrcOsc}
onClick={() => next(true)}
icon={<HeadsetIcon width={80} />}
name="onboarding-quiz-runtime-answer-standalone"
/>
</div>
</div>
</div>
<div className="flex">
<Button
to={'/onboarding/quiz/usage'}
variant="secondary"
id="onboarding-quiz_back"
/>
</div>
</div>
</div>
);
}
@@ -0,0 +1,136 @@
import { useOnboarding } from '@/hooks/onboarding';
import { ReactNode } from 'react';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { useNavigate } from 'react-router-dom';
export function QuizButton({
name,
active,
icon,
onClick,
}: {
active?: boolean;
name: string;
icon: ReactNode;
onClick: () => void;
}) {
return (
<div
onClick={onClick}
className={classNames(
'flex rounded-lg bg-background-60 hover:bg-background-50 cursor-pointer',
'p-4 outline outline-2 flex-col gap-4 items-center justify-between fill-background-20',
{
'outline-accent-background-30': active,
'outline-transparent': !active,
}
)}
>
{icon}
<Typography id={name} variant="section-title" />
</div>
);
}
export function QuizSlimeSetQuestion() {
const { applyProgress, setSlimeSet, slimeSet } = useOnboarding();
const nav = useNavigate();
applyProgress(0.2);
const next = (type: typeof slimeSet) => {
setSlimeSet(type);
switch (type) {
case 'butterfly':
case 'dongle-slime':
nav('/onboarding/dongle');
break;
case 'slime-v1':
case 'wifi-slime':
nav('/onboarding/wifi-creds');
break;
}
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="onboarding-quiz-slimeset-title"
/>
<Typography id="onboarding-quiz-slimeset-description" />
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<Typography
variant="section-title"
id="onboarding-quiz-slimeset-official-sets"
/>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={slimeSet === 'slime-v1'}
onClick={() => next('slime-v1')}
icon={
<img
src="/images/trackers/v1_2_slime.webp"
className="w-60"
/>
}
name="onboarding-quiz-slimeset-answer-regular"
/>
<QuizButton
active={slimeSet === 'butterfly'}
onClick={() => next('butterfly')}
icon={
<img
src="/images/trackers/butterfly_slime.webp"
className="w-60"
/>
}
name="onboarding-quiz-slimeset-answer-butterfly"
/>
</div>
</div>
<div className="flex gap-2 flex-col">
<Typography
variant="section-title"
id="onboarding-quiz-slimeset-thirdparty-sets"
/>
<div className="grid grid-cols-2 gap-4">
<QuizButton
onClick={() => next('wifi-slime')}
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
height="50"
viewBox="0 0 24 24"
width="50"
className="fill-background-20"
>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z" />
</svg>
}
name="onboarding-quiz-slimeset-answer-wifi"
/>
<QuizButton
onClick={() => next('dongle-slime')}
icon={
<div className="fill-background-20">
<USBIcon size={50} />
</div>
}
name="onboarding-quiz-slimeset-answer-dongle"
/>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,62 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { QuizButton } from './SlimeSetQuestion';
import { useNavigate } from 'react-router-dom';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { HumanIcon } from '@/components/commons/icon/HumanIcon';
export function QuizUsageQuestion() {
const { applyProgress, setUsage, usage } = useOnboarding();
const nav = useNavigate();
applyProgress(0.8);
const next = (type: typeof usage) => {
setUsage(type);
if (type === 'vr-gaming') {
if (window.__ANDROID__) {
nav('/');
} else {
nav('/onboarding/quiz/runtime');
}
} else nav('/onboarding/quiz/mocap-pos');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="onboarding-quiz-usage-title" />
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-quiz-usage-description"
/>
</div>
<div className="flex flex-col gap-6">
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={usage === 'vr-gaming'}
icon={<HeadsetIcon width={50} />}
name="onboarding-quiz-usage-answer-VRC"
onClick={() => next('vr-gaming')}
/>
<QuizButton
active={usage === 'mocap'}
icon={<HumanIcon width={50} />}
name="onboarding-quiz-usage-answer-mocap_vtubing"
onClick={() => next('mocap')}
/>
</div>
</div>
<div className="flex">
<Button
to={'/onboarding/quiz/slime-set'}
variant="secondary"
id="onboarding-quiz_back"
/>
</div>
</div>
</div>
);
}
@@ -11,6 +11,7 @@ import { ResetType } from 'solarxr-protocol';
export function PreparationStep({
nextStep,
prevStep,
isActive,
}: VerticalStepComponentProps) {
return (
<div className="flex flex-col flex-grow justify-between py-2 gap-2">
@@ -53,7 +54,14 @@ export function PreparationStep({
<Button variant={'secondary'} onClick={prevStep} />
</Localized>
<ResetButton type={ResetType.Full} onReseted={nextStep} />
<ResetButton
type={ResetType.Full}
onReseted={() => {
if (isActive) {
nextStep();
}
}}
/>
</div>
</div>
);
@@ -10,6 +10,7 @@ import { ManualMountingPageStayAligned } from '@/components/onboarding/pages/mou
export function VerifyMountingStep({
nextStep,
prevStep,
isActive,
}: VerticalStepComponentProps) {
const { isMobile } = useBreakpoint('mobile');
const [isOpen, setOpen] = useState(false);
@@ -79,7 +80,11 @@ export function VerifyMountingStep({
onClick={() => setDisableMounting(true)}
type={ResetType.Mounting}
group="default"
onReseted={goNextStep}
onReseted={() => {
if (isActive) {
nextStep();
}
}}
onFailed={() => setDisableMounting(false)}
/>
</div>
@@ -55,7 +55,7 @@ export function TrackersAssignPage() {
const { isMd } = useBreakpoint('md');
const { l10n } = useLocalization();
const { config, setConfig } = useConfig();
const { applyProgress, state } = useOnboarding();
const { applyProgress, state, slimeSet } = useOnboarding();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const defaultValues = {
mirrorView: config?.mirrorView ?? defaultConfig.mirrorView,
@@ -100,7 +100,11 @@ export function TrackersAssignPage() {
tapDetectionSettings.mountingResetDelay,
tapDetectionSettings.mountingResetEnabled,
tapDetectionSettings.mountingResetTaps,
true
true,
null,
tapDetectionSettings.yawResetTracker,
tapDetectionSettings.fullResetTracker,
tapDetectionSettings.mountingResetTracker
);
sendRPCPacket(
@@ -329,9 +333,24 @@ export function TrackersAssignPage() {
<div className="flex flex-row">
{!state.alonePage && (
<>
<Button variant="secondary" to="/onboarding/wifi-creds">
{l10n.getString('onboarding-previous_step')}
</Button>
{state.alonePage && (
<Button variant="secondary" to="/onboarding/wifi-creds">
{l10n.getString('onboarding-previous_step')}
</Button>
)}
{!state.alonePage && (
<Button
variant="secondary"
to={
slimeSet &&
['butterfly', 'dongle-slime'].includes(slimeSet)
? '/onboarding/dongle'
: '/onboarding/wifi-creds'
}
>
{l10n.getString('onboarding-previous_step')}
</Button>
)}
<Button
variant="primary"
to="/onboarding/mounting/choose"
@@ -7,9 +7,9 @@
grid-template:
't t t' var(--topbar-h)
'n s c' calc(100% - var(--topbar-h))
/ var(--navbar-w) var(--settings-sidebar-w) calc(100% - var(--navbar-w) - var(
--settings-sidebar-w
));
/ var(--navbar-w) var(--settings-sidebar-w) calc(
100% - var(--navbar-w) - var(--settings-sidebar-w)
);
@screen lg {
--settings-sidebar-w: 270px;
@@ -1,6 +1,13 @@
import { Localized, useLocalization } from '@fluent/react';
import { useEffect, useState } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import { useEffect, useRef, useState } from 'react';
import {
Control,
Controller,
DefaultValues,
FieldPath,
FieldValues,
useForm,
} from 'react-hook-form';
import {
ChangeSettingsRequestT,
FilteringSettingsT,
@@ -15,8 +22,9 @@ import {
SteamVRTrackersSettingT,
TapDetectionSettingsT,
HIDSettingsT,
BodyPart,
} from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { AssignMode, defaultConfig, useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useLocaleConfig } from '@/i18n/config';
import { CheckBox } from '@/components/commons/Checkbox';
@@ -43,6 +51,103 @@ import {
loadResetSettings,
ResetSettingsForm,
} from '@/hooks/reset-settings';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
import { BodyPartIcon } from '@/components/commons/BodyPartIcon';
import { Button } from '@/components/commons/Button';
import { BodyAssignment } from '@/components/onboarding/BodyAssignment';
import { useBreakpoint } from '@/hooks/breakpoint';
import ReactModal from 'react-modal';
function TapResetPartSelector<T extends FieldValues = FieldValues>({
id,
control,
name,
}: {
id: string;
control: Control<T>;
name: FieldPath<T>;
}) {
const { isMobile } = useBreakpoint('mobile');
const { config } = useConfig();
const [bodyPartSelectorOpen, setBodyPartSelectorOpen] = useState(false);
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, value } }) => (
<>
<div className="flex flex-col gap-1 w-full">
<Typography bold id={id} />
<div className="flex justify-between bg-background-80 w-full p-3 rounded-lg">
<div className="flex gap-3 items-center fill-background-10">
<BodyPartIcon bodyPart={value} />
<Typography
id={
value === BodyPart.NONE
? 'settings-general-gesture_control-part_select-no_preference'
: 'body_part-' + BodyPart[value]
}
/>
</div>
<div className="flex">
<Button
variant="secondary"
onClick={() => setBodyPartSelectorOpen(true)}
id="settings-general-gesture_control-part_select-edit"
/>
</div>
</div>
</div>
<ReactModal
isOpen={bodyPartSelectorOpen}
shouldCloseOnOverlayClick
shouldCloseOnEsc
onRequestClose={() => setBodyPartSelectorOpen(false)}
overlayClassName="fixed top-0 right-0 left-0 bottom-0 flex flex-col items-center w-full h-full justify-center bg-background-90 bg-opacity-90 z-20"
className="focus:ring-transparent focus:ring-offset-transparent focus:outline-transparent outline-none mt-12 z-10 overflow-y-auto"
>
<div className="flex w-full h-full flex-col gap-10 px-3">
<div className="flex xs:flex-row h-full xs:gap-8 mobile:flex-col xs:justify-center items-center">
<div className="flex flex-col xs:flex-grow gap-3 rounded-xl fill-background-50 py-2">
<div className="flex flex-col xs:max-w-sm gap-3">
<Typography
variant="mobile-title"
bold
id="settings-general-gesture_control-part_select"
/>
</div>
<BodyAssignment
mirror={config?.mirrorView ?? defaultConfig.mirrorView}
width={isMobile ? 160 : undefined}
assignMode={AssignMode.All}
showAssignedTracker={false}
onRoleSelected={(part) => {
onChange(part);
setBodyPartSelectorOpen(false);
}}
/>
<div className="flex justify-center">
<Button
variant="secondary"
id="settings-general-gesture_control-part_select-reset"
onClick={() => {
onChange(BodyPart.NONE);
setBodyPartSelectorOpen(false);
}}
/>
</div>
</div>
</div>
</div>
</ReactModal>
</>
)}
/>
);
}
export type SettingsForm = {
trackers: {
@@ -86,15 +191,18 @@ export type SettingsForm = {
interpKneeAnkle: number;
};
tapDetection: {
mountingResetEnabled: boolean;
yawResetEnabled: boolean;
fullResetEnabled: boolean;
mountingResetEnabled: boolean;
yawResetDelay: number;
fullResetDelay: number;
mountingResetDelay: number;
yawResetTaps: number;
fullResetTaps: number;
mountingResetTaps: number;
yawResetTracker: BodyPart;
fullResetTracker: BodyPart;
mountingResetTracker: BodyPart;
numberTrackersOverThreshold: number;
};
legTweaks: {
@@ -146,15 +254,18 @@ const defaultValues: SettingsForm = {
},
filtering: { amount: 0.1, type: FilteringType.NONE },
tapDetection: {
mountingResetEnabled: false,
yawResetEnabled: false,
fullResetEnabled: false,
mountingResetEnabled: false,
yawResetDelay: 0.2,
fullResetDelay: 1.0,
mountingResetDelay: 1.0,
yawResetTaps: 2,
fullResetTaps: 3,
mountingResetTaps: 3,
yawResetTracker: BodyPart.NONE,
fullResetTracker: BodyPart.NONE,
mountingResetTracker: BodyPart.NONE,
numberTrackersOverThreshold: 1,
},
legTweaks: { correctionStrength: 0.3 },
@@ -163,11 +274,27 @@ const defaultValues: SettingsForm = {
hidSettings: { trackersOverHID: false },
};
const settingsAtom = atom(new SettingsResponseT());
const settingsValueAtom = selectAtom(
settingsAtom,
(settings) => settings,
isEqual
);
export function GeneralSettings() {
const setSettings = useSetAtom(settingsAtom);
const settings = useAtomValue(settingsValueAtom);
const { l10n } = useLocalization();
const { config } = useConfig();
const { currentLocales } = useLocaleConfig();
const blockHandsWarning = useRef(false);
// If not null, warning will be shown, and showHandsWarning will
// hold which hands should be toggled ([leftHand, rightHand])
const [showHandsWarning, setShowHandsWarning] = useState<
[boolean, boolean] | null
>(null);
const percentageFormat = new Intl.NumberFormat(currentLocales, {
style: 'percent',
maximumFractionDigits: 0,
@@ -183,17 +310,16 @@ export function GeneralSettings() {
const { reset, control, watch, handleSubmit, getValues, setValue } =
useForm<SettingsForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const {
trackers: {
automaticTrackerToggle,
leftHand: steamVrLeftHand,
rightHand: steamVrRightHand,
},
trackers: { automaticTrackerToggle },
} = watch();
const onSubmit = (values: SettingsForm) => {
const settings = new ChangeSettingsRequestT();
const settingsReq = new ChangeSettingsRequestT();
if (values.trackers) {
const trackers = new SteamVRTrackersSettingT();
@@ -211,8 +337,29 @@ export function GeneralSettings() {
trackers.leftHand = values.trackers.leftHand;
trackers.rightHand = values.trackers.rightHand;
if (
!blockHandsWarning.current &&
!showHandsWarning &&
!settings.steamVrTrackers?.leftHand &&
!settings.steamVrTrackers?.rightHand &&
(trackers.leftHand || trackers.rightHand)
) {
// We have just toggled on one of the hand trackers, show the user a warning
setShowHandsWarning([trackers.leftHand, trackers.rightHand]);
trackers.leftHand = false;
trackers.rightHand = false;
} else if (
blockHandsWarning.current &&
!trackers.leftHand &&
!trackers.rightHand
) {
// Both hand trackers have just been disabled, make sure the warning shows up
// again next time the user toggles one back on
blockHandsWarning.current = false;
}
trackers.automaticTrackerToggle = values.trackers.automaticTrackerToggle;
settings.steamVrTrackers = trackers;
settingsReq.steamVrTrackers = trackers;
}
const modelSettings = new ModelSettingsT();
@@ -257,44 +404,50 @@ export function GeneralSettings() {
modelSettings.legTweaks = legTweaks;
}
settings.modelSettings = modelSettings;
settingsReq.modelSettings = modelSettings;
const tapDetection = new TapDetectionSettingsT();
tapDetection.fullResetDelay = values.tapDetection.fullResetDelay;
tapDetection.fullResetEnabled = values.tapDetection.fullResetEnabled;
tapDetection.fullResetTaps = values.tapDetection.fullResetTaps;
tapDetection.fullResetTracker = values.tapDetection.fullResetTracker;
tapDetection.yawResetDelay = values.tapDetection.yawResetDelay;
tapDetection.yawResetEnabled = values.tapDetection.yawResetEnabled;
tapDetection.yawResetTaps = values.tapDetection.yawResetTaps;
tapDetection.yawResetTracker = values.tapDetection.yawResetTracker;
tapDetection.mountingResetEnabled =
values.tapDetection.mountingResetEnabled;
tapDetection.mountingResetDelay = values.tapDetection.mountingResetDelay;
tapDetection.mountingResetTaps = values.tapDetection.mountingResetTaps;
tapDetection.mountingResetTracker =
values.tapDetection.mountingResetTracker;
tapDetection.numberTrackersOverThreshold =
values.tapDetection.numberTrackersOverThreshold;
tapDetection.setupMode = false;
settings.tapDetectionSettings = tapDetection;
settingsReq.tapDetectionSettings = tapDetection;
const filtering = new FilteringSettingsT();
filtering.type = values.filtering.type;
filtering.amount = values.filtering.amount;
settings.filtering = filtering;
settingsReq.filtering = filtering;
settings.stayAligned = serializeStayAlignedSettings(values.stayAligned);
settingsReq.stayAligned = serializeStayAlignedSettings(values.stayAligned);
const hidSettings = new HIDSettingsT();
hidSettings.trackersOverHid = values.hidSettings.trackersOverHID;
settings.hidSettings = hidSettings;
settingsReq.hidSettings = hidSettings;
if (values.resetsSettings) {
settings.resetsSettings = loadResetSettings(values.resetsSettings);
settingsReq.resetsSettings = loadResetSettings(values.resetsSettings);
}
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsReq);
};
useEffect(() => {
const subscription = watch(() => handleSubmit(onSubmit)());
const subscription = watch((value, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
@@ -302,10 +455,7 @@ export function GeneralSettings() {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
// If null, we still haven't shown the hands warning
// if false then initially the hands warning was disabled
const [handsWarning, setHandsWarning] = useState<boolean | null>(null);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
useEffect(() => {
const formData: DefaultValues<SettingsForm> = {};
if (settings.filtering) {
@@ -315,10 +465,11 @@ export function GeneralSettings() {
if (settings.steamVrTrackers) {
formData.trackers = settings.steamVrTrackers;
if (
settings.steamVrTrackers.leftHand ||
settings.steamVrTrackers.rightHand
!blockHandsWarning.current &&
(settings.steamVrTrackers.leftHand ||
settings.steamVrTrackers.rightHand)
) {
setHandsWarning(false);
blockHandsWarning.current = true;
}
}
@@ -377,6 +528,15 @@ export function GeneralSettings() {
mountingResetTaps:
settings.tapDetectionSettings.mountingResetTaps ||
defaultValues.tapDetection.mountingResetTaps,
yawResetTracker:
settings.tapDetectionSettings.yawResetTracker ||
defaultValues.tapDetection.yawResetTracker,
fullResetTracker:
settings.tapDetectionSettings.fullResetTracker ||
defaultValues.tapDetection.fullResetTracker,
mountingResetTracker:
settings.tapDetectionSettings.mountingResetTracker ||
defaultValues.tapDetection.mountingResetTracker,
numberTrackersOverThreshold:
settings.tapDetectionSettings.numberTrackersOverThreshold ||
defaultValues.tapDetection.numberTrackersOverThreshold,
@@ -408,44 +568,27 @@ export function GeneralSettings() {
}
reset({ ...getValues(), ...formData });
}, [settings]);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
});
useEffect(() => {
if ((steamVrLeftHand || steamVrRightHand) && handsWarning === null) {
setHandsWarning(true);
} else if (
!(steamVrLeftHand || steamVrRightHand) &&
handsWarning === false
) {
setHandsWarning(null);
}
}, [steamVrLeftHand, steamVrRightHand, handsWarning]);
// Handle scrolling to selected page
// useEffect(() => {
// const typedState: { scrollTo: string } = state as any;
// if (!pageRef.current || !typedState || !typedState.scrollTo) {
// return;
// }
// const elem = pageRef.current.querySelector(`#${typedState.scrollTo}`);
// if (elem) {
// elem.scrollIntoView({ behavior: 'smooth' });
// }
// }, [state]);
return (
<SettingsPageLayout>
<HandsWarningModal
isOpen={!!handsWarning}
isOpen={!!showHandsWarning}
onClose={() => {
setValue('trackers.leftHand', false);
setValue('trackers.rightHand', false);
setHandsWarning(null);
setShowHandsWarning(null);
}}
accept={() => {
setValue('trackers.leftHand', true);
setValue('trackers.rightHand', true);
setHandsWarning(false);
const [leftHand, rightHand] = showHandsWarning!;
blockHandsWarning.current = true;
setValue('trackers.leftHand', leftHand);
setValue('trackers.rightHand', rightHand);
setShowHandsWarning(null);
}}
/>
<form className="flex flex-col gap-2 w-full">
@@ -1144,32 +1287,31 @@ export function GeneralSettings() {
/>
</div>
</div>
<div className="flex flex-col pt-2 pb-3">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-self_localization-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap3 pb5">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.selfLocalization"
label={l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
/>
</div>
</>
)}
<div className="flex flex-col pt-2 pb-3">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-self_localization-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap3 pb5">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.selfLocalization"
label={l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
/>
</div>
</>
</SettingsPagePaneLayout>
@@ -1216,6 +1358,23 @@ export function GeneralSettings() {
)}
/>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<TapResetPartSelector
control={control}
name="tapDetection.yawResetTracker"
id="settings-general-gesture_control-yawResetPart"
/>
<TapResetPartSelector
control={control}
name="tapDetection.fullResetTracker"
id="settings-general-gesture_control-fullResetPart"
/>
<TapResetPartSelector
control={control}
name="tapDetection.mountingResetTracker"
id="settings-general-gesture_control-mountingResetPart"
/>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<NumberSelector
control={control}
@@ -14,7 +14,7 @@ import {
import { useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { ReactNode, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { FieldPath, useForm } from 'react-hook-form';
import { TrackingChecklistStepId } from 'solarxr-protocol';
import * as Sentry from '@sentry/react';
@@ -82,7 +82,7 @@ export function TrackingChecklistSettings({
<div key={step.id}>
<CheckBox
control={control}
name={`steps.${step.id}`}
name={`steps.${step.id}` as FieldPath<StepsForm>}
disabled={!step.ignorable || !step.enabled}
label={l10n.getString(trackingchecklistIdtoLabel[step.id])}
outlined
+108 -41
View File
@@ -31,7 +31,6 @@ import { boolean, object } from 'yup';
interface VMCSettingsForm {
vmc: {
oscSettings: OSCSettings;
vrmJson?: FileList;
anchorHip: boolean;
mirrorTracking: boolean;
};
@@ -50,10 +49,92 @@ const defaultValues = {
},
};
export function VMCFileUpload() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { l10n } = useLocalization();
const [modelName, setModelName] = useState<string | null>(null);
const [settings, setSettings] = useState<SettingsResponseT>();
const { control, watch } = useForm<{
vrmJson?: FileList;
}>({
defaultValues: { vrmJson: undefined },
reValidateMode: 'onChange',
mode: 'onChange',
});
const vrmJson = watch('vrmJson');
const updateVRMJson = async () => {
if (!settings?.vmcOsc) return;
const req = new ChangeSettingsRequestT();
const vmcOsc = new VMCOSCSettingsT();
vmcOsc.oscSettings = Object.assign(
new OSCSettingsT(),
settings.vmcOsc.oscSettings
);
if (vrmJson !== undefined) {
if (vrmJson.length > 0) {
const file = await parseVRMFile(vrmJson[0]);
if (file) {
vmcOsc.vrmJson = file.json;
setModelName(file.name);
}
} else {
vmcOsc.vrmJson = '';
setModelName(null);
}
}
req.vmcOsc = vmcOsc;
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
};
useEffect(() => {
updateVRMJson();
}, [vrmJson]);
useEffect(() => {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
const vrmJson = settings.vmcOsc?.vrmJson?.toString();
if (vrmJson) {
let data: any;
try {
data = JSON.parse(vrmJson);
setModelName(getVRMName(data) || '');
} catch (e) {
error('Failed to fetch VRM name: ' + e);
}
}
});
return (
<FileInput
control={control}
name="vrmJson"
rules={{
required: false,
}}
value="help"
importedFileName={
// if modelname is an empty string, it's an untitled model
modelName === ''
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
: modelName
}
label="settings-osc-vmc-vrm-file_select"
accept="model/gltf-binary, model/gltf+json, model/vrml, .vrm, .glb, .gltf"
/>
);
}
export function VMCSettings() {
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [modelName, setModelName] = useState<string | null>(null);
const { oscValidator } = useOscSettingsValidator();
const { reset, control, watch, handleSubmit } = useForm<VMCSettingsForm>({
@@ -81,18 +162,6 @@ export function VMCSettings() {
new OSCSettingsT(),
values.vmc.oscSettings
);
if (values.vmc.vrmJson !== undefined) {
if (values.vmc.vrmJson.length > 0) {
const file = await parseVRMFile(values.vmc.vrmJson[0]);
if (file) {
vmcOsc.vrmJson = file.json;
setModelName(file.name);
}
} else {
vmcOsc.vrmJson = '';
setModelName(null);
}
}
vmcOsc.anchorHip = values.vmc.anchorHip;
vmcOsc.mirrorTracking = values.vmc.mirrorTracking;
@@ -124,10 +193,6 @@ export function VMCSettings() {
formData.vmc.oscSettings.address =
settings.vmcOsc.oscSettings.address.toString();
}
const vrmJson = settings.vmcOsc.vrmJson?.toString();
if (vrmJson) {
setModelName(getVRMName(vrmJson) || '');
}
formData.vmc.anchorHip = settings.vmcOsc.anchorHip;
formData.vmc.mirrorTracking = settings.vmcOsc.mirrorTracking;
@@ -238,23 +303,7 @@ export function VMCSettings() {
</Typography>
</div>
<div className="grid gap-3 pb-5">
<FileInput
control={control}
name="vmc.vrmJson"
rules={{
required: false,
}}
value="help"
importedFileName={
// if modelname is an empty string, it's an untitled model
modelName === ''
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
: modelName
}
label="settings-osc-vmc-vrm-file_select"
accept="model/gltf-binary, model/gltf+json, model/vrml, .vrm, .glb, .gltf"
/>
{/* For some reason, linux (GNOME) is detecting the VRM file is a VRML */}
<VMCFileUpload />
</div>
<Typography variant="section-title">
{l10n.getString('settings-osc-vmc-anchor_hip')}
@@ -344,16 +393,34 @@ async function parseVRMFile(
.slice(gltfHeaderEnd, gltfHeaderEnd + jsonLength, 'application/json')
.text();
const name = getVRMName(json);
let data: any;
try {
data = JSON.parse(json);
} catch (e) {
error('Failed to parse VRM glTF header: ' + e);
return null;
}
const name = getVRMName(data);
if (name === null) return null;
return { json, name };
// Only keep the fields we care about
/* eslint-disable camelcase */
const vrmJson = {
extensions: {
vrmV0: data.extensions.vrmV0,
VRMC_vrm: data.extensions.VRMC_vrm,
},
extensionsUsed: data.extensionsUsed,
nodes: data.nodes,
};
/* eslint-enable camelcase */
return { json: JSON.stringify(vrmJson), name };
}
function getVRMName(json: string): string | null {
function getVRMName(data: any): string | null {
try {
const data = JSON.parse(json);
if (typeof data?.extensions?.VRMC_vrm?.specVersion === 'string') {
const name = data.extensions.VRMC_vrm.meta.name;
@@ -369,7 +436,7 @@ function getVRMName(json: string): string | null {
return data?.extensions?.VRM?.meta?.title || '';
}
} catch (e) {
error(e);
error('Failed to fetch VRM name: ' + e);
return null;
}
}
@@ -13,7 +13,9 @@ export function TrackerBattery({
textColor = 'primary',
}: {
/**
* a [0, 1] value range is expected
* Normally [0, 1] value range
* Values >1 indicate fully charged
* Values <0 or >2 (Byte was cast to UByte, so -1 -> 255) also indicate 0%
*/
value: number;
voltage?: number | null;
@@ -36,11 +38,13 @@ export function TrackerBattery({
const debug = config?.debug || config?.devSettings.moreInfo;
const showVoltage = moreInfo && voltage && debug;
const pct = value > 2 ? 0 : Math.min(Math.max(value, 0), 1);
return (
<Tooltip
disabled={charging || !runtime || debug}
preferedDirection="left"
content=<Typography>{percentFormatter.format(value)}</Typography>
content=<Typography>{percentFormatter.format(pct)}</Typography>
>
<div className="flex gap-2">
<div className="flex flex-col justify-around">
@@ -61,7 +65,7 @@ export function TrackerBattery({
)}
{!charging && (!runtime || debug) && (
<Typography color={textColor}>
{percentFormatter.format(value)}
{percentFormatter.format(pct)}
</Typography>
)}
{showVoltage && (
+17 -11
View File
@@ -38,12 +38,14 @@ export function TrackerPartCard({
direction,
roleError,
onlyAssigned,
showAssignedTracker,
onClick,
}: {
td: FlatDeviceTracker[];
role: BodyPart;
roleError: string | undefined;
onlyAssigned: boolean;
showAssignedTracker: boolean;
direction: 'left' | 'right';
onClick?: MouseEventHandler<HTMLDivElement>;
}) {
@@ -107,17 +109,21 @@ export function TrackerPartCard({
>
{l10n.getString('body_part-' + BodyPart[role])}
</Typography>
{td?.map(({ tracker }, index) => (
<Tracker
tracker={tracker}
key={index}
updateVelocity={(vel) => updateVelocity(vel)}
/>
))}
{!td && (
<Typography color="text-background-30">
{l10n.getString('tracker-part_card-unassigned')}
</Typography>
{showAssignedTracker && (
<>
{td?.map(({ tracker }, index) => (
<Tracker
tracker={tracker}
key={index}
updateVelocity={(vel) => updateVelocity(vel)}
/>
))}
{!td && (
<Typography color="text-background-30">
{l10n.getString('tracker-part_card-unassigned')}
</Typography>
)}
</>
)}
</div>
)) || <></>
+1 -1
View File
@@ -1,5 +1,5 @@
import classNames from 'classnames';
import { IPv4 } from 'ip-num/IPNumber';
import { IPv4 } from 'ip-num';
import { createContext, ReactNode, useContext, useMemo } from 'react';
import { useConfig } from '@/hooks/config';
import { useTracker } from '@/hooks/tracker';
@@ -6,7 +6,12 @@ import {
} from '@/hooks/tracking-checklist';
import classNames from 'classnames';
import {
ChangeSettingsRequestT,
ResetType,
RpcMessage,
SettingsRequestT,
SettingsResponseT,
SteamVRTrackersSettingT,
TrackingChecklistPublicNetworksT,
TrackingChecklistStepId,
} from 'solarxr-protocol';
@@ -29,6 +34,7 @@ import { TrackingChecklistModal } from './TrackingChecklistModal';
import { NavLink, useNavigate } from 'react-router-dom';
import { useBreakpoint } from '@/hooks/breakpoint';
import { openUrl } from '@/hooks/crossplatform';
import { useWebsocketAPI } from '@/hooks/websocket-api';
function Step({
step: { status, id, optional, firstRequired },
@@ -102,6 +108,55 @@ function Step({
);
}
function SteamVRHandsEnabled() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [steamVrTrackers, setSteamVrTrackers] = useState<Omit<
SteamVRTrackersSettingT,
'pack'
> | null>(null);
useEffect(() => {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
if (settings.steamVrTrackers) {
setSteamVrTrackers(settings.steamVrTrackers);
}
});
const disableHandTrackers = () => {
const settings = new ChangeSettingsRequestT();
settings.steamVrTrackers = new SteamVRTrackersSettingT(
steamVrTrackers?.waist,
steamVrTrackers?.chest,
steamVrTrackers?.automaticTrackerToggle,
steamVrTrackers?.leftFoot,
steamVrTrackers?.rightFoot,
steamVrTrackers?.leftKnee,
steamVrTrackers?.rightKnee,
steamVrTrackers?.leftElbow,
steamVrTrackers?.rightElbow,
false,
false
);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
};
return (
<div className="space-y-2.5">
<Typography id="tracking_checklist-STEAMVR_HANDS_ENABLED-desc" />
<div className="flex">
<Button
id="tracking_checklist-STEAMVR_HANDS_ENABLED-go"
variant="primary"
onClick={disableHandTrackers}
/>
</div>
</div>
);
}
const stepContentLookup: Record<
number,
(
@@ -352,6 +407,9 @@ const stepContentLookup: Record<
</>
);
},
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]: () => {
return <SteamVRHandsEnabled />;
},
};
export function TrackingChecklistMobile() {
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { FieldPath, useForm } from 'react-hook-form';
import { useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { CheckBox } from '@/components/commons/Checkbox';
@@ -57,7 +57,7 @@ export function DeveloperModeWidget() {
control={control}
variant="toggle"
outlined
name={name}
name={name as FieldPath<DeveloperModeWidgetForm>}
label={l10n.getString(`widget-developer_mode-${label}`)}
/>
);
+3 -4
View File
@@ -48,6 +48,7 @@ export interface Config {
homeLayout: 'default' | 'table';
skeletonPreview: boolean;
lastUsedProportions: 'manual' | 'autobone' | 'scaled' | null;
dontShowUdevModal: boolean;
}
export interface ConfigContext {
@@ -79,6 +80,7 @@ export const defaultConfig: Config = {
homeLayout: 'default',
skeletonPreview: true,
lastUsedProportions: null,
dontShowUdevModal: false,
};
const localStore: CrossStorage = {
@@ -103,10 +105,7 @@ function fallbackToDefaults(loadedConfig: any): Config {
// allows to load everything before the first render
export const loadConfig = async () => {
try {
const json = await store.get<string>('config.json');
if (!json) throw new Error('Config has ceased existing for some reason');
const json = (await store.get<string>('config.json')) ?? '{}';
const loadedConfig = fallbackToDefaults(JSON.parse(json));
if (!loadedConfig.uuid) {
+2 -1
View File
@@ -152,7 +152,8 @@ export function checkForUpdate(
if (
canUpdate &&
device.hardwareStatus?.batteryPctEstimate != null &&
device.hardwareStatus.batteryPctEstimate < 50
(device.hardwareStatus.batteryPctEstimate < 50 ||
device.hardwareStatus.batteryPctEstimate > 200)
) {
return 'low-battery';
}
+108 -10
View File
@@ -1,6 +1,28 @@
import { createContext, Reducer, useContext, useLayoutEffect, useReducer } from 'react';
import {
createContext,
Reducer,
useContext,
useEffect,
useLayoutEffect,
useReducer,
useState,
} from 'react';
import { useLocation } from 'react-router-dom';
import { useConfig } from './config';
import { useWebsocketAPI } from './websocket-api';
import {
ChangeSettingsRequestT,
ModelSettingsT,
ModelTogglesT,
OSCSettingsT,
ResetsSettingsT,
RpcMessage,
SettingsRequestT,
SettingsResponseT,
SkeletonBone,
VRCOSCSettingsT,
} from 'solarxr-protocol';
import { useManualProportions } from './manual-proportions';
type OnboardingAction =
| { type: 'progress'; value: number }
@@ -13,13 +35,6 @@ interface OnboardingState {
alonePage: boolean;
}
export interface OnboardingContext {
state: OnboardingState;
applyProgress: (value: number) => void;
setWifiCredentials: (ssid: string, password?: string) => void;
skipSetup: () => void;
}
export function reducer(state: OnboardingState, action: OnboardingAction) {
switch (action.type) {
case 'wifi-creds':
@@ -42,8 +57,17 @@ export function reducer(state: OnboardingState, action: OnboardingAction) {
}
}
export function useProvideOnboarding(): OnboardingContext {
export type OnboardingContext = ReturnType<typeof useProvideOnboarding>;
export function useProvideOnboarding() {
const { setConfig } = useConfig();
const [slimeSet, setSlimeSet] = useState<
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime'
>();
const [usage, setUsage] = useState<'vr-gaming' | 'mocap' | 'vtubing'>();
const [vrcOsc, setVrcOSC] = useState<boolean>();
const [mocapPos, setMocapPos] = useState<'forehead' | 'face'>();
const [playspace, setPlayspace] = useState<'sitting' | 'standing'>();
const [state, dispatch] = useReducer<Reducer<OnboardingState, OnboardingAction>>(
reducer,
{
@@ -52,7 +76,11 @@ export function useProvideOnboarding(): OnboardingContext {
}
);
const { state: locatioState } = useLocation();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { state: locatioState, pathname } = useLocation();
const [previousPath, setPreviousPath] = useState(pathname);
const [settings, setSettings] = useState<SettingsResponseT>();
useLayoutEffect(() => {
const { alonePage = false }: { alonePage?: boolean } = (locatioState as any) || {};
@@ -61,8 +89,74 @@ export function useProvideOnboarding(): OnboardingContext {
dispatch({ type: 'alone-page', value: alonePage });
}, [locatioState, state]);
useEffect(() => {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
});
const { changeBoneValue } = useManualProportions({
type: 'linear',
});
const onboardingEnded = () => {
if (!settings?.modelSettings || !settings?.vrcOsc) return;
const req = new ChangeSettingsRequestT();
const modelSettings = new ModelSettingsT();
const oscSettings = new VRCOSCSettingsT();
const mocap = usage === 'mocap' || usage === 'vtubing';
const toggles = Object.assign(new ModelTogglesT(), settings.modelSettings.toggles);
toggles.selfLocalization = mocap && playspace === 'standing';
modelSettings.toggles = toggles;
req.modelSettings = modelSettings;
const resets = Object.assign(new ResetsSettingsT(), settings.resetsSettings);
resets.resetHmdPitch = mocapPos === 'forehead';
req.resetsSettings = resets;
const osc = Object.assign(new OSCSettingsT(), settings.vrcOsc.oscSettings);
osc.enabled = vrcOsc ?? false;
oscSettings.oscSettings = osc;
req.vrcOsc = oscSettings;
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
if (mocap) {
changeBoneValue({ bone: SkeletonBone.HAND_Z, type: 'bone', newValue: 0 });
}
};
const onboardingStarted = () => {
setSlimeSet(undefined);
setUsage(undefined);
setVrcOSC(undefined);
setMocapPos(undefined);
setPlayspace(undefined);
};
useEffect(() => {
setPreviousPath(pathname);
if (!pathname.startsWith('/onboarding') && previousPath.startsWith('/onboarding')) {
onboardingEnded();
}
if (pathname.startsWith('/onboarding') && !previousPath.startsWith('/onboarding')) {
onboardingStarted();
}
}, [pathname]);
return {
state,
slimeSet,
usage,
vrcOsc,
mocapPos,
playspace,
setPlayspace,
applyProgress: (value: number) => {
useLayoutEffect(() => {
dispatch({ type: 'progress', value });
@@ -74,6 +168,10 @@ export function useProvideOnboarding(): OnboardingContext {
skipSetup: () => {
setConfig({ doneOnboarding: true });
},
setSlimeSet,
setUsage,
setVrcOSC,
setMocapPos,
};
}
+2
View File
@@ -30,6 +30,8 @@ export const trackingchecklistIdtoLabel: Record<TrackingChecklistStepId, string>
'tracking_checklist-FEET_MOUNTING_CALIBRATION',
[TrackingChecklistStepId.STAY_ALIGNED_CONFIGURED]:
'tracking_checklist-STAY_ALIGNED_CONFIGURED',
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]:
'tracking_checklist-STEAMVR_HANDS_ENABLED',
};
export type TrackingChecklistStepStatus =
+5 -1
View File
@@ -11,8 +11,12 @@ import { DeviceDataT } from 'solarxr-protocol';
export function getSentryOrCompute(enabled = false, uuid: string) {
Sentry.setUser({ id: uuid });
// if sentry is already initialized - SKIP
if (enabled && Sentry.isInitialized()) return;
if (enabled && Sentry.isInitialized()) {
log('Sentry already enabled, skipping initialization');
return;
}
const client = Sentry.getClient();
if (client) {
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "slimevr",
"version": "0.0.0",
"private": true,
"packageManager": "pnpm@9.12.2",
"packageManager": "pnpm@10.33.0",
"workspaces": [
"solarxr-protocol",
"gui"
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff. Show more