Compare commits

..
Author SHA1 Message Date
JovannMC e9622135c1 fix: avoid calculating velocity if accel is available 2026-11-25 22:41:23 +03:00
JovannMC 5e06df1458 Merge branch 'server-rewrite' into maya/onboarding-middleware 2026-11-25 20:04:48 +03:00
JovannMC 96309573b3 fix(onboarding): navigate properly on previous step 2026-11-25 19:12:16 +03:00
JovannMC 3d13bfc5df fix(onboarding): show solarxr (driver) trackers in middleware
slimetora can use solarxr to connect to slimevr now
2026-11-24 21:24:49 +03:00
JovannMC 3a570585a8 feat(solarxr): add linear acceleration
slimetora already calculates linear acceleration. adds to solarxr and takes precedence over velocity, if available
2026-11-24 17:35:13 +03:00
Sapphire 48255272d2 Put exit code and received signal in Sentry event tags instead of extra 2026-11-23 04:23:52 -05:00
Sapphire e4b0d0a58e Catch exceptions in implementation of ProcessHandle::allProcesses 2026-11-21 20:16:00 -05:00
Sapphire ae9efb1a92 Clean up conditions in TrackerBattery a bit 2026-11-21 17:39:48 -05:00
Sapphire 0368292bf1 Toggle to show battery runtime estimate instead of percentage 2026-11-21 17:37:05 -05:00
Sapphire d55c0ef494 Don't snap skeleton height when switching units
This ends up showing the 'are you sure you want to do this' popup
when switching units, which is annoying. Feel free to revert if this has
bad side effects.
2026-11-21 17:15:00 -05:00
JovannMC baa82a3683 feat(onboarding): unknown trackers in external software page 2026-11-21 23:50:41 +03:00
JovannMC ee58f3d5f4 feat(onboarding): external software ui
adds middleware connection page based off wifi slime page

fixed wifi/middleware title padding on mobile & use DOCS_TROUBLESHOOTING_URL properly
2026-11-20 23:03:29 +03:00
Butterscotch! 7bc6d99f09 AutoBone weighted average bone contribution 2026-11-20 01:35:27 -05:00
Erimel 7cf14188e6 make foot plant and toe snap less agressive 2026-11-19 16:15:57 -05:00
Erimel 292da8d91f upper waist as default 2026-11-19 16:14:11 -05:00
JovannMC a8e4006b34 feat(onboarding): tracker type external software btn 2026-11-19 23:49:18 +03:00
Erimel 594391a647 gui lint 2026-11-18 17:45:06 -05:00
Erimel e719fe38cf spotless 2026-11-18 17:37:23 -05:00
Erimel 9667fd93be Fix Stay Aligned first frame being way too strong 2026-11-18 17:36:19 -05:00
Erimel e2406cacac improve upper leg twist math 2026-11-18 17:25:44 -05:00
Erimel 48b36961f7 Increase max yaw reset smooth time to 1s 2026-11-18 16:31:06 -05:00
Erimel 128d5e58da Skeleton processor reset when yaw reset smoothing finishes 2026-11-18 16:20:11 -05:00
Erimel c71f06cf71 TapDetection -> TrackerAction 2026-11-18 16:04:05 -05:00
Aed 78deb81e21 Tap/Button Reset settings (#1963) 2026-11-18 13:32:52 -05:00
Erimel 768a623cd2 Move Setup Wizard at the bottom of the settings 2026-11-17 23:29:03 -05:00
Erimel 3ea39549ba fix tests 2026-11-17 20:59:47 -05:00
Erimel e2e0a3d87d tune prediction 2026-11-17 20:52:02 -05:00
Erimel 2068b208f8 lower default prediction 2026-11-17 20:19:28 -05:00
Erimel f44baef615 compensate for feet pose mounting going inwards 2026-11-17 20:19:20 -05:00
Erimel 40848cd8a3 bone offset in tracker module 2026-11-17 19:48:24 -05:00
Erimel c9e0479a51 Remove TrackerDataType 2026-11-17 14:49:45 -05:00
Erimel 4e5f0736d9 Constrain preferred rotations 2026-11-16 20:07:50 -05:00
Erimel 4e84ebdfc9 upper leg twist as post processing 2026-11-16 19:59:44 -05:00
Erimel 999c27c36f yawAlign 300ms todo 2026-11-16 19:58:14 -05:00
Erimel 64af814db0 Revert "Add TODO for GIT_COMMIT_HASH"
This reverts commit f2b86ec6fd.
2026-11-16 19:03:00 -05:00
Erimel 0479b162b4 Improve feet scaling in preview 2026-11-16 17:14:43 -05:00
Erimel f2b86ec6fd Add TODO for GIT_COMMIT_HASH 2026-11-16 15:43:42 -05:00
Erimel e4482971b0 Disable stay aligned for ADC_RESISTANCE 2026-11-16 15:43:18 -05:00
Erimel cf55f48e2f reorganize stayaligned ImuTypes 2026-11-16 15:34:11 -05:00
loucass003 caf8435636 Migrate old server configs to rewrite 2026-11-13 23:59:35 +01:00
loucass003 6b65058bb3 Fix multiple trackers on the same part display. add occluded to the assignment conflict stuff 2026-11-13 21:34:34 +01:00
loucass003 4fa3f83f95 Fix crowdin when built for prod 2026-11-13 19:36:26 +01:00
Erimel 4481aea2b3 80% knee interpolation default 2026-11-12 16:33:09 -05:00
Erimel 8c1478d3e4 Fix preffered rotation snapping 2026-11-12 16:07:14 -05:00
Erimel 9942e843ff Fix upper legs twist math 2026-11-12 15:12:01 -05:00
Erimel d0fa419131 improve hip tracker reliability 2026-11-12 15:07:14 -05:00
Erimel 834e5d340e Improve arm IK constraints 2026-11-12 14:04:48 -05:00
94 changed files with 1824 additions and 733 deletions

No files matched your search

+17 -18
View File
@@ -326,7 +326,6 @@ tracker-infos-custom_name = Custom Name
tracker-infos-url = Tracker URL
tracker-infos-hardware_identifier = Hardware ID
tracker-infos-mac_address = MAC address
tracker-infos-data_type = Data type
tracker-infos-imu = IMU Sensor
tracker-infos-board_type = Main board
tracker-infos-network_version = Protocol Version
@@ -778,8 +777,8 @@ settings-general-fk_settings-self_localization-title = Mocap mode
settings-general-fk_settings-self_localization-description = Mocap Mode allows the skeleton to roughly track its own position without any positional tracker.
## Gesture control settings (tracker tapping)
settings-general-gesture_control-subtitle = Tap/button based resets
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker or pressing its button. Taps must occur within the time limit of 0.3 seconds times the number of taps to be recognized.
settings-general-gesture_control-subtitle = Tracker actions
settings-general-gesture_control-description = Allows resets to be triggered by tapping a tracker repetitively or pressing its button.
# 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 ->
@@ -792,27 +791,19 @@ settings-general-gesture_control-trackers = { $amount ->
[one] 1 tracker
*[other] { $amount } trackers
}
settings-general-gesture_control-column-reset = Reset
settings-general-gesture_control-BUTTON = Button
settings-general-gesture_control-TAP = Tap
settings-general-gesture_control-BOTH = Both
settings-general-gesture_control-column-action = Action
settings-general-gesture_control-column-tracker = Tracker
settings-general-gesture_control-column-method = Method
settings-general-gesture_control-column-taps = Taps
settings-general-gesture_control-column-delay = Delay
settings-general-gesture_control-yawReset-name = Yaw reset
settings-general-gesture_control-fullReset-name = Full reset
settings-general-gesture_control-mountingReset-name = Mounting calibration
settings-general-gesture_control-yawResetEnabled = Enable tap to yaw reset
settings-general-gesture_control-yawResetDelay = Yaw reset delay
settings-general-gesture_control-yawResetTaps = Taps for yaw reset
settings-general-gesture_control-yawResetTracker = Yaw reset tracker
settings-general-gesture_control-fullResetEnabled = Enable tap to full reset
settings-general-gesture_control-fullResetDelay = Full reset delay
settings-general-gesture_control-fullResetTaps = Taps for full reset
settings-general-gesture_control-fullResetTracker = Full reset tracker
settings-general-gesture_control-mountingResetEnabled = Enable tap to perform mounting calibration
settings-general-gesture_control-mountingResetDelay = Mounting calibration delay
settings-general-gesture_control-mountingResetTaps = Taps for mounting calibration
settings-general-gesture_control-mountingResetTracker = Mounting reset tracker
# The number of trackers that can have higher acceleration before a tap is rejected
settings-general-gesture_control-numberTrackersOverThreshold = Trackers over threshold
settings-general-gesture_control-tapsTrackersOverThreshold = Taps trackers over threshold
settings-general-gesture_control-numberTrackersOverThreshold-description = Increase this value if tap detection is not working. Do not increase it above what is needed to make it work in order to prevent false positives.
## Appearance settings
@@ -1163,6 +1154,7 @@ settings-home-table_columns-desc = Choose which columns are shown in the tracker
settings-home-display_group = Display
settings-home-tracker_display = Tracker info
settings-home-tracker_display-desc = Choose which extra details are shown on trackers
settings-home-tracker_display-battery_runtime_estimate = Battery runtime estimate
settings-home-tracker_display-battery_voltage = Battery voltage
settings-home-tracker_display-numeric_signal = Numeric signal strength
@@ -1197,6 +1189,7 @@ onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 & V1.2
onboarding-quiz-slimeset-answer-butterfly = Butterfly
onboarding-quiz-slimeset-answer-wifi = Wi-Fi-based Slime
onboarding-quiz-slimeset-answer-dongle = Dongle-based Slime
onboarding-quiz-slimeset-answer-middleware = External software
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.
@@ -1271,17 +1264,24 @@ onboarding-home-start = Let's get set up!
## Tracker connection setup
onboarding-connect_tracker-title = Let's connect your trackers
onboarding-connect_tracker-description = Enter your Wi-Fi network below and submit once. Every tracker you connect via USB, now or later, will automatically use those credentials.
onboarding-connect_tracker-description-middleware =
Follow the instructions of the external software you are using to connect your trackers.
This page is for connecting non-SlimeVR trackers via external software, which interprets devices to act like SlimeVR trackers.
onboarding-connect_tracker-learn_more = Learn more
onboarding-connect_tracker-issue-serial = I'm having trouble connecting!
onboarding-connect_tracker-issue-middleware = I'm having trouble connecting!
onboarding-connect_tracker-usb = USB Tracker
onboarding-connect_tracker-tracker_mac_name = SlimeVR Tracker ({ $suffix })
onboarding-connect_tracker-tracker_port_name = USB Tracker ({ $port })
onboarding-connect_tracker-network_profile-ignore = I configured my firewall and know what I'm doing
onboarding-connect_tracker-waiting_first_title = Waiting for your first tracker
onboarding-connect_tracker-waiting_first_desc = Plug one in over USB to get started.
onboarding-connect_tracker-waiting_first_desc-middleware = Follow the instructions of the external software you are using to connect your trackers.
onboarding-connect_tracker-scan_results_title = Select network & enter password
onboarding-connect_tracker-scan_results_desc = Enter your Wi-Fi credentials on the left to connect your trackers.
onboarding-connect_tracker-all_caught_up = All caught up. Plug in more any time
onboarding-connect_tracker-all_caught_up-middleware = All caught up. Connect more from the external software any time.
onboarding-connect_tracker-shake_tip = Not sure which tracker is which? Shake a tracker to see it light up in the list.
onboarding-connect_tracker-close = Close
onboarding-connect_tracker-connection_status-serial_init = Connecting to serial device
@@ -1310,7 +1310,6 @@ onboarding-connect_tracker-connected_trackers = { $amount ->
} connected
onboarding-connect_tracker-setting_up = Setting up ({ $amount })
onboarding-connect_tracker-next = I connected all my trackers
## Tracker assignment setup
onboarding-assign_trackers-title = Assign trackers
onboarding-assign_trackers-description = Let's choose which tracker goes where. Click on a location where you want to place a tracker.
+8 -1
View File
@@ -192,7 +192,14 @@ function AppRoutes() {
<Route path="dongle" element={<DonglePage />} />
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
<Route path="add-trackers" element={<AddTrackersPage />} />
<Route path="connect-trackers" element={<ConnectTrackersPage />} />
<Route
path="connect-trackers"
element={<ConnectTrackersPage type="slimevr" />}
/>
<Route
path="connect-middleware"
element={<ConnectTrackersPage type="middleware" />}
/>
<Route path="trackers-assign" element={<TrackersAssignPage />} />
<Route path="mounting/choose" element={<MountingChoose />} />
<Route path="mounting/auto" element={<AutomaticMountingPage />} />
@@ -74,14 +74,14 @@ export function PersonFrontIcon({
<circle
className="body-part-circle"
cx="82"
cy="140"
cy="155"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.UPPER_WAIST]}
/>
<circle
className="body-part-circle"
cx="82"
cy="155"
cy="169"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.LOWER_WAIST]}
/>
@@ -0,0 +1,12 @@
export function LinkIcon({ size = 24 }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
height={size}
width={size}
>
<path d="M7.95,21q-2.05,0-3.5-1.45T3,16.05q0-1 0.38-1.9t1.08-1.6L7.8,9.23l1.4,1.4L5.85,13.98Q5.43,14.4 5.21,14.94T5,16.05q0,1.22 0.86,2.09T7.95,19q0.58,0 1.13-0.21t0.97-0.64l3.32-3.35l1.43,1.43l-3.35,3.32q-0.7,0.7-1.6,1.07T7.95,21Zm1.98-5.5L8.5,14.08L14.08,8.5L15.5,9.92L9.93,15.5Zm6.27-0.7l-1.4-1.42l3.35-3.33q0.42-0.42 0.63-0.95T18.98,8q0-1.25-0.85-2.13Q17.28,5 16.03,5q-0.58,0-1.11,0.21q-0.54,0.21-0.96,0.64L10.63,9.2L9.2,7.8l3.35-3.35q0.7-0.7 1.6-1.07T16.05,3q2.05,0 3.49,1.45t1.44,3.52q0,0.98-0.36,1.88t-1.06,1.6L16.2,14.8Z" />
</svg>
);
}
@@ -277,26 +277,8 @@ export function HeightSelectionInput({
};
const handleUnitChange = (newUnit: 'meter' | 'foot') => {
if (!headHeight || newUnit === unit) return;
if (newUnit === unit) return;
const fullHeight = headHeight / EYE_HEIGHT_TO_HEIGHT_RATIO;
let snappedHeight;
if (newUnit === 'foot') {
// Snap to nearest inch
const totalInches = Math.round(convert(fullHeight, 'meter').to('inch'));
snappedHeight = convert(totalInches, 'inch').to('meter');
} else {
// Snap to nearest centimeter
const totalCm = Math.round(convert(fullHeight, 'meter').to('cm'));
snappedHeight = convert(totalCm, 'cm').to('meter');
}
const newEyeHeight = round4Digit(
snappedHeight * EYE_HEIGHT_TO_HEIGHT_RATIO
);
setHeadHeight(newEyeHeight);
onUnitChange(newUnit);
};
@@ -3,9 +3,7 @@ import { A } from '@/components/commons/A';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
export const DOCS_TROUBLESHOOTING_URL =
'https://docs.slimevr.dev/common-issues.html';
import { DOCS_TROUBLESHOOTING_URL } from './TrackerList';
export function ErrorDetailModal({
isOpen,
@@ -3,6 +3,9 @@ import classNames from 'classnames';
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { useAtomValue } from 'jotai';
import {
BoardType,
DeviceOrigin,
TrackerStatus,
TrackerProvisioningStatus,
TrackingChecklistPublicNetworksT,
TrackingChecklistStepId,
@@ -16,8 +19,16 @@ import {
} from '@/hooks/wifi-form';
import { useTrackingChecklist } from '@/hooks/tracking-checklist';
import { useBreakpoint } from '@/hooks/breakpoint';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import {
connectedIMUTrackersAtom,
connectedTrackersAtom,
unknownDevicesAtom,
} from '@/store/app-store';
import { A } from '@/components/commons/A';
import {
BUTTERFLY_BOARDS,
SLIME_BOARDS,
} from '@/components/commons/BodyPartIcon';
import { Button } from '@/components/commons/Button';
import { Dropdown } from '@/components/commons/Dropdown';
import { Input } from '@/components/commons/Input';
@@ -32,11 +43,18 @@ import {
} from '@/components/commons/icon/ArrowIcons';
import { MoreSetsConfirm } from '@/components/onboarding/pages/quiz/MoreSetsConfirm';
import {
DOCS_TROUBLESHOOTING_URL,
MIDDLEWARE_DOCS_URL,
mergeTrackerList,
NoSerialLogsModal,
normalizeMac,
TrackerList,
DOCS_TROUBLESHOOTING_URL,
TrackerType,
} from './TrackerList';
import {
PendingTrackerCard,
PendingTrackersDivider,
} from '@/components/tracker/PendingTrackers';
export function FloatingWifiForm({
summary,
@@ -326,6 +344,16 @@ function WifiFormFields({
);
}
function MiddlewareLinks() {
return (
<div className="flex flex-col gap-2">
<ArrowLink to={MIDDLEWARE_DOCS_URL} direction="right" variant="boxed-2">
<Typography id="onboarding-connect_tracker-issue-middleware" />
</ArrowLink>
</div>
);
}
function TroubleshootingLinks({
networkProfileBanner,
}: {
@@ -348,13 +376,153 @@ function TroubleshootingLinks({
);
}
export function ConnectTrackersPage() {
export function ConnectTrackersPage({ type }: { type: TrackerType }) {
return type === 'middleware' ? (
<MiddlewareConnectTrackersPage />
) : (
<SlimeVRConnectTrackersPage />
);
}
function isMiddlewareBoard(boardType?: BoardType | null) {
return (
boardType == null ||
(!SLIME_BOARDS.has(boardType) && !BUTTERFLY_BOARDS.has(boardType))
);
}
function MiddlewareConnectTrackersPage() {
const { applyProgress, state } = useOnboarding();
const { isMobile } = useBreakpoint('mobile');
const connectedTrackers = useAtomValue(connectedTrackersAtom);
const activeTrackers = useMemo(
() =>
connectedTrackers.filter(
({ tracker }) => tracker.status !== TrackerStatus.TIMED_OUT
),
[connectedTrackers]
);
const unknownDevices = useAtomValue(unknownDevicesAtom);
const rows = useMemo(
() =>
mergeTrackerList(
[],
activeTrackers.filter(
({ tracker, device }) =>
tracker.origin === DeviceOrigin.DRIVER ||
(tracker.origin === DeviceOrigin.UDP &&
isMiddlewareBoard(device?.hardwareInfo?.officialBoardType))
)
),
[activeTrackers]
);
const pendingDevices = useMemo(() => {
const liveHardwareIds = new Set(
activeTrackers
.map(({ device }) =>
normalizeMac(device?.hardwareInfo?.hardwareIdentifier)
)
.filter((hardwareId): hardwareId is string => !!hardwareId)
);
return unknownDevices.filter((device) => {
const hardwareId = normalizeMac(device.hardwareId);
return (
isMiddlewareBoard(device.boardType) &&
hardwareId &&
!liveHardwareIds.has(hardwareId)
);
});
}, [activeTrackers, unknownDevices]);
applyProgress(0.4);
return (
<div className="w-full h-full flex flex-col xs:flex-row overflow-hidden min-h-0">
<div className="w-full xs:w-[340px] sm:w-[380px] lg:w-[400px] xl:w-[440px] p-5 mobile:pt-0 flex flex-col gap-4 shrink-0 overflow-y-auto border-b xs:border-b-0 xs:border-r border-background-60 justify-between">
<div className="flex flex-col gap-1">
<Typography
variant="mobile-title"
id="onboarding-connect_tracker-title"
/>
<Typography
variant="standard"
whitespace="whitespace-pre-wrap"
id="onboarding-connect_tracker-description-middleware"
/>
</div>
{!isMobile && (
<div className="flex flex-col gap-2">
<TipBox>
<Typography
variant="standard"
color="text-accent-background-10"
id="onboarding-connect_tracker-shake_tip"
/>
</TipBox>
<MiddlewareLinks />
</div>
)}
</div>
<div className="flex-1 flex flex-col gap-4 px-4 pt-4 min-h-0 overflow-hidden justify-between">
<TrackerList
rows={rows}
isMiddleware
hideEmptyState={pendingDevices.length > 0}
>
{pendingDevices.length > 0 && (
<div className="flex flex-col gap-3">
<PendingTrackersDivider devices={pendingDevices} />
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-4">
{pendingDevices.map((device) => (
<PendingTrackerCard
key={device.hardwareId as string}
device={device}
/>
))}
</div>
</div>
)}
{isMobile && (
<div className="pt-2 shrink-0">
<MiddlewareLinks />
</div>
)}
</TrackerList>
<div className="flex flex-row justify-between items-center shrink-0 py-4 border-t border-background-60">
<Button
variant="secondary"
state={{ alonePage: state.alonePage }}
to={
state.alonePage
? '/onboarding/add-trackers'
: '/onboarding/quiz/slime-set'
}
id="onboarding-wifi_creds-back-v2"
/>
{state.alonePage ? (
<Button
variant="primary"
to="/"
id="onboarding-connect_tracker-next"
/>
) : (
<MoreSetsConfirm />
)}
</div>
</div>
</div>
);
}
function SlimeVRConnectTrackersPage() {
const { l10n } = useLocalization();
const { visibleSteps, toggleSession } = useTrackingChecklist();
const { applyProgress, state } = useOnboarding();
const connectedIMUTrackers = useAtomValue(connectedIMUTrackersAtom);
const { isMobile } = useBreakpoint('mobile');
const credsForm = useWifiCredsForm();
const scan = useWifiScan();
const session = useWifiProvisioningSession(credsForm.control);
@@ -430,7 +598,9 @@ export function ConnectTrackersPage() {
id="tracking_checklist-NETWORK_PROFILE_PUBLIC-desc"
elems={{
PublicFixLink: (
<A href="https://docs.slimevr.dev/common-issues.html#network-profile-is-currently-set-to-public" />
<A
href={`${DOCS_TROUBLESHOOTING_URL}#network-profile-is-currently-set-to-public`}
/>
),
}}
vars={{
@@ -467,7 +637,7 @@ export function ConnectTrackersPage() {
return (
<>
<div className="w-full h-full flex flex-col xs:flex-row overflow-hidden min-h-0">
<div className="w-full xs:w-[340px] sm:w-[380px] lg:w-[400px] xl:w-[440px] p-5 flex flex-col gap-4 shrink-0 overflow-y-auto border-b xs:border-b-0 xs:border-r border-background-60 justify-between">
<div className="w-full xs:w-[340px] sm:w-[380px] lg:w-[400px] xl:w-[440px] p-5 mobile:pt-0 flex flex-col gap-4 shrink-0 overflow-y-auto border-b xs:border-b-0 xs:border-r border-background-60 justify-between">
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-1">
<Typography
@@ -499,7 +669,7 @@ export function ConnectTrackersPage() {
)}
</div>
<div className="flex-1 flex flex-col gap-4 px-4 pt-4 min-h-0 overflow-hidden justify-between mobile:pb-14">
<div className="flex-1 flex flex-col gap-4 px-4 pt-4 min-h-0 overflow-hidden justify-between mobile:pb-[76px]">
<div className="flex flex-col gap-4 min-h-0 flex-1">
<TrackerList
rows={rows}
@@ -24,6 +24,9 @@ import { TrackerWifi } from '@/components/tracker/TrackerWifi';
export const DOCS_TROUBLESHOOTING_URL =
'https://docs.slimevr.dev/common-issues.html';
export const MIDDLEWARE_DOCS_URL = 'https://docs.slimevr.dev/tools/index.html';
export type TrackerType = 'slimevr' | 'middleware';
export const trackerStatusLabelMap: Record<TrackerProvisioningStatus, string> =
{
@@ -401,9 +404,11 @@ export function NoSerialLogsModal({
export function StatusBar({
connectedCount,
connectingCount,
isMiddleware,
}: {
connectedCount: number;
connectingCount: number;
isMiddleware?: boolean;
}) {
return (
<div className="hidden sm:flex rounded-lg bg-background-60 p-4 items-center gap-3 shrink-0">
@@ -430,7 +435,7 @@ export function StatusBar({
id={
connectingCount > 0
? 'onboarding-connect_tracker-setting_up'
: 'onboarding-connect_tracker-all_caught_up'
: `onboarding-connect_tracker-all_caught_up${isMiddleware ? '-middleware' : ''}`
}
vars={{ amount: connectingCount }}
/>
@@ -443,20 +448,23 @@ function EmptyTrackerListIllustration({
scanStatus,
hasNetworks = false,
onOpenNoSerialLogsModal,
isMiddleware = false,
}: {
scanStatus: WifiScanStatus;
hasNetworks?: boolean;
onOpenNoSerialLogsModal?: () => void;
isMiddleware?: boolean;
}) {
const isError =
scanStatus === WifiScanStatus.CONNECTION_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND ||
scanStatus === WifiScanStatus.UNSUPPORTED;
!isMiddleware &&
(scanStatus === WifiScanStatus.CONNECTION_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND ||
scanStatus === WifiScanStatus.UNSUPPORTED);
const hasScanResults = scanStatus === WifiScanStatus.RESULTS || hasNetworks;
const titleId =
const slimevrTitleId =
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND
? 'onboarding-connect_tracker-connection_status-no_serial_device_found'
: scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR
@@ -468,8 +476,7 @@ function EmptyTrackerListIllustration({
: hasScanResults
? 'onboarding-connect_tracker-scan_results_title'
: 'onboarding-connect_tracker-waiting_first_title';
const descId =
const slimevrDescId =
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND
? 'onboarding-wifi_creds-scan_error_no_device'
: scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR
@@ -482,13 +489,17 @@ function EmptyTrackerListIllustration({
? 'onboarding-connect_tracker-scan_results_desc'
: 'onboarding-connect_tracker-waiting_first_desc';
const middlewareTitleId = 'onboarding-connect_tracker-waiting_first_title';
const middlewareDescId =
'onboarding-connect_tracker-waiting_first_desc-middleware';
return (
<EmptyState
className="flex-1 h-full min-h-[220px] !gap-3 my-auto"
slimeState={isError ? SlimeState.SAD : SlimeState.JUMPY}
titleColor={isError ? 'text-status-critical' : undefined}
titleId={titleId}
descriptionId={descId}
titleId={isMiddleware ? middlewareTitleId : slimevrTitleId}
descriptionId={isMiddleware ? middlewareDescId : slimevrDescId}
action={
isError && (
<button
@@ -558,8 +569,7 @@ export function mergeTrackerList(
for (const ct of connectedIMUTrackers) {
if (claimedConnected.has(ct)) continue;
const mac = normalizeMac(ct.device?.hardwareInfo?.hardwareIdentifier);
const key = mac || `connected-${ct.device?.id}`;
const key = `connected-${ct.tracker.trackerId}`;
rows.push({ kind: 'connected', key, tracker: ct });
}
@@ -568,16 +578,20 @@ export function mergeTrackerList(
export function TrackerList({
rows,
scanStatus,
networks,
scanStatus = WifiScanStatus.NONE,
networks = [],
onOpenNoSerialLogsModal,
children,
isMiddleware = false,
hideEmptyState = false,
}: {
rows: TrackerRow[];
scanStatus: WifiScanStatus;
networks: WifiNetworkT[];
onOpenNoSerialLogsModal: () => void;
children: ReactNode;
scanStatus?: WifiScanStatus;
networks?: WifiNetworkT[];
onOpenNoSerialLogsModal?: () => void;
children?: ReactNode;
isMiddleware?: boolean;
hideEmptyState?: boolean;
}) {
const { isMobile } = useBreakpoint('mobile');
const connectedCount = useMemo(
@@ -597,6 +611,7 @@ export function TrackerList({
<StatusBar
connectedCount={connectedCount}
connectingCount={connectingCount}
isMiddleware={isMiddleware}
/>
)}
@@ -623,13 +638,14 @@ export function TrackerList({
/>
)
)
) : (
) : !hideEmptyState ? (
<EmptyTrackerListIllustration
scanStatus={scanStatus}
hasNetworks={networks.length > 0}
onOpenNoSerialLogsModal={onOpenNoSerialLogsModal}
isMiddleware={isMiddleware}
/>
)}
) : null}
{children}
</div>
</div>
@@ -5,17 +5,21 @@ import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { useNavigate } from 'react-router-dom';
import { LinkIcon } from '@/components/commons/icon/LinkIcon';
import { useBreakpoint } from '@/hooks/breakpoint';
export function QuizButton({
name,
active,
icon,
onClick,
textVariant = 'section-title',
}: {
active?: boolean;
name: string;
icon: ReactNode;
onClick: () => void;
textVariant?: 'section-title' | 'standard';
}) {
return (
<Clickable
@@ -23,7 +27,7 @@ export function QuizButton({
pressed={active}
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',
'p-4 outline outline-2 flex-col gap-4 items-center justify-between fill-background-20 text-center',
{
'outline-accent-background-30': active,
'outline-transparent': !active,
@@ -31,12 +35,13 @@ export function QuizButton({
)}
>
{icon}
<Typography id={name} variant="section-title" />
<Typography id={name} variant={textVariant} bold />
</Clickable>
);
}
export function QuizSlimeSetQuestion() {
const { isMobile } = useBreakpoint('mobile');
const { applyProgress, setSlimeSet, slimeSet } = useOnboarding();
const nav = useNavigate();
@@ -49,6 +54,9 @@ export function QuizSlimeSetQuestion() {
case 'dongle-slime':
nav('/onboarding/dongle');
break;
case 'middleware':
nav('/onboarding/connect-middleware');
break;
case 'slime-v1':
case 'wifi-slime':
nav('/onboarding/connect-trackers');
@@ -103,7 +111,7 @@ export function QuizSlimeSetQuestion() {
variant="section-title"
id="onboarding-quiz-slimeset-thirdparty-sets"
/>
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,0.45fr)] mobile:grid-cols-3 gap-4">
<QuizButton
onClick={() => next('wifi-slime')}
icon={
@@ -129,6 +137,16 @@ export function QuizSlimeSetQuestion() {
}
name="onboarding-quiz-slimeset-answer-dongle"
/>
<QuizButton
onClick={() => next('middleware')}
textVariant={isMobile ? 'section-title' : 'standard'}
icon={
<div className="fill-background-20">
<LinkIcon size={isMobile ? 50 : 40} />
</div>
}
name="onboarding-quiz-slimeset-answer-middleware"
/>
</div>
</div>
</div>
@@ -174,7 +174,9 @@ export function AssignmentNavFooter({
? '/onboarding/connect-trackers'
: slimeSet && ['butterfly', 'dongle-slime'].includes(slimeSet)
? '/onboarding/dongle'
: '/onboarding/connect-trackers';
: slimeSet === 'middleware'
? '/onboarding/connect-middleware'
: '/onboarding/connect-trackers';
return (
<div className="flex flex-row justify-between items-center">
@@ -84,7 +84,6 @@ export function SettingsSidebar() {
<div className="flex flex-col gap-2">
<Typography variant="section-title" id="settings-sidebar-utils" />
<div className="flex flex-col gap-1">
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
<SettingsLink to="/settings/serial" id="settings-sidebar-serial" />
<SettingsLink to="/settings/logs" id="settings-sidebar-logs" />
<SettingsLink
@@ -101,6 +100,7 @@ export function SettingsSidebar() {
to="/settings/advanced"
id="settings-sidebar-advanced"
/>
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
</div>
</div>
</div>
@@ -22,7 +22,7 @@ import {
} from '@/components/settings/SettingRow';
import { FullResetIcon } from '@/components/commons/icon/ResetIcon';
import { settingReset } from '@/components/settings/SettingReset';
import { TapDetectionSettings } from './components/TapDetectionSettings';
import { TrackerActionSettings } from './components/TrackerActionSettings';
import { defineSettingsPage } from '@/components/settings/settings-definitions';
type ResetsSettingsForm = {
@@ -101,8 +101,8 @@ export const resetsSettingsPage = defineSettingsPage({
},
tapThreshold: {
rows: {
numberTrackersOverThreshold: {
title: 'settings-general-gesture_control-numberTrackersOverThreshold',
tapsTrackersOverThreshold: {
title: 'settings-general-gesture_control-tapsTrackersOverThreshold',
description:
'settings-general-gesture_control-numberTrackersOverThreshold-description',
},
@@ -250,7 +250,7 @@ export function ResetsSettings() {
</SettingRow>
</SettingsGroup>
<TapDetectionSettings
<TrackerActionSettings
resets={groups.tapResets}
threshold={groups.tapThreshold}
/>
@@ -267,7 +267,7 @@ export function ResetsSettings() {
name="yawResetSmoothTime"
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.0}
max={0.5}
max={1.0}
step={0.05}
/>
}
@@ -123,11 +123,14 @@ export function TrackersTableColumnsSettings({
}
const trackerDisplayToggleOrder: (keyof TrackerDisplayConfig)[] = [
'showBatteryRuntimeEstimate',
'showBatteryVoltage',
'showNumericSignal',
];
const trackerDisplayToggleLabel: Record<keyof TrackerDisplayConfig, string> = {
showBatteryRuntimeEstimate:
'settings-home-tracker_display-battery_runtime_estimate',
showBatteryVoltage: 'settings-home-tracker_display-battery_voltage',
showNumericSignal: 'settings-home-tracker_display-numeric_signal',
};
@@ -3,10 +3,12 @@ import { ReactNode, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import {
BodyPart,
ChangeTapDetectionSettingsRequestT,
ChangeTrackerActionSettingsRequestT,
RpcMessage,
TapDetectionSettingsRequestT,
TapDetectionSettingsResponseT,
TrackerActionMethod,
TrackerActionSettingsRequestT,
TrackerActionSettingsResponseT,
TrackerActionSettingsT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useSettingsDefaults } from '@/hooks/settings-defaults';
@@ -40,48 +42,64 @@ import {
SettingsGroupDef,
} from '@/components/settings/settings-definitions';
type TapDetectionForm = {
type TrackerActionForm = {
yawResetEnabled: boolean;
fullResetEnabled: boolean;
mountingResetEnabled: boolean;
yawResetDelay: number;
fullResetDelay: number;
mountingResetDelay: number;
yawResetBodyPart: string;
yawResetMethod: string;
yawResetTaps: number;
yawResetDelay: number;
fullResetEnabled: boolean;
fullResetBodyPart: string;
fullResetMethod: string;
fullResetTaps: number;
fullResetDelay: number;
mountingResetEnabled: boolean;
mountingResetBodyPart: string;
mountingResetMethod: string;
mountingResetTaps: number;
yawResetTracker: string;
fullResetTracker: string;
mountingResetTracker: string;
numberTrackersOverThreshold: number;
mountingResetDelay: number;
tapsTrackersOverThreshold: number;
};
// The server always sends every field, the fallbacks only satisfy the optional types
function toForm(settings: TapDetectionSettingsResponseT): TapDetectionForm {
function toForm(settings: TrackerActionSettingsResponseT): TrackerActionForm {
return {
yawResetEnabled: settings.yawResetEnabled ?? false,
fullResetEnabled: settings.fullResetEnabled ?? false,
mountingResetEnabled: settings.mountingResetEnabled ?? false,
yawResetDelay: settings.yawResetDelay ?? 0,
fullResetDelay: settings.fullResetDelay ?? 0,
mountingResetDelay: settings.mountingResetDelay ?? 0,
yawResetTaps: settings.yawResetTaps ?? 0,
fullResetTaps: settings.fullResetTaps ?? 0,
mountingResetTaps: settings.mountingResetTaps ?? 0,
yawResetTracker: String(settings.yawResetTracker ?? BodyPart.NONE),
fullResetTracker: String(settings.fullResetTracker ?? BodyPart.NONE),
mountingResetTracker: String(
settings.mountingResetTracker ?? BodyPart.NONE
yawResetEnabled: settings.yawResetAction?.enabled ?? false,
yawResetBodyPart: String(
settings.yawResetAction?.bodyPart ?? BodyPart.NONE
),
numberTrackersOverThreshold: settings.numberTrackersOverThreshold ?? 0,
yawResetMethod: String(
settings.yawResetAction?.method ?? TrackerActionMethod.TAP
),
yawResetTaps: settings.yawResetAction?.taps ?? 2,
yawResetDelay: settings.yawResetAction?.delay ?? 0,
fullResetEnabled: settings.fullResetAction?.enabled ?? false,
fullResetBodyPart: String(
settings.fullResetAction?.bodyPart ?? BodyPart.NONE
),
fullResetMethod: String(
settings.fullResetAction?.method ?? TrackerActionMethod.TAP
),
fullResetTaps: settings.fullResetAction?.taps ?? 2,
fullResetDelay: settings.fullResetAction?.delay ?? 0,
mountingResetEnabled: settings.mountingResetAction?.enabled ?? false,
mountingResetBodyPart: String(
settings.mountingResetAction?.bodyPart ?? BodyPart.NONE
),
mountingResetMethod: String(
settings.mountingResetAction?.method ?? TrackerActionMethod.TAP
),
mountingResetTaps: settings.mountingResetAction?.taps ?? 2,
mountingResetDelay: settings.mountingResetAction?.delay ?? 0,
tapsTrackersOverThreshold: settings.tapsTrackersOverThreshold ?? 0,
};
}
const tapDetectionSettingsAtom = atom<TapDetectionSettingsResponseT | null>(
const trackerActionSettingsAtom = atom<TrackerActionSettingsResponseT | null>(
null
);
const tapDetectionSettingsValueAtom = selectAtom(
tapDetectionSettingsAtom,
const trackerActionSettingsValueAtom = selectAtom(
trackerActionSettingsAtom,
(settings) => settings,
isEqual
);
@@ -111,19 +129,19 @@ function FocusableRow({
);
}
export function TapDetectionSettings({
export function TrackerActionSettings({
resets,
threshold,
}: {
resets: SettingsGroupDef<'yawReset' | 'fullReset' | 'mountingReset'>;
threshold: SettingsGroupDef<'numberTrackersOverThreshold'>;
threshold: SettingsGroupDef<'tapsTrackersOverThreshold'>;
}) {
const setSettings = useSetAtom(tapDetectionSettingsAtom);
const settings = useAtomValue(tapDetectionSettingsValueAtom);
const setSettings = useSetAtom(trackerActionSettingsAtom);
const settings = useAtomValue(trackerActionSettingsValueAtom);
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
const defaults = useSettingsDefaults().tapDetection;
const defaults = useSettingsDefaults().trackerAction;
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
@@ -140,31 +158,49 @@ export function TapDetectionSettings({
label: l10n.getString(`body_part-${BodyPart[value]}`),
}));
const TrackerActionMethods: { value: string; label: string }[] =
Object.values(TrackerActionMethod)
.filter((v): v is TrackerActionMethod => typeof v === 'number')
.map((value) => ({
value: String(value),
label: l10n.getString(
`settings-general-gesture_control-${TrackerActionMethod[value]}`
),
}));
const { control, watch, handleSubmit, reset, setValue } =
useForm<TapDetectionForm>({
useForm<TrackerActionForm>({
defaultValues: toForm(defaults),
mode: 'onChange',
reValidateMode: 'onChange',
});
const onSubmit = (values: TapDetectionForm) => {
const settingsReq = new ChangeTapDetectionSettingsRequestT();
settingsReq.fullResetDelay = values.fullResetDelay;
settingsReq.fullResetEnabled = values.fullResetEnabled;
settingsReq.fullResetTaps = values.fullResetTaps;
settingsReq.yawResetDelay = values.yawResetDelay;
settingsReq.yawResetEnabled = values.yawResetEnabled;
settingsReq.yawResetTaps = values.yawResetTaps;
settingsReq.yawResetTracker = Number(values.yawResetTracker);
settingsReq.mountingResetTracker = Number(values.mountingResetTracker);
settingsReq.fullResetTracker = Number(values.fullResetTracker);
settingsReq.mountingResetEnabled = values.mountingResetEnabled;
settingsReq.mountingResetDelay = values.mountingResetDelay;
settingsReq.mountingResetTaps = values.mountingResetTaps;
settingsReq.numberTrackersOverThreshold =
values.numberTrackersOverThreshold;
const onSubmit = (values: TrackerActionForm) => {
const settingsReq = new ChangeTrackerActionSettingsRequestT();
settingsReq.yawResetAction = new TrackerActionSettingsT(
values.yawResetEnabled,
values.yawResetDelay,
Number(values.yawResetBodyPart),
Number(values.yawResetMethod),
values.yawResetTaps
);
settingsReq.fullResetAction = new TrackerActionSettingsT(
values.fullResetEnabled,
values.fullResetDelay,
Number(values.fullResetBodyPart),
Number(values.fullResetMethod),
values.fullResetTaps
);
settingsReq.mountingResetAction = new TrackerActionSettingsT(
values.mountingResetEnabled,
values.mountingResetDelay,
Number(values.mountingResetBodyPart),
Number(values.mountingResetMethod),
values.mountingResetTaps
);
settingsReq.tapsTrackersOverThreshold = values.tapsTrackersOverThreshold;
sendRPCPacket(RpcMessage.ChangeTapDetectionSettingsRequest, settingsReq);
sendRPCPacket(RpcMessage.ChangeTrackerActionSettingsRequest, settingsReq);
};
useEffect(() => {
@@ -176,8 +212,8 @@ export function TapDetectionSettings({
useConnectedEffect(() => {
sendRPCPacket(
RpcMessage.TapDetectionSettingsRequest,
new TapDetectionSettingsRequestT()
RpcMessage.TrackerActionSettingsRequest,
new TrackerActionSettingsRequestT()
);
}, []);
@@ -187,27 +223,33 @@ export function TapDetectionSettings({
}, [settings]);
useRPCPacket(
RpcMessage.TapDetectionSettingsResponse,
(settings: TapDetectionSettingsResponseT) => {
RpcMessage.TrackerActionSettingsResponse,
(settings: TrackerActionSettingsResponseT) => {
setSettings(settings);
}
);
const resetThreshold = settingReset<
TapDetectionForm,
'numberTrackersOverThreshold'
TrackerActionForm,
'tapsTrackersOverThreshold'
>(
defaults.numberTrackersOverThreshold ?? undefined,
watch('numberTrackersOverThreshold'),
defaults.tapsTrackersOverThreshold ?? undefined,
watch('tapsTrackersOverThreshold'),
(next) => {
setValue('numberTrackersOverThreshold', next);
setValue('tapsTrackersOverThreshold', next);
handleSubmit(onSubmit)();
}
);
const defaultForm = toForm(defaults);
const resetKindFields = (id: (typeof resetKinds)[number]['id']) =>
[`${id}Enabled`, `${id}Tracker`, `${id}Taps`, `${id}Delay`] as const;
[
`${id}Enabled`,
`${id}BodyPart`,
`${id}Method`,
`${id}Taps`,
`${id}Delay`,
] as const;
const kindReset = (id: (typeof resetKinds)[number]['id']) => {
const fields = resetKindFields(id);
return {
@@ -224,16 +266,19 @@ export function TapDetectionSettings({
id: 'yawReset',
enabled: watch('yawResetEnabled'),
icon: <YawResetIcon width={20} />,
method: watch('yawResetMethod'),
},
{
id: 'fullReset',
enabled: watch('fullResetEnabled'),
icon: <FullResetIcon width={20} />,
method: watch('fullResetMethod'),
},
{
id: 'mountingReset',
enabled: watch('mountingResetEnabled'),
icon: <MountingResetIcon width={20} />,
method: watch('mountingResetMethod'),
},
] as const;
@@ -245,7 +290,7 @@ export function TapDetectionSettings({
);
const mobileCaption = (id: string) => (
<div className="md:hidden">
<div className="lg:hidden">
<Typography bold id={`settings-general-gesture_control-column-${id}`} />
</div>
);
@@ -259,27 +304,28 @@ export function TapDetectionSettings({
<Typography id="settings-general-gesture_control-description" />
</div>
<div className="rounded-2xl bg-background-80 overflow-hidden">
<table className="w-full text-left border-collapse block md:table">
<thead className="hidden md:table-header-group">
<table className="w-full text-left border-collapse block lg:table">
<thead className="hidden lg:table-header-group">
<tr className="border-b border-background-60 uppercase">
<th className="py-3 pl-4 pr-2 w-0" />
<th className="py-3 pr-4 w-64 whitespace-nowrap">
{column('reset')}
{column('action')}
</th>
<th className="py-3 px-4">{column('tracker')}</th>
<th className="py-3 px-4">{column('method')}</th>
<th className="py-3 px-4 w-56">{column('taps')}</th>
<th className="py-3 pl-4 pr-4 w-56">{column('delay')}</th>
</tr>
</thead>
<tbody className="divide-y divide-background-60 block md:table-row-group">
{resetKinds.map(({ id, enabled, icon }) => (
<tbody className="divide-y divide-background-60 block lg:table-row-group">
{resetKinds.map(({ id, enabled, icon, method }) => (
<FocusableRow
key={id}
setting={resets.rows[id]}
className="grid grid-cols-[1.75rem_minmax(0,1fr)_minmax(0,1fr)] md:table-row gap-x-2 gap-y-3 md:gap-0 items-center pl-1 pr-3 py-3 xs:pl-2 xs:pr-4 xs:py-4 md:p-0"
className="grid grid-cols-[1.75rem_minmax(0,1fr)_minmax(0,1fr)] lg:table-row gap-x-2 gap-y-3 lg:gap-0 items-center pl-1 pr-3 py-3 xs:pl-2 xs:pr-4 xs:py-4 lg:p-0"
>
<td className="contents md:table-cell md:py-3 md:pl-4 md:pr-2 align-middle">
<div className="contents md:flex md:items-center md:gap-2">
<td className="contents lg:table-cell lg:py-3 lg:pl-4 lg:pr-2 align-middle">
<div className="contents lg:flex lg:items-center lg:gap-2">
<div className="col-start-1 row-start-1 flex justify-center">
<SettingResetButton {...kindReset(id)} />
</div>
@@ -293,7 +339,7 @@ export function TapDetectionSettings({
</div>
</div>
</td>
<td className="col-start-2 col-span-2 row-start-1 min-w-0 pr-12 block md:table-cell md:py-3 md:pr-4 align-middle">
<td className="col-start-2 col-span-2 row-start-1 min-w-0 pr-12 block lg:table-cell lg:py-3 lg:pr-2 align-middle">
<label
htmlFor={`tap-${id}`}
className="flex items-center gap-2.5 cursor-pointer whitespace-nowrap"
@@ -308,7 +354,7 @@ export function TapDetectionSettings({
/>
</label>
</td>
<td className="col-start-2 col-span-2 row-start-2 block md:table-cell md:py-3 md:px-4 align-middle">
<td className="col-start-2 col-span-2 row-start-2 smol:col-start-2 smol:col-span-1 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={!enabled}
className={classNames(
@@ -321,23 +367,45 @@ export function TapDetectionSettings({
display="block"
control={control}
placeholder={''}
name={`${id}Tracker` as keyof TapDetectionForm}
name={`${id}BodyPart` as keyof TrackerActionForm}
items={bodyParts}
/>
</fieldset>
</td>
<td className="col-start-2 col-span-2 row-start-3 smol:col-start-2 smol:col-span-1 min-w-0 block md:table-cell md:py-3 md:px-4 align-middle">
<td className="col-start-2 col-span-2 row-start-2 smol:col-start-3 smol:col-span-1 smol:row-start-2 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={!enabled}
className={classNames(
'flex flex-col gap-1.5',
!enabled && 'opacity-50'
)}
>
{mobileCaption('method')}
<Dropdown
display="block"
control={control}
placeholder={''}
name={`${id}Method` as keyof TrackerActionForm}
items={TrackerActionMethods}
/>
</fieldset>
</td>
<td className="col-start-2 col-span-2 row-start-3 smol:col-start-2 smol:col-span-1 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={
!enabled || Number(method) == TrackerActionMethod.BUTTON
}
className={classNames(
'flex flex-col gap-1.5',
(!enabled ||
Number(method) == TrackerActionMethod.BUTTON) &&
'opacity-50'
)}
>
{mobileCaption('taps')}
<NumberSelector
control={control}
name={`${id}Taps` as keyof TapDetectionForm}
name={`${id}Taps` as keyof TrackerActionForm}
valueLabelFormat={(value) =>
l10n.getString(
'settings-general-gesture_control-taps',
@@ -350,7 +418,7 @@ export function TapDetectionSettings({
/>
</fieldset>
</td>
<td className="col-start-2 col-span-2 row-start-4 smol:col-start-3 smol:col-span-1 smol:row-start-3 min-w-0 block md:table-cell md:py-3 md:px-4 align-middle">
<td className="col-start-2 col-span-2 row-start-3 smol:col-start-3 smol:col-span-1 smol:row-start-3 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={!enabled}
className={classNames(
@@ -361,7 +429,7 @@ export function TapDetectionSettings({
{mobileCaption('delay')}
<NumberSelector
control={control}
name={`${id}Delay` as keyof TapDetectionForm}
name={`${id}Delay` as keyof TrackerActionForm}
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.2}
max={3.0}
@@ -377,13 +445,13 @@ export function TapDetectionSettings({
<SettingsGroup group={threshold}>
<SettingRow
setting={threshold.rows.numberTrackersOverThreshold}
setting={threshold.rows.tapsTrackersOverThreshold}
controlWidth="wide"
{...resetThreshold}
control={
<NumberSelector
control={control}
name="numberTrackersOverThreshold"
name="tapsTrackersOverThreshold"
valueLabelFormat={(value) =>
l10n.getString('settings-general-gesture_control-trackers', {
amount: Math.round(value),
@@ -33,14 +33,17 @@ export function TrackerBattery({
});
const charging = (voltage || 0) > 4.3;
const debug = config?.debug;
const showRuntime =
config?.trackerDisplay?.showBatteryRuntimeEstimate &&
runtime != null &&
runtime > 0;
const showVoltage = voltage && config?.trackerDisplay?.showBatteryVoltage;
const pct = value > 2 ? 0 : Math.min(Math.max(value, 0), 1);
return (
<Tooltip
disabled={charging || !runtime || debug}
disabled={charging || !showRuntime}
preferedDirection="left"
content={<Typography>{percentFormatter.format(pct)}</Typography>}
>
@@ -50,7 +53,7 @@ export function TrackerBattery({
</div>
{((!charging || showVoltage) && (
<div className="w-15">
{!charging && runtime != null && runtime > 0 && (
{!charging && showRuntime && (
<Typography color={textColor}>
{(runtime / BigInt(3600000000)).toString() +
'h ' +
@@ -61,7 +64,7 @@ export function TrackerBattery({
'min'}
</Typography>
)}
{!charging && (!runtime || debug) && (
{!charging && !showRuntime && (
<Typography color={textColor}>
{percentFormatter.format(pct)}
</Typography>
@@ -14,7 +14,6 @@ import {
MagnetometerStatus,
MountingMethod,
RpcMessage,
TrackerDataType,
} from 'solarxr-protocol';
import { useDebouncedEffect } from '@/hooks/timeout';
import { useTrackerFromId } from '@/hooks/tracker';
@@ -362,14 +361,6 @@ export function TrackerSettingsPage() {
<Typography id="tracker-infos-mac_address" />
<Typography>{macAddress || '--'}</Typography>
</div>
<div className="flex justify-between">
<Typography>
{l10n.getString('tracker-infos-data_type')}
</Typography>
<Typography>
{TrackerDataType[tracker?.tracker.info?.dataType ?? 0]}
</Typography>
</div>
<div className="flex justify-between">
<Typography>{l10n.getString('tracker-infos-imu')}</Typography>
<Typography>
@@ -48,6 +48,7 @@ import { NavLink, useNavigate } from 'react-router-dom';
import { useBreakpoint } from '@/hooks/breakpoint';
import { openUrl } from '@/hooks/crossplatform';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { DOCS_TROUBLESHOOTING_URL } from '@/components/onboarding/pages/connect-trackers/TrackerList';
function Step({
step: { status, id, optional, firstRequired },
@@ -345,7 +346,7 @@ const stepContentLookup: Record<
PublicFixLink: (
<A
className="text-background-20"
href="https://docs.slimevr.dev/common-issues.html#network-profile-is-currently-set-to-public"
href={`${DOCS_TROUBLESHOOTING_URL}#network-profile-is-currently-set-to-public`}
/>
),
}}
+2
View File
@@ -69,11 +69,13 @@ export const trackersTableColumnOrder = [
export type TrackersTableOptionalColumn = (typeof trackersTableColumnOrder)[number];
export interface TrackerDisplayConfig {
showBatteryRuntimeEstimate: boolean;
showBatteryVoltage: boolean;
showNumericSignal: boolean;
}
export const defaultTrackerDisplay: TrackerDisplayConfig = {
showBatteryRuntimeEstimate: true,
showBatteryVoltage: false,
showNumericSignal: false,
};
+1 -1
View File
@@ -59,7 +59,7 @@ export type OnboardingContext = ReturnType<typeof useProvideOnboarding>;
export function useProvideOnboarding() {
const { setConfig } = useConfig();
const [slimeSet, setSlimeSet] = useState<
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime'
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime' | 'middleware'
>();
const [usage, setUsage] = useState<'vr-gaming' | 'mocap' | 'vtubing'>();
const [vrcOsc, setVrcOSC] = useState<boolean>();
+8 -8
View File
@@ -5,8 +5,8 @@ import {
QuatT,
ResetTrackerAssignmentsT,
RpcMessage,
TapDetectionSetupModeRequestT,
TapDetectionSetupNotificationT,
TrackerActionSetupModeRequestT,
TrackerActionSetupNotificationT,
} from 'solarxr-protocol';
import { useChokerWarning } from './choker-warning';
import { useWebsocketAPI } from './websocket-api';
@@ -59,14 +59,14 @@ export function useTrackerAssignment(mode: AssignmentMode) {
useConnectedEffect(() => {
sendRPCPacket(
RpcMessage.TapDetectionSetupModeRequest,
new TapDetectionSetupModeRequestT(true)
RpcMessage.TrackerActionSetupModeRequest,
new TrackerActionSetupModeRequestT(true)
);
return () => {
sendRPCPacket(
RpcMessage.TapDetectionSetupModeRequest,
new TapDetectionSetupModeRequestT(false)
RpcMessage.TrackerActionSetupModeRequest,
new TrackerActionSetupModeRequestT(false)
);
};
}, []);
@@ -150,8 +150,8 @@ export function useTrackerAssignment(mode: AssignmentMode) {
};
useRPCPacket(
RpcMessage.TapDetectionSetupNotification,
(tapSetup: TapDetectionSetupNotificationT) => {
RpcMessage.TrackerActionSetupNotification,
(tapSetup: TrackerActionSetupNotificationT) => {
if (armedPart === BodyPart.NONE || !tapSetup.trackerId) return;
handleDropTracker(tapSetup.trackerId, armedPart);
playTapSetupSound(config?.feedbackSoundVolume);
+7 -7
View File
@@ -75,7 +75,7 @@ const ASSIGNABLE_PARTS = new Set(ALL_ASSIGNABLE_PARTS);
type SetupRegionName =
| 'legs'
| 'chest'
| 'upperChest'
| 'hip'
| 'feet'
| 'upperArms'
@@ -96,12 +96,12 @@ const SETUP_REGIONS: {
needs: SetupRegionName[];
}[] = [
{ id: 'legs', parts: [...LEGS_PARTS], needs: [] },
{ id: 'chest', parts: [BodyPart.UPPER_CHEST], needs: [] },
{ id: 'hip', parts: [BodyPart.HIP], needs: ['chest'] },
{ id: 'upperChest', parts: [BodyPart.UPPER_CHEST], needs: [] },
{ id: 'hip', parts: [BodyPart.HIP], needs: ['upperChest'] },
// one spine point at a time, each halving the largest remaining gap
{ id: 'lowerWaist', parts: [BodyPart.LOWER_WAIST], needs: ['hip'] },
{ id: 'lowerChest', parts: [BodyPart.LOWER_CHEST], needs: ['lowerWaist'] },
{ id: 'upperWaist', parts: [BodyPart.UPPER_WAIST], needs: ['lowerChest'] },
{ id: 'upperWaist', parts: [BodyPart.UPPER_WAIST], needs: ['hip'] },
{ id: 'lowerChest', parts: [BodyPart.LOWER_CHEST], needs: ['upperWaist'] },
{ id: 'lowerWaist', parts: [BodyPart.LOWER_WAIST], needs: ['lowerChest'] },
{
id: 'feet',
parts: [BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT],
@@ -110,7 +110,7 @@ const SETUP_REGIONS: {
{
id: 'upperArms',
parts: [BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM],
needs: ['legs', 'chest'],
needs: ['legs', 'upperChest'],
},
{
id: 'lowerArms',
+17 -31
View File
@@ -16,7 +16,6 @@ import {
ResetsSettingsResponseT,
SkeletonSettingsResponseT,
StayAlignedSettingsResponseT,
TapDetectionSettingsResponseT,
TimeoutSettingsResponseT,
TrackerDataT,
TrackerStatus,
@@ -24,6 +23,7 @@ import {
VMCOSCSettingsResponseT,
VRCOSCSettingsResponseT,
VRMSettingsResponseT,
TrackerActionSettingsResponseT,
} from 'solarxr-protocol';
import { selectAtom } from 'jotai/utils';
import { isEqual } from '@react-hookz/deep-equal';
@@ -48,7 +48,7 @@ export type SettingsDefaults = {
skeleton: SkeletonSettingsResponseT;
resets: ResetsSettingsResponseT;
stayAligned: StayAlignedSettingsResponseT;
tapDetection: TapDetectionSettingsResponseT;
trackerAction: TrackerActionSettingsResponseT;
timeout: TimeoutSettingsResponseT;
hid: HIDSettingsResponseT;
driver: DriverSettingsResponseT;
@@ -233,39 +233,25 @@ export function groupTrackersByDevice(
return order.map((key) => byDevice.get(key)!);
}
const PRESENT_STATUSES = new Set([
TrackerStatus.OK,
TrackerStatus.SLEEPING,
TrackerStatus.TIMED_OUT,
TrackerStatus.OCCLUDED,
]);
function isPresent(status: TrackerStatus) {
return PRESENT_STATUSES.has(status);
}
export function groupTrackerByBodyPart(
trackers: FlatDeviceTracker[]
): Partial<Record<BodyPart, FlatDeviceTracker>> {
const byPart: Partial<Record<BodyPart, FlatDeviceTracker>> = {};
trackers
.toSorted((a, b) => {
if (
a.tracker.info &&
b.tracker.info &&
a.tracker.info.bodyPart == b.tracker.info.bodyPart
) {
// Make sure the active tracker is further in the array, so that it takes precedence in the byPart record.
// This shouldn't happen if the body parts are equal, but handle it just in case.
if (a.tracker.status == b.tracker.status) return 0;
if (
a.tracker.status !== TrackerStatus.OK &&
a.tracker.status !== TrackerStatus.SLEEPING &&
a.tracker.status !== TrackerStatus.TIMED_OUT
) {
// put a before b
return -1;
} else {
// put b before a
return 1;
}
}
return a.tracker.trackerId - b.tracker.trackerId;
})
.forEach((td) => {
byPart[td.tracker.info?.bodyPart ?? BodyPart.NONE] = td;
});
trackers.forEach((td) => {
const part = td.tracker.info?.bodyPart ?? BodyPart.NONE;
if (!byPart[part] || isPresent(td.tracker.status)) byPart[part] = td;
});
return byPart;
}
+13 -8
View File
@@ -197,13 +197,13 @@ const fingerRight = (file: string) =>
// shows. The length ratio keeps the tip on the bone's tail despite the tuck.
const TOE_TUCK = 0.5;
const toeScale = (width: number, depth: number) =>
spanBone({ width, depth, length: 1 + TOE_TUCK, girthFrom: 'foot' });
const toeOffset = inBoneLengths({ length: TOE_TUCK, depth: 0.11 });
const toe = (file: string, scale = toeScale(1.3, 1.0)) =>
spanBone({ width, depth, length: 1 + TOE_TUCK, girthFrom: 'height' });
const toeOffset = inBoneLengths({ length: TOE_TUCK, depth: -0.02 });
const toe = (file: string, scale = toeScale(1, 1.0)) =>
part(model(file, { scale, offset: toeOffset }));
const toeRight = (file: string, scale = toeScale(1.3, 1.0)) =>
const toeRight = (file: string, scale = toeScale(1, 1.0)) =>
part(model(file, { scale: otherSide(scale), offset: toeOffset }));
const bigToeScale = toeScale(1.3, 1.15);
const bigToeScale = toeScale(1, 1.1);
const HEAD_SIZE_EXPONENT = 0.25;
const headSize = ({ bodyScale }: SkeletonProportions) =>
@@ -245,9 +245,14 @@ const lowerArmScale = spanBone({
const upperLegScale = spanBone({ girthFrom: 'hips', length: 1.0 });
const lowerLegScale = spanBone({ girthFrom: 'hips', length: 0.78 });
const footScale: ShapeScale = {
compute: ({ boneLength }) => {
const ratio = boneLength / RIG_FOOT_LENGTH;
return { width: 0.91 * ratio, length: 1.12 * ratio, depth: 1.195 };
compute: ({ boneLength, proportions }) => {
const heightRatio = proportions.bodyScale;
const footRatio = boneLength / RIG_FOOT_LENGTH;
return {
width: 0.91 * footRatio,
length: 1.12 * footRatio,
depth: 1.1 * heightRatio,
};
},
};
// Forward follows foot length; the drop from the ankle to the sole doesn't.
+35 -2
View File
@@ -1,5 +1,5 @@
import { BrowserWindow } from 'electron';
import { isAppUrl, openExternalUrl } from './urls';
import { BrowserWindow, session } from 'electron';
import { getAppUrl, isAppUrl, openExternalUrl } from './urls';
import { IPC_CHANNELS } from '@slimevr/gui-shared';
const SESSION_SET_URL = /^https:\/\/[\w-]+\.crowdin\.com\/backend\/jwt\/set\b/;
@@ -27,6 +27,39 @@ const HIDE_WAIT_JS = `document.querySelectorAll('.slimevr-crowdin-wait').forEach
let crowdinPopup: BrowserWindow | null = null;
const FAKE_ORIGIN = 'http://localhost';
const JIPT_API = /^https:\/\/[\w-]+\.crowdin\.com\/api\/v2\/jipt\//;
// The jipt API rejects any non-http(s) origin with "Invalid origin", and the
// prod build runs on app://. we make it sees http://localhost instead
export function rewriteCrowdinOrigin() {
const appUrl = new URL(getAppUrl());
const appOrigin = `${appUrl.protocol}//${appUrl.host}`;
if (appOrigin.startsWith('http')) return;
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['https://*.crowdin.com/*'] },
(details, callback) => {
const url = new URL(details.url);
if (details.resourceType === 'subFrame') {
callback(replaceParam(url, 'jipt', FAKE_ORIGIN, appOrigin));
return;
}
if (JIPT_API.test(details.url)) {
callback(replaceParam(url, 'origin', appOrigin, FAKE_ORIGIN));
return;
}
callback({});
}
);
}
function replaceParam(url: URL, param: string, from: string, to: string) {
if (url.searchParams.get(param) !== from) return {};
url.searchParams.set(param, to);
return { redirectURL: url.toString() };
}
export function openCrowdinPopup(parent: BrowserWindow, url: string) {
if (crowdinPopup) {
crowdinPopup.loadURL(url);
+3 -1
View File
@@ -37,7 +37,7 @@ import { discordPresence } from './presence';
import { options } from './cli';
import { mkdir, writeFile } from 'node:fs/promises';
import { MenuItem } from 'electron/main';
import { openCrowdinPopup } from './crowdin';
import { openCrowdinPopup, rewriteCrowdinOrigin } from './crowdin';
import {
applyErrorReporting,
captureJavaNotFound,
@@ -603,6 +603,8 @@ app.whenReady().then(async () => {
return new Response(response.body, { status: response.status, headers });
});
rewriteCrowdinOrigin();
try {
await createFolders();
} catch (err) {
+12 -5
View File
@@ -178,7 +178,8 @@ export function captureServerExit(
const eventId = Sentry.captureMessage('server_exit_nonzero', {
...serverScope,
level: 'error',
extra: { code, signal, outputTail },
tags: { code, signal },
extra: { outputTail },
});
lastServerFailure = { eventId, code, signal, outputTail };
}
@@ -192,10 +193,16 @@ export function sendCrashReport(kind: CrashReportKind) {
event_id: failure?.eventId,
message: failure ? 'server_exit_nonzero' : `server_${kind}`,
level: 'error',
tags: serverScope.tags,
extra: failure
? { code: failure.code, signal: failure.signal, outputTail: failure.outputTail }
: { outputTail: serverOutputTail() },
tags: failure
? {
...serverScope.tags,
code: failure.code,
signal: failure.signal,
}
: serverScope.tags,
extra: {
outputTail: failure?.outputTail ?? serverOutputTail(),
},
});
});
return true;
@@ -47,7 +47,7 @@ import dev.slimevr.sentry.registerErrorReportSnapshots
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpServer
import dev.slimevr.util.appCoroutineExceptionHandler
@@ -191,7 +191,7 @@ class ForegroundService : Service() {
)
val stepMountingManager = StepMountingManager.create(ctx = phase1, scope = scope)
val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, vrcOscManager = vrcOscManager, stepMountingManager = stepMountingManager, scope = scope)
val tapDetectionManager = TapDetectionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope)
val trackerActionManager = TrackerActionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope)
val keybindManager = KeybindManager.create(scope = scope)
val serverInfos = ServerInfos(::resolveAndroidLocalIpAddress)
@@ -221,7 +221,7 @@ class ForegroundService : Service() {
vmcManager = vmcManager,
vrcOscManager = vrcOscManager,
resetsManager = resetsManager,
tapDetectionManager = tapDetectionManager,
trackerActionManager = trackerActionManager,
stepMountingManager = stepMountingManager,
logSources = listOf(serverLogSource),
)
+1
View File
@@ -52,6 +52,7 @@ kotlin {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
implementation("it.krzeminski:snakeyaml-engine-kmp:3.2.1")
}
}
val commonTest = getByName("commonTest") {
@@ -15,7 +15,7 @@ import dev.slimevr.serial.SerialServer
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpServer
import dev.slimevr.vmc.VMCManager
@@ -53,7 +53,7 @@ interface AppContextProvider : Phase1ContextProvider {
val vmcManager: VMCManager
val vrcOscManager: VRCOSCManager
val resetsManager: ResetsManager
val tapDetectionManager: TapDetectionManager
val trackerActionManager: TrackerActionManager
val stepMountingManager: StepMountingManager
val logSources: List<LogSourceProvider>
fun startObserving()
@@ -81,7 +81,7 @@ class AppContext(
override val vmcManager: VMCManager,
override val vrcOscManager: VRCOSCManager,
override val resetsManager: ResetsManager,
override val tapDetectionManager: TapDetectionManager,
override val trackerActionManager: TrackerActionManager,
override val stepMountingManager: StepMountingManager,
override val logSources: List<LogSourceProvider>,
) : AppContextProvider {
@@ -99,7 +99,7 @@ class AppContext(
vmcManager.startObserving(this)
vrcOscManager.startObserving(this)
resetsManager.startObserving()
tapDetectionManager.startObserving()
trackerActionManager.startObserving()
stepMountingManager.startObserving()
}
@@ -0,0 +1,29 @@
package dev.slimevr.autobone
class WeightedAverage {
var value: Float = 0f
private set
var weight: Float = 0f
private set
fun average() = if (weight > 0f) {
value / weight
} else {
0f
}
fun addValue(value: Float, weight: Float) {
this.value += value * weight
this.weight += weight
}
fun subtractValue(value: Float, weight: Float) {
this.value -= value * weight
this.weight -= weight
}
fun reset() {
value = 0f
weight = 0f
}
}
@@ -0,0 +1,106 @@
package dev.slimevr.autobone
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.bodyPartMap
import dev.slimevr.skeleton.mapValues
import dev.slimevr.util.Side
import dev.slimevr.util.side
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
val BODY_PARTS_TO_ADJUST = arrayOf(
BodyPart.NECK,
BodyPart.UPPER_CHEST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
BodyPart.LEFT_UPPER_LEG,
BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_UPPER_LEG,
BodyPart.RIGHT_LOWER_LEG,
)
// TODO This should probably be every bone excluding arms, feet, and toes?
val CONTRIBUTING_BODY_PARTS = BODY_PARTS_TO_ADJUST.plus(
arrayOf(
BodyPart.HEAD,
),
)
data class TrackerFrame(
val rotation: Quaternion,
val position: Vector3?,
)
typealias AutoBoneRecording = List<TrackerFrame>
// TODO Figure out actually doing the recording
typealias BoneContribution = WeightedAverage
typealias BoneContributions = BodyPartMap<BoneContribution>
fun process(recording: BodyPartMap<AutoBoneRecording>) {
// TODO Actually make skeletons
val skeletonA: ComputedSkeleton = bodyPartMap()
val skeletonB: ComputedSkeleton = bodyPartMap()
val contributions: BoneContributions = bodyPartMap()
val recordingLength = recording.minOf { it.value.size }
for (i in 0 until recordingLength) {
val trackers = recording.mapValues { _, frames -> frames[i] }
// TODO Apply trackers to skeletons A and B somehow
computeContributions(contributions, skeletonA, skeletonB)
// TODO Figure out how to choose adjustment scale
// TODO Test new config to see if it actually reduces error
}
}
fun boneContribution(contribution: BoneContribution, ankleAToB: Vector3, localBoneTailAToB: Vector3) {
val boneToSlideDirectionRatio = ankleAToB.unit().dot(localBoneTailAToB.unit())
// - if bone is too short, + if bone is too long
contribution.addValue(boneToSlideDirectionRatio, localBoneTailAToB.len())
}
fun computeContributions(contributions: BoneContributions, skeletonA: ComputedSkeleton, skeletonB: ComputedSkeleton) {
val leftAnkleA = skeletonA[BodyPart.LEFT_LOWER_LEG]?.tailPosition ?: error("Missing left ankle position A")
val leftAnkleB = skeletonB[BodyPart.LEFT_LOWER_LEG]?.tailPosition ?: error("Missing left ankle position B")
val leftAnkleAToB = leftAnkleB - leftAnkleA
val rightAnkleA = skeletonA[BodyPart.RIGHT_LOWER_LEG]?.tailPosition ?: error("Missing right ankle position A")
val rightAnkleB = skeletonB[BodyPart.RIGHT_LOWER_LEG]?.tailPosition ?: error("Missing right ankle position B")
val rightAnkleAToB = rightAnkleB - rightAnkleA
// TODO Consider headset sliding; if HMD consistently aligns with sliding, then
// either height is wrong, or the headset has weird movement
CONTRIBUTING_BODY_PARTS.forEach { bodyPart ->
val boneA = skeletonA[bodyPart] ?: return@forEach
val boneB = skeletonB[bodyPart] ?: return@forEach
val contribution = contributions.getOrPut(bodyPart) { BoneContribution() }
val localBoneTailAToB = boneB.localTailPosition - boneA.localTailPosition
val side = bodyPart.side
// LEFT (or both)
if (side != Side.RIGHT) {
boneContribution(
contribution,
leftAnkleAToB,
localBoneTailAToB,
)
}
// RIGHT (or both)
if (side != Side.LEFT) {
boneContribution(
contribution,
rightAnkleAToB,
localBoneTailAToB,
)
}
}
}
@@ -1,68 +0,0 @@
package dev.slimevr.autobone
import dev.slimevr.skeleton.ComputedSkeleton
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
fun slideContributionWeight(ankleA: Vector3, ankleB: Vector3, localBoneTailA: Vector3, localBoneTailB: Vector3): Float {
val ankleAToB = ankleB - ankleA
val localBoneTailAToB = localBoneTailB - localBoneTailA
val boneToSlideDirectionRatio = ankleAToB.unit().dot(localBoneTailAToB.unit())
// if +, shorten bone, if -, lengthen bone
// sum all contribution weights, divide each bone's weight by the sum, then multiply
// by the slide magnitude in order to find the corresponding bone change
return localBoneTailAToB.len() * boneToSlideDirectionRatio
}
// TODO This is a placeholder
val PLACEHOLDER_BODY_PARTS_TO_ADJUST = arrayOf(
BodyPart.UPPER_CHEST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
// etc.
)
fun step(skeletonA: ComputedSkeleton, skeletonB: ComputedSkeleton) {
// TODO We need to consider both ankles, there are two... We can do contribution per
// ankle
// TODO This is a placeholder
val ankleA = Vector3.ZERO
// TODO This is a placeholder
val ankleB = Vector3.ZERO
// TODO Consider headset sliding; if HMD consistently aligns with sliding, then
// either height is wrong, or the headset has weird movement
val contributions = PLACEHOLDER_BODY_PARTS_TO_ADJUST.map { bodyPart ->
val boneA = skeletonA[bodyPart] ?: return@map 0f
val boneB = skeletonB[bodyPart] ?: return@map 0f
slideContributionWeight(
ankleA,
ankleB,
boneA.localTailPosition,
boneB.localTailPosition,
)
}.filter { it > 0f }
// TODO This is a placeholder
val slideMag = 1f
val contributionSum = contributions.sum()
val perBoneSlide = contributions.map {
(it * slideMag) / contributionSum
}
// TODO This is a placeholder
val config = 1f
val newConfigs = perBoneSlide.map {
config + it
}
// TODO Test new config to see if it actually reduces error? Or do we just
// accept the changes? The contribution scales for each frame and considers
// direction; we should be able to skip checking if it reduces error
}
@@ -2,18 +2,22 @@ package dev.slimevr.config
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.tracker.driverTrackerHardwareId
import dev.slimevr.tracker.hidTrackerHardwareId
import dev.slimevr.tracker.udpTrackerHardwareId
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import solarxr_protocol.datatypes.BodyPart
private const val DEVICES_CONFIG_VERSION = 1
private const val DEVICES_CONFIG_VERSION = 2
const val DEVICES_CONFIG_PATH = "devices.json"
@Serializable
@@ -88,9 +92,32 @@ class DevicesConfig(
private fun migrateDevicesConfig(json: JsonObject): JsonObject {
val version = json["version"]?.jsonPrimitive?.intOrNull ?: 0
return when {
else -> json
if (version >= DEVICES_CONFIG_VERSION) return json
val migrated = (version + 1..DEVICES_CONFIG_VERSION).fold(json) { current, to -> migrateDevicesConfigTo(to, current) }
return JsonObject(migrated + ("version" to JsonPrimitive(DEVICES_CONFIG_VERSION)))
}
/** Brings a devices config up to version [to] from the one before. */
private fun migrateDevicesConfigTo(to: Int, json: JsonObject): JsonObject = when (to) {
1 -> json
2 -> migrateDevicesConfigV2(json)
else -> error("No devices config migration to version $to")
}
/** Version 1 keyed trackers by their bare hardware id, version 2 prefixes it with the tracker origin. */
private fun migrateDevicesConfigV2(json: JsonObject): JsonObject {
val udpTrackerId = Regex("((?:[0-9A-F]{2}:){5}[0-9A-F]{2}|\\d{1,3}(?:\\.\\d{1,3}){3}):(\\d{1,9})")
val hidTrackerId = Regex("[0-9A-F]{12}|[0-9A-F]{16}")
fun prefixed(id: String): String {
if (id.startsWith("vmc:") || id.startsWith("vrcosc:")) return id
udpTrackerId.matchEntire(id)?.let { return udpTrackerHardwareId(it.groupValues[1], it.groupValues[2].toInt()) }
if (hidTrackerId.matches(id)) return hidTrackerHardwareId(id)
return driverTrackerHardwareId(id)
}
val trackers = json["trackers"] as? JsonObject ?: return json
return JsonObject(json + ("trackers" to JsonObject(trackers.mapKeys { (id, _) -> prefixed(id) })))
}
private fun parseAndMigrateDevicesConfig(raw: String): DevicesConfigState {
@@ -0,0 +1,276 @@
package dev.slimevr.config
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.hidTrackerHardwareId
import dev.slimevr.tracker.udpTrackerHardwareId
import io.github.axisangles.ktmath.Quaternion
import it.krzeminski.snakeyaml.engine.kmp.api.Load
import it.krzeminski.snakeyaml.engine.kmp.api.LoadSettings
import kotlinx.coroutines.delay
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.StayAlignedRelaxedPose
/** Config file of the previous server, in the same folder as the current config. */
const val LEGACY_CONFIG_PATH = "vrconfig.yml"
private const val MIN_LEGACY_CONFIG_VERSION = 14
private val UDP_TRACKER_NAME = Regex("udp://((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})/(\\d{1,9})")
private val HID_TRACKER_NAME = Regex("([0-9A-Fa-f]{12})/0")
private val LEGACY_POSE_KEYS = listOf(
StayAlignedRelaxedPose.STANDING to "standingRelaxedPose",
StayAlignedRelaxedPose.SITTING to "sittingRelaxedPose",
StayAlignedRelaxedPose.FLAT to "flatRelaxedPose",
)
data class LegacyConfigMigration(
val settings: SettingsConfigState,
val user: UserConfigData,
val devices: DevicesConfigState,
)
suspend fun importLegacyConfig(storage: ConfigStorage) {
if (storage.exists(GLOBAL_CONFIG_PATH)) return
val raw = storage.read(LEGACY_CONFIG_PATH) ?: return
val migration = try {
migrateLegacyConfig(raw)
} catch (e: Exception) {
AppLogger.config.error(e, "Failed to read ${storage.displayPath(LEGACY_CONFIG_PATH)}")
return
}
if (migration == null) {
AppLogger.config.info("Skipped ${storage.displayPath(LEGACY_CONFIG_PATH)}, only version $MIN_LEGACY_CONFIG_VERSION and newer are imported")
return
}
val defaults = GlobalConfigState()
storage.write(
configPath(SETTINGS_PROFILE_DIR, profileFileName(defaults.selectedSettingsProfile)),
jsonConfig.encodeToString(migration.settings),
overwrite = false,
)
storage.write(
configPath(USER_PROFILE_DIR, profileFileName(defaults.selectedUserProfile)),
jsonConfig.encodeToString(migration.user),
overwrite = false,
)
storage.write(DEVICES_CONFIG_PATH, jsonConfig.encodeToString(migration.devices), overwrite = false)
AppLogger.config.info("Imported ${storage.displayPath(LEGACY_CONFIG_PATH)}")
}
fun migrateLegacyConfig(yaml: String): LegacyConfigMigration? {
// Configs saved before the GUI trimmed the VRM hold its whole glTF JSON, which can go past the 3 MB default
val loadSettings = LoadSettings.builder().setCodePointLimit(Int.MAX_VALUE).build()
val root = Load(loadSettings).loadOne(yaml) as? Map<*, *> ?: return null
val version = intOf(root["modelVersion"]) ?: return null
if (version < MIN_LEGACY_CONFIG_VERSION) return null
return LegacyConfigMigration(
settings = settingsOf(root),
user = userOf(root),
devices = devicesOf(root),
)
}
private fun settingsOf(root: Map<*, *>): SettingsConfigState {
val defaults = SettingsConfigState()
val server = section(root, "server")
val skeleton = section(root, "skeleton")
val toggles = section(skeleton, "toggles")
val values = section(skeleton, "values")
val resets = section(root, "resetsConfig")
val tap = section(root, "tapDetection")
val vmc = section(root, "vmc")
val hid = section(root, "hidConfig")
val stayAligned = section(root, "stayAlignedConfig")
val defaultToggles = defaults.skeletonConfig.toggles
val defaultRatios = defaults.skeletonConfig.ratios
val defaultResets = defaults.resetsConfig
val defaultTap = defaults.trackerActionConfig
val defaultVmc = defaults.vmcConfig
return defaults.copy(
trackersConfig = defaults.trackersConfig.copy(
globalMagEnabled = boolOf(server["useMagnetometerOnAllTrackers"]) ?: defaults.trackersConfig.globalMagEnabled,
),
hidConfig = defaults.hidConfig.copy(
trackersOverHid = boolOf(hid["trackersOverHID"]) ?: defaults.hidConfig.trackersOverHid,
),
skeletonConfig = defaults.skeletonConfig.copy(
toggles = defaultToggles.copy(
floorClip = boolOf(toggles["floorClip"]) ?: defaultToggles.floorClip,
skatingCorrection = boolOf(toggles["skatingCorrection"]) ?: defaultToggles.skatingCorrection,
toeSnap = boolOf(toggles["toeSnap"]) ?: defaultToggles.toeSnap,
footPlant = boolOf(toggles["footPlant"]) ?: defaultToggles.footPlant,
mocapMode = boolOf(toggles["selfLocalization"]) ?: defaultToggles.mocapMode,
enforceConstraints = boolOf(toggles["enforceConstraints"]) ?: defaultToggles.enforceConstraints,
),
ratios = defaultRatios.copy(
interpolateUpperLegsTwistWithLowerLegs = floatOf(values["kneeTrackerAnkleAveraging"])
?: defaultRatios.interpolateUpperLegsTwistWithLowerLegs,
),
),
resetsConfig = defaultResets.copy(
resetMountingFeet = boolOf(resets["resetMountingFeet"]) ?: defaultResets.resetMountingFeet,
armsMountingResetMode = armsMountingResetModeOf(resets["mode"]) ?: defaultResets.armsMountingResetMode,
yawResetSmoothTime = floatOf(resets["yawResetSmoothTime"]) ?: defaultResets.yawResetSmoothTime,
saveMountingReset = boolOf(resets["saveMountingReset"]) ?: defaultResets.saveMountingReset,
resetHmdAttitude = boolOf(resets["resetHmdPitch"]) ?: defaultResets.resetHmdAttitude,
),
trackerActionConfig = defaultTap.copy(
yawResetAction = defaultTap.yawResetAction.copy(
enabled = boolOf(tap["yawResetEnabled"]) ?: defaultTap.yawResetAction.enabled,
delay = floatOf(tap["yawResetDelay"]) ?: defaultTap.yawResetAction.delay,
bodyPart = stringOf(tap["yawResetTracker"])?.let(::bodyPartOf) ?: defaultTap.yawResetAction.bodyPart,
taps = intOf(tap["yawResetTaps"]) ?: defaultTap.yawResetAction.taps,
),
fullResetAction = defaultTap.fullResetAction.copy(
enabled = boolOf(tap["fullResetEnabled"]) ?: defaultTap.fullResetAction.enabled,
delay = floatOf(tap["fullResetDelay"]) ?: defaultTap.fullResetAction.delay,
bodyPart = stringOf(tap["fullResetTracker"])?.let(::bodyPartOf) ?: defaultTap.fullResetAction.bodyPart,
taps = intOf(tap["fullResetTaps"]) ?: defaultTap.fullResetAction.taps,
),
mountingResetAction = defaultTap.mountingResetAction.copy(
enabled = boolOf(tap["mountingResetEnabled"]) ?: defaultTap.mountingResetAction.enabled,
delay = floatOf(tap["mountingResetDelay"]) ?: defaultTap.mountingResetAction.delay,
bodyPart = stringOf(tap["mountingResetTracker"])?.let(::bodyPartOf) ?: defaultTap.mountingResetAction.bodyPart,
taps = intOf(tap["mountingResetTaps"]) ?: defaultTap.mountingResetAction.taps,
),
tapsTrackersOverThreshold = intOf(tap["numberTrackersOverThreshold"]) ?: defaultTap.tapsTrackersOverThreshold,
),
vmcConfig = defaultVmc.copy(
enabled = boolOf(vmc["enabled"]) ?: defaultVmc.enabled,
portIn = intOf(vmc["portIn"]) ?: defaultVmc.portIn,
portOut = intOf(vmc["portOut"]) ?: defaultVmc.portOut,
address = stringOf(vmc["address"]) ?: defaultVmc.address,
mirrorTracking = boolOf(vmc["mirrorTracking"]) ?: defaultVmc.mirrorTracking,
anchorAtHips = boolOf(vmc["anchorHip"]) ?: defaultVmc.anchorAtHips,
vrmJson = vrmJsonOf(vmc["vrmJson"]) ?: defaultVmc.vrmJson,
),
stayAlignedConfig = defaults.stayAlignedConfig.copy(
enabled = boolOf(stayAligned["enabled"]) ?: defaults.stayAlignedConfig.enabled,
),
)
}
private fun userOf(root: Map<*, *>): UserConfigData {
val skeleton = section(root, "skeleton")
val stayAligned = section(root, "stayAlignedConfig")
val poses = LEGACY_POSE_KEYS.mapNotNull { (pose, key) ->
val old = section(stayAligned, key)
if (boolOf(old["enabled"]) != true) return@mapNotNull null
pose to StayAlignedPoseConfig(
recorded = true,
enabled = true,
upperLegAngleInDeg = floatOf(old["upperLegAngleInDeg"]) ?: 0f,
lowerLegAngleInDeg = floatOf(old["lowerLegAngleInDeg"]) ?: 0f,
footAngleInDeg = floatOf(old["footAngleInDeg"]) ?: 0f,
)
}.toMap()
val user = UserConfigData(stayAlignedPoses = poses)
val height = (floatOf(skeleton["hmdHeight"]) ?: 0f) - (floatOf(skeleton["floorHeight"]) ?: 0f)
if (height < MIN_USER_HEIGHT) return user
// Proportions are not imported, they are the defaults for the imported height
return withDefaultProportions(user.copy(userHeight = height))
}
private fun devicesOf(root: Map<*, *>): DevicesConfigState {
val oldTrackers = section(root, "trackers")
val trackers = oldTrackers.entries.mapNotNull { (name, old) ->
val hardwareId = (name as? String)?.let(::hardwareIdOf) ?: return@mapNotNull null
val config = old as? Map<*, *> ?: return@mapNotNull null
hardwareId to TrackerConfig(
bodyPart = stringOf(config["designation"])?.let { bodyPartOf(it.removePrefix("body:").uppercase()) },
customName = stringOf(config["customName"])?.takeIf { it.isNotBlank() },
mountingOrientation = quaternionOf(config["mountingOrientation"]) ?: Quaternion.IDENTITY,
)
}.toMap()
val knownDevices = (root["knownDevices"] as? List<*>).orEmpty().mapNotNull { stringOf(it)?.uppercase() }.toSet()
return DevicesConfigState(allowedUdpDevices = knownDevices, trackers = trackers)
}
private fun hardwareIdOf(trackerName: String): String? {
UDP_TRACKER_NAME.matchEntire(trackerName)?.let { return udpTrackerHardwareId(it.groupValues[1].uppercase(), it.groupValues[2].toInt()) }
HID_TRACKER_NAME.matchEntire(trackerName)?.let { return hidTrackerHardwareId(it.groupValues[1].uppercase()) }
return null
}
private fun bodyPartOf(trackerPosition: String): BodyPart? = when (trackerPosition) {
"CHEST" -> BodyPart.UPPER_CHEST
"WAIST" -> BodyPart.LOWER_WAIST
else -> BodyPart.entries.firstOrNull { it != BodyPart.NONE && it.name == trackerPosition }
}
/** T-pose down does not exist anymore, both T-poses become the side T-pose. */
private fun armsMountingResetModeOf(value: Any?): ArmsMountingResetMode? = when (stringOf(value)) {
"BACK" -> ArmsMountingResetMode.BACK
"FORWARD" -> ArmsMountingResetMode.FORWARD
"TPOSE_UP", "TPOSE_DOWN" -> ArmsMountingResetMode.SIDE
else -> null
}
/** Strip older VRM that were too big */
private fun vrmJsonOf(value: Any?): String? {
val raw = stringOf(value)?.takeIf { it.isNotEmpty() } ?: return null
val gltf = try {
jsonConfig.parseToJsonElement(raw).jsonObject
} catch (_: IllegalArgumentException) {
return null
}
val extensions = gltf["extensions"] as? JsonObject
return buildJsonObject {
if (extensions != null) {
put(
"extensions",
buildJsonObject {
extensions["VRM"]?.let { put("VRM", it) }
extensions["VRMC_vrm"]?.let { put("VRMC_vrm", it) }
},
)
}
gltf["extensionsUsed"]?.let { put("extensionsUsed", it) }
gltf["nodes"]?.let { put("nodes", it) }
}.toString()
}
private fun quaternionOf(value: Any?): Quaternion? {
val map = value as? Map<*, *> ?: return null
return Quaternion(
floatOf(map["w"]) ?: return null,
floatOf(map["x"]) ?: return null,
floatOf(map["y"]) ?: return null,
floatOf(map["z"]) ?: return null,
)
}
private fun section(map: Map<*, *>, key: String): Map<*, *> = map[key] as? Map<*, *> ?: emptyMap<Any?, Any?>()
private fun stringOf(value: Any?): String? = value as? String
private fun boolOf(value: Any?): Boolean? = when (value) {
is Boolean -> value
is String -> value.toBooleanStrictOrNull()
else -> null
}
private fun floatOf(value: Any?): Float? = when (value) {
is Number -> value.toFloat()
is String -> value.toFloatOrNull()
else -> null
}
private fun intOf(value: Any?): Int? = when (value) {
is Number -> value.toInt()
is String -> value.toIntOrNull()
else -> null
}
@@ -20,6 +20,7 @@ import solarxr_protocol.rpc.ProfileKind
import solarxr_protocol.rpc.ProfileOperationStatus
import java.util.UUID
const val GLOBAL_CONFIG_PATH = "global.json"
private const val GLOBAL_CONFIG_VERSION = 1
private const val CURRENT_CONSENT_VERSION = 2
@@ -67,7 +68,7 @@ class GlobalConfig(
companion object {
suspend fun create(scope: CoroutineScope, storage: ConfigStorage): GlobalConfig {
val initialState = loadFileWithBackup(storage, "global.json", GlobalConfigState()) {
val initialState = loadFileWithBackup(storage, GLOBAL_CONFIG_PATH, GlobalConfigState()) {
parseAndMigrateGlobalConfig(it)
}.let(::withSafeProfileNames)
val context = Context.create(
@@ -79,12 +80,12 @@ class GlobalConfig(
val globalConfig = GlobalConfig(context)
globalConfig.startObserving()
// Persists defaults filled on load (the generated userId), autosave skips the initial state
storage.write("global.json", jsonConfig.encodeToString(initialState))
storage.write(GLOBAL_CONFIG_PATH, jsonConfig.encodeToString(initialState))
launchAutosave(
scope = scope,
state = context.state,
storage = storage,
toPath = { "global.json" },
toPath = { GLOBAL_CONFIG_PATH },
serialize = { jsonConfig.encodeToString(it) },
)
return globalConfig
@@ -280,6 +281,7 @@ class AppConfig(
companion object {
suspend fun create(scope: CoroutineScope, storage: ConfigStorage): AppConfig {
importLegacyConfig(storage)
val globalConfig = GlobalConfig.create(scope, storage)
val userConfig = UserConfig.create(scope, storage, globalConfig.context.state.value.selectedUserProfile)
@@ -12,6 +12,7 @@ import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.KeybindId
import solarxr_protocol.rpc.RoutingOutput
@@ -47,24 +48,23 @@ data class DriverConfig(
val sendVelocity: Boolean = false,
)
// Used in TrackerActionConfig
@Serializable
data class TapDetectionConfig(
var yawResetDelay: Float = 0.2f,
var fullResetDelay: Float = 1.4f,
var mountingResetDelay: Float = 1.4f,
var yawResetEnabled: Boolean = true,
var fullResetEnabled: Boolean = true,
var mountingResetEnabled: Boolean = true,
data class TrackerActionSettings(
val enabled: Boolean = true,
val delay: Float,
@Serializable(with = BodyPartSerializer::class)
var yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST,
@Serializable(with = BodyPartSerializer::class)
var mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG,
@Serializable(with = BodyPartSerializer::class)
var fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG,
var yawResetTaps: Int = 2,
var fullResetTaps: Int = 3,
var mountingResetTaps: Int = 3,
var numberTrackersOverThreshold: Int = 1,
val bodyPart: BodyPart?,
val method: TrackerActionMethod = TrackerActionMethod.BOTH,
val taps: Int,
)
@Serializable
data class TrackerActionConfig(
val yawResetAction: TrackerActionSettings = TrackerActionSettings(delay = 0.2f, bodyPart = BodyPart.UPPER_CHEST, taps = 2),
val fullResetAction: TrackerActionSettings = TrackerActionSettings(delay = 1.4f, bodyPart = BodyPart.LEFT_UPPER_LEG, taps = 3),
val mountingResetAction: TrackerActionSettings = TrackerActionSettings(delay = 1.0f, bodyPart = BodyPart.RIGHT_UPPER_LEG, taps = 3),
val tapsTrackersOverThreshold: Int = 1,
)
@Serializable
@@ -120,7 +120,7 @@ data class SkeletonRatiosConfig(
val predictionStrength: Float = 0.30f,
val spineCurvature: Float = 0.75f,
val imputeSpineFromUpperToLower: Float = DEFAULT_SPINE_UPPER_LOWER,
val interpolateUpperLegsTwistWithLowerLegs: Float = 0.8f,
val interpolateUpperLegsTwistWithLowerLegs: Float = 0.85f,
val skatingCorrectionStrength: Float = 0.5f,
)
@@ -170,7 +170,7 @@ data class SettingsConfigState(
val hidConfig: HidConfig = HidConfig(),
val boneRoutingConfig: BoneRoutingConfig = BoneRoutingConfig(),
val driverConfig: DriverConfig = DriverConfig(),
val tapDetectionConfig: TapDetectionConfig = TapDetectionConfig(),
val trackerActionConfig: TrackerActionConfig = TrackerActionConfig(),
val resetsConfig: ResetsConfig = ResetsConfig(),
val keybinds: List<KeybindConfig> = defaultKeybinds(),
val skeletonConfig: SkeletonConfig = SkeletonConfig(),
@@ -16,6 +16,9 @@ import solarxr_protocol.rpc.StayAlignedRelaxedPose
private const val USER_CONFIG_VERSION = 1
private const val DEFAULT_USER_HEIGHT = 1.6f
/** Lowest eye height accepted as the user height. */
const val MIN_USER_HEIGHT = 0.9f
/** A relaxed pose of the user, used by Stay Aligned to correct moving trackers. */
@Serializable
data class StayAlignedPoseConfig(
@@ -83,8 +83,8 @@ class HeightCalibrationManager(
combine(
controllers.map { controller ->
controller.context.state.map { s ->
val position = s.position ?: error("hands (or Controller) will always have a position in this case")
TrackerSnapshot(position = position, rotation = s.rawRotation)
val rawPosition = s.rawPosition ?: error("hands (or Controller) will always have a rawPosition in this case")
TrackerSnapshot(position = rawPosition, rotation = s.rawRotation)
}
},
) { snapshots -> snapshots.minByOrNull { it.position.y } ?: error("snapshots is empty; controllers check above should have prevented this") }
@@ -7,6 +7,7 @@ import dev.slimevr.hid.HIDDataLegacy
import dev.slimevr.hid.HIDReceiver
import dev.slimevr.hid.HIDReceiverBehaviour
import dev.slimevr.hid.HIDRotationButtonLegacy
import solarxr_protocol.datatypes.TrackerActionMethod
class HIDButtonLegacyBehaviour(private val appContext: AppContextProvider) : HIDReceiverBehaviour {
private val lastButton = mutableMapOf<Int, Int>()
@@ -24,7 +25,11 @@ class HIDButtonLegacyBehaviour(private val appContext: AppContextProvider) : HID
if (!fired) return
val tracker = receiver.getTracker(hidId) ?: return
appContext.tapDetectionManager.actionTriggered(tracker.context.state.value.id, "HIDButtonLegacy")
appContext.trackerActionManager.actionTriggered(
tracker.context.state.value.id,
"HIDButtonLegacy",
TrackerActionMethod.BUTTON,
)
}
companion object {
@@ -7,6 +7,7 @@ import dev.slimevr.hid.HIDReceiverActions
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.hidTrackerHardwareId
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
@@ -53,10 +54,11 @@ internal suspend fun registerHidDevice(
/** Creates or finds the [Tracker] for an already-registered HID device and links it to [hidId]. */
internal fun ensureHidTracker(receiver: HIDReceiver, hidId: Int, deviceId: Int, imuType: ImuType? = null): Tracker? {
val deviceState = receiver.appContext.server.getDevice(deviceId)?.context?.state?.value ?: return null
val hardwareId = hidTrackerHardwareId(deviceState.address)
val tracker = receiver.getTracker(hidId)
?: receiver.appContext.server.context.state.value.trackers.values
.find { it.context.state.value.hardwareId == deviceState.address && it.context.state.value.origin == DeviceOrigin.HID }
.find { it.context.state.value.hardwareId == hardwareId && it.context.state.value.origin == DeviceOrigin.HID }
?: run {
val trackerId = receiver.appContext.server.nextHandle()
val newTracker = Tracker.create(
@@ -64,7 +66,7 @@ internal fun ensureHidTracker(receiver: HIDReceiver, hidId: Int, deviceId: Int,
id = trackerId,
deviceId = deviceState.id,
imuType = imuType,
hardwareId = deviceState.address,
hardwareId = hardwareId,
origin = DeviceOrigin.HID,
appContext = receiver.appContext,
)
@@ -4,12 +4,17 @@ import dev.slimevr.AppContextProvider
import dev.slimevr.hid.HIDButton
import dev.slimevr.hid.HIDReceiver
import dev.slimevr.hid.HIDReceiverBehaviour
import solarxr_protocol.datatypes.TrackerActionMethod
class HIDButtonV3Behaviour(private val appContext: AppContextProvider) : HIDReceiverBehaviour {
override fun observe(receiver: HIDReceiver) {
receiver.packetEvents.on<HIDButton> { packet ->
val tracker = receiver.getTracker(packet.hidId) ?: return@on
appContext.tapDetectionManager.actionTriggered(tracker.context.state.value.id, "HIDButtonV3")
appContext.trackerActionManager.actionTriggered(
tracker.context.state.value.id,
"HIDButtonV3",
TrackerActionMethod.BUTTON,
)
}.launchIn(receiver.context.scope)
}
}
@@ -46,6 +46,9 @@ import kotlin.collections.listOf
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeMark
// Feet go slightly inwards on pose mounting
private const val FEET_POSE_DEG_INWARDS = 15
data class ResetsState(
val canDoYawReset: Boolean,
val canDoMountingReset: Boolean,
@@ -233,6 +236,11 @@ class ResetsManager(
}
private fun getYawOffset(bodyPart: BodyPart?, armsResetMode: ArmsMountingResetMode) = when (bodyPart) {
// Feet go back but a little inwards
BodyPart.LEFT_FOOT -> FastMath.PI - FEET_POSE_DEG_INWARDS * FastMath.DEG_TO_RAD
BodyPart.RIGHT_FOOT -> FastMath.PI + FEET_POSE_DEG_INWARDS * FastMath.DEG_TO_RAD
// Going forward
in ResetBodyParts.UPPER_LEGS -> 0f
@@ -90,7 +90,6 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.LOWER_CHEST,
Vector3.ZERO,
Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)),
Vector3.ZERO,
null,
@@ -99,7 +98,6 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.LEFT_LOWER_LEG,
Vector3.ZERO,
Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)),
Vector3.ZERO,
null,
@@ -114,7 +112,6 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.HEAD,
Vector3.ZERO,
Quaternion.IDENTITY,
Vector3.ZERO,
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
@@ -299,7 +296,7 @@ class ComputedSkeletonBehaviour(
// If head changed position, set the new position in state (for Localizer).
if (bodyPart == BodyPart.HEAD && !boneInput.isPositionActive && boneInput.position != previous?.position) {
receiver.context.dispatch(SkeletonActions.SetBonePose(BodyPart.HEAD, Vector3.ZERO, null, null, boneInput.position, false))
receiver.context.dispatch(SkeletonActions.SetBonePose(BodyPart.HEAD, null, null, boneInput.position, false))
}
}
// Inputs changed; re-run FK
@@ -4,7 +4,6 @@ import com.jme3.math.FastMath
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import javax.swing.text.StyledEditorKit
private val METACARPAL_THUMB_CONSTRAINT = LooseHingeConstraint(
-80f * FastMath.DEG_TO_RAD,
@@ -49,8 +48,8 @@ val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
70f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_UPPER_ARM to FreeHingeConstraint(
-30f * FastMath.DEG_TO_RAD,
130f * FastMath.DEG_TO_RAD,
-40f * FastMath.DEG_TO_RAD,
125f * FastMath.DEG_TO_RAD,
Vector3.POS_Y,
),
BodyPart.LEFT_LOWER_ARM to LooseHingeConstraint(
@@ -70,8 +69,8 @@ val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
70f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_UPPER_ARM to FreeHingeConstraint(
-30f * FastMath.DEG_TO_RAD,
130f * FastMath.DEG_TO_RAD,
-40f * FastMath.DEG_TO_RAD,
125f * FastMath.DEG_TO_RAD,
Vector3.NEG_Y,
),
BodyPart.RIGHT_LOWER_ARM to LooseHingeConstraint(
@@ -114,9 +113,9 @@ val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
90f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_LOWER_LEG to LooseHingeConstraint(
-150f * FastMath.DEG_TO_RAD,
-165f * FastMath.DEG_TO_RAD,
6f * FastMath.DEG_TO_RAD,
50f * FastMath.DEG_TO_RAD,
65f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_FOOT to LooseHingeConstraint(
-45f * FastMath.DEG_TO_RAD,
@@ -131,9 +130,9 @@ val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
90f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_LOWER_LEG to LooseHingeConstraint(
-150f * FastMath.DEG_TO_RAD,
-165f * FastMath.DEG_TO_RAD,
6f * FastMath.DEG_TO_RAD,
50f * FastMath.DEG_TO_RAD,
65f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_FOOT to LooseHingeConstraint(
-45f * FastMath.DEG_TO_RAD,
@@ -220,10 +219,10 @@ val BODY_PART_PREFERRED_ROTATION = BodyPartMap(
BodyPart.LEFT_LOWER_ARM to Quaternion.fromRotationVector(0f, 70f * FastMath.DEG_TO_RAD, 0f),
BodyPart.RIGHT_LOWER_ARM to Quaternion.fromRotationVector(0f, -70f * FastMath.DEG_TO_RAD, 0f),
BodyPart.LEFT_UPPER_LEG to Quaternion.rotationAroundXAxis(115f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_UPPER_LEG to Quaternion.rotationAroundXAxis(115f * FastMath.DEG_TO_RAD),
BodyPart.LEFT_LOWER_LEG to Quaternion.rotationAroundXAxis(-48f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_LOWER_LEG to Quaternion.rotationAroundXAxis(-48f * FastMath.DEG_TO_RAD),
BodyPart.LEFT_UPPER_LEG to Quaternion.rotationAroundXAxis(35f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_UPPER_LEG to Quaternion.rotationAroundXAxis(35f * FastMath.DEG_TO_RAD),
BodyPart.LEFT_LOWER_LEG to Quaternion.rotationAroundXAxis(-20f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_LOWER_LEG to Quaternion.rotationAroundXAxis(-20f * FastMath.DEG_TO_RAD),
// BodyPart.UPPER_CHEST to Quaternion.rotationAroundXAxis(-10f * FastMath.DEG_TO_RAD),
// BodyPart.LOWER_CHEST to Quaternion.rotationAroundXAxis(-5f * FastMath.DEG_TO_RAD),
@@ -237,45 +236,44 @@ val BODY_PART_PREFERRED_ROTATION = BodyPartMap(
// TODO May need to decay constraint over iterations
val BODY_PART_OFFSET_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
mapOf(
// TODO Figure out arms
BodyPart.LEFT_UPPER_ARM to TwistSwingConstraint(
BodyPart.LEFT_UPPER_ARM to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
10f * FastMath.DEG_TO_RAD,
Vector3.POS_Z,
Vector3.POS_X,
),
BodyPart.LEFT_LOWER_ARM to LooseAxisConstraint(
1f * FastMath.DEG_TO_RAD,
5f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.RIGHT_UPPER_ARM to TwistSwingConstraint(
BodyPart.RIGHT_UPPER_ARM to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
10f * FastMath.DEG_TO_RAD,
Vector3.NEG_Z,
Vector3.POS_X,
),
BodyPart.RIGHT_LOWER_ARM to LooseAxisConstraint(
1f * FastMath.DEG_TO_RAD,
5f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.UPPER_CHEST to TwistSwingConstraint(
8f * FastMath.DEG_TO_RAD,
4f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.LOWER_CHEST to TwistSwingConstraint(
4f * FastMath.DEG_TO_RAD,
2f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.UPPER_WAIST to TwistSwingConstraint(
6f * FastMath.DEG_TO_RAD,
4f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.LOWER_WAIST to TwistSwingConstraint(
3f * FastMath.DEG_TO_RAD,
2f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
// BodyPart.UPPER_CHEST to TwistSwingConstraint(
// 8f * FastMath.DEG_TO_RAD,
// 4f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
// BodyPart.LOWER_CHEST to TwistSwingConstraint(
// 4f * FastMath.DEG_TO_RAD,
// 2f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
// BodyPart.UPPER_WAIST to TwistSwingConstraint(
// 6f * FastMath.DEG_TO_RAD,
// 4f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
// BodyPart.LOWER_WAIST to TwistSwingConstraint(
// 3f * FastMath.DEG_TO_RAD,
// 2f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
BodyPart.LEFT_UPPER_LEG to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
@@ -0,0 +1,52 @@
package dev.slimevr.skeleton.computedprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonComputedProcessor
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
/**
* Rotates the first Quaternion to match its twist to the rotation of
* the second Quaternion
*
* @param from the first Quaternion
* @param to the second Quaternion
* @return the rotated Quaternion
*/
private fun alignTwist(from: Quaternion, to: Quaternion): Quaternion {
val local = to.localAbout(from)
val twist = local.eulerHeading()
return twist.globalAbout(from)
}
/**
* Handles rotating the upper legs' twist to match the lower legs' twist to make VRChat's knee IK work better.
*
* This is a computed processor running after IK because we want to use the real upper leg's twist for IK and constraints.
*/
class UpperLegsTwistComputedProcessor(val settings: Settings) : SkeletonComputedProcessor {
/**
* First value is the BodyPart to be aligned.
* Second value is the source BodyPart.
*/
private val bodyPartToSources = arrayOf(
BodyPart.LEFT_UPPER_LEG to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_LOWER_LEG,
)
override fun process(mutableComputedSkeleton: ComputedSkeleton, inputSkeleton: InputSkeleton) {
val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs
if (ratio == 0f) return
// Upper legs are written, lower legs are read, so the two never overlap
for ((part, source) in bodyPartToSources) {
val bone = mutableComputedSkeleton[part] ?: continue
val sourceRotation = mutableComputedSkeleton[source]?.rotation ?: continue
val alignedRotation = alignTwist(bone.rotation, sourceRotation)
mutableComputedSkeleton[part] = bone.copy(rotation = bone.rotation.interpR(alignedRotation, ratio))
}
}
}
@@ -1,23 +1,36 @@
package dev.slimevr.skeleton.fkprocessors
import com.jme3.math.FastMath
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.skeleton.SkeletonFkProcessor
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import kotlin.math.abs
// The max height to plant feet by
const val ROTATION_CORRECTION_VERTICAL = 0.1f
private const val ROTATION_CORRECTION_VERTICAL = 0.1f
private const val ANKLE_DOWN_MIN = 0.35f
private const val ANKLE_DOWN_MAX = 0.63f
fun computeFootPlantRatio(
ankleHeight: Float,
floorLevel: Float,
ankleLocalPosition: Vector3,
): Float {
val ankleHeightAboveFloor = ankleHeight - floorLevel
val ratioOfRangeFromFloor = (ankleHeightAboveFloor / ROTATION_CORRECTION_VERTICAL).coerceIn(0f, 1f)
// Ratio of range *to* floor
return 1f - ratioOfRangeFromFloor
val rangeToFloorRatio = 1f - ratioOfRangeFromFloor
// Lessen the ratio as the ankle doesn't point down
val ankleDownDirection = abs(ankleLocalPosition.unit().y.coerceAtMost(0f))
val ankleDownRatio = FastMath.remapClamped(ankleDownDirection, ANKLE_DOWN_MIN, ANKLE_DOWN_MAX, 0f, 1f)
return rangeToFloorRatio * ankleDownRatio
}
fun correctFootAttitude(
@@ -27,21 +40,26 @@ fun correctFootAttitude(
): Quaternion = rotation.interpQ(rotation.eulerHeading(), correctionRatio)
class FootPlantFkProcessor(val skeleton: Skeleton) : SkeletonFkProcessor {
val bodyParts: Array<BodyPart> = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT)
val bodyParts = arrayOf(
BodyPart.LEFT_LOWER_LEG to BodyPart.LEFT_FOOT,
BodyPart.RIGHT_LOWER_LEG to BodyPart.RIGHT_FOOT,
)
override fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) {
if (!skeleton.effectiveFootPlant) return
for (bodyPart in bodyParts) {
val input = mutableInputSkeleton[bodyPart] ?: continue
for ((anklePart, footPart) in bodyParts) {
val input = mutableInputSkeleton[footPart] ?: continue
if (input.isRotationActive) continue
val output = fk[bodyPart] ?: continue
mutableInputSkeleton[bodyPart] = input.copy(
val foot = fk[footPart] ?: continue
val ankle = fk[anklePart] ?: continue
mutableInputSkeleton[footPart] = input.copy(
rotation = correctFootAttitude(
input.rotation,
computeFootPlantRatio(
output.headPosition.y,
foot.headPosition.y,
floorLevel,
ankle.localTailPosition,
),
),
)
@@ -10,10 +10,10 @@ import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import kotlin.math.abs
const val TOE_SNAP_RANGE_MULTIPLIER = 2f
const val MAX_TOE_SNAP_RATIO = 0.8f
const val ANKLE_DOWN_MIN = 0.65f
const val ANKLE_DOWN_MAX = 0.85f
private const val TOE_SNAP_RANGE_MULTIPLIER = 1.64f
private const val MAX_TOE_SNAP_RATIO = 0.8f
private const val ANKLE_DOWN_MIN = 0.75f
private const val ANKLE_DOWN_MAX = 0.94f
fun computeToeSnapRatio(
ankleHeight: Float,
@@ -65,6 +65,7 @@ class ToeSnapFkProcessor(val skeleton: Skeleton) : SkeletonFkProcessor {
if (input.isRotationActive) continue
val length = input.offset.len()
if (length <= 0f) continue
val ankle = fk[anklePart] ?: continue
val foot = fk[footPart] ?: continue
mutableInputSkeleton[footPart] = input.copy(
@@ -32,29 +32,30 @@ fun parentRot(
bones[parent]?.rotation
} ?: Quaternion.IDENTITY
const val PREFERRED_ROTATION_START_BIAS = 25.0
const val PREFERRED_ROTATION_START_BIAS = 62.0
const val PREFERRED_ROTATION_START_BIAS_MULTIPLIER = (PREFERRED_ROTATION_START_BIAS * PREFERRED_ROTATION_START_BIAS) - PREFERRED_ROTATION_START_BIAS
fun adjustToPreferredRotations(
mutableBoneInputs: InputSkeleton,
mutableComputedSkeleton: ComputedSkeleton,
goals: List<IKChainGoal>,
constraints: BodyPartMap<Constraint>?,
) {
val changedBodyParts = mutableSetOf<BodyPart>()
for (goal in goals) {
val distanceFromTarget = chainDistanceFromTarget(mutableComputedSkeleton, goal.chain, goal.target).toDouble()
val chainEndToTarget = chainDistanceFromTarget(mutableComputedSkeleton, goal.chain, goal.target).toDouble()
val maxChainLength = chainOffsetsLength(mutableComputedSkeleton, goal.chain)
val chainStartToTarget = (goal.target - requireBone(mutableComputedSkeleton, goal.chain.first()).headPosition).len()
val distanceRatio = if (chainStartToTarget < maxChainLength) {
(distanceFromTarget / maxChainLength).coerceAtMost(1.0)
} else {
// Unreachable
continue
}
val distanceRatio = (chainEndToTarget / maxChainLength).coerceAtMost(1.0)
val t = (log(PREFERRED_ROTATION_START_BIAS + (distanceRatio * PREFERRED_ROTATION_START_BIAS_MULTIPLIER), PREFERRED_ROTATION_START_BIAS) - 1).toFloat()
for (bodyPart in goal.chain) {
val preferredRotation = BODY_PART_PREFERRED_ROTATION[bodyPart] ?: continue
val bone = mutableBoneInputs[bodyPart] ?: continue
mutableBoneInputs[bodyPart] = bone.copy(rotation = bone.rotation * preferredRotation.pow(t))
val offsetRotation = bone.rotation * preferredRotation.pow(t)
val newRotation = constraints?.get(bodyPart)?.apply(
parentRot(mutableComputedSkeleton, bodyPart),
offsetRotation,
) ?: offsetRotation
mutableBoneInputs[bodyPart] = bone.copy(rotation = newRotation)
changedBodyParts.add(bodyPart)
}
}
@@ -206,7 +207,7 @@ fun ccdIk(
if (goals.isEmpty()) return true
// Set each bone we're gonna do IK on to its preferred rotation
adjustToPreferredRotations(mutableBoneInputs, mutableComputedSkeleton, goals)
adjustToPreferredRotations(mutableBoneInputs, mutableComputedSkeleton, goals, constraints)
// IK iterations
var allGoalsMet = true
@@ -35,8 +35,8 @@ private val UPSAMPLING_TIME_CARRYOVER_LIMIT = 900.milliseconds
private const val SMOOTHING_MS_MAX = 50.0
// Prediction
private const val PREDICTION_MS_MAX = 32.0
private const val PREVIOUS_PREDICTION_DECAY = 0.25f
private const val PREDICTION_MS_MAX = 30.0
private const val PREVIOUS_PREDICTION_CARRYOVER = 0.2f
// Used to minimize latency even more for arm tracking where it is more noticeable
private val PART_MULTIPLIER = BodyPartMap(
@@ -100,7 +100,7 @@ private fun computePredictedRotation(
if (previousRotation == null) return targetRotation
// Use some of the previous prediction
val previousPredictionDelta = previousPredictedRotation?.localAbout(previousRotation)?.pow(PREVIOUS_PREDICTION_DECAY)
val previousPredictionDelta = previousPredictedRotation?.localAbout(previousRotation)?.pow(PREVIOUS_PREDICTION_CARRYOVER)
?: Quaternion.IDENTITY
val currentDelta = if (poseTimeDelta > Duration.ZERO) {
@@ -8,8 +8,8 @@ import solarxr_protocol.datatypes.BodyPart
// Neck bends less when looking up
private const val UP_RATIO = 0.74f
// Neck bends slightly more when looking down.
private const val DOWN_RATIO = 1.14f
// Neck bends more when looking down.
private const val DOWN_RATIO = 1.25f
/**
* Guesses where the neck is supposed to be when the user has a head tracker but no neck tracker.
@@ -43,9 +43,9 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_CHEST to Reliability(-11.5f, -20f), // Itself
// To
SpineSource.LOWER_CHEST to Reliability(-6f, -15f, 0f),
SpineSource.UPPER_WAIST to Reliability(1.5f, 4f, 0.4f),
SpineSource.UPPER_WAIST to Reliability(1.5f, 4f, 0.44f),
SpineSource.LOWER_WAIST to Reliability(2f, 5f, 0.4f),
SpineSource.HIP to Reliability(4f, 6.25f, 0.35f),
SpineSource.HIP to Reliability(4f, 6.25f, 0.4f),
SpineSource.UPPER_LEGS to Reliability(4f, 5f),
),
SpineSource.LOWER_CHEST to arrayOf(
@@ -53,9 +53,9 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_CHEST to Reliability(-18f, 40f),
SpineSource.LOWER_CHEST to Reliability(30f), // Itself
// To
SpineSource.UPPER_WAIST to Reliability(1.5f, 10f, 0.4f),
SpineSource.UPPER_WAIST to Reliability(1.5f, 10f, 0.44f),
SpineSource.LOWER_WAIST to Reliability(2f, 8f, 0.4f),
SpineSource.HIP to Reliability(4f, 7.25f, 0.35f),
SpineSource.HIP to Reliability(4f, 7.25f, 0.4f),
SpineSource.UPPER_LEGS to Reliability(4f, 6f),
),
SpineSource.UPPER_WAIST to arrayOf(
@@ -65,7 +65,7 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_WAIST to Reliability(40f), // Itself
// To
SpineSource.LOWER_WAIST to Reliability(16f, 18f, 0.85f),
SpineSource.HIP to Reliability(4.5f, 13.5f, 0.87f),
SpineSource.HIP to Reliability(4.5f, 13.5f, 0.88f),
SpineSource.UPPER_LEGS to Reliability(0.25f, 12f),
),
SpineSource.LOWER_WAIST to arrayOf(
@@ -75,7 +75,7 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_WAIST to Reliability(25f),
SpineSource.LOWER_WAIST to Reliability(38f), // Itself
// To
SpineSource.HIP to Reliability(5.25f, 13f, 0.87f),
SpineSource.HIP to Reliability(5.25f, 13f, 0.88f),
SpineSource.UPPER_LEGS to Reliability(1.75f, 11f),
),
SpineSource.HIP to arrayOf(
@@ -84,7 +84,7 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.LOWER_CHEST to Reliability(9.75f, 9.25f),
SpineSource.UPPER_WAIST to Reliability(13f, 20f),
SpineSource.LOWER_WAIST to Reliability(14f, 30f),
SpineSource.HIP to Reliability(38f, 60f, 0.92f), // Itself
SpineSource.HIP to Reliability(38f, 60f), // Itself
// To
SpineSource.UPPER_LEGS to Reliability(7f, 17f),
),
@@ -1,17 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
/**
* Handles tracker offset. For example, an HMD's rotation will be about 10cm in front of the head bone.
*/
class BoneOffsetInputProcessor : SkeletonInputProcessor {
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for ((bodyPart, bone) in mutableInputSkeleton) {
if (bone.boneOffset.isZero()) continue
val localOffset = bone.rotation.sandwich(bone.boneOffset)
mutableInputSkeleton[bodyPart] = bone.copy(position = bone.position?.plus(localOffset))
}
}
}
@@ -1,51 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
/**
* Rotates the first Quaternion to match its roll to the rotation of
* the second Quaternion
*
* @param from the first Quaternion
* @param to the second Quaternion
* @return the rotated Quaternion
*/
private fun alignRoll(from: Quaternion, to: Quaternion): Quaternion {
val r = to.inv() * from
val c = Quaternion(r.w, 0f, -r.y, 0f)
return (to * r * c).unit()
}
/**
* Handles rotating the upper legs' roll to match the lower legs' roll.
*/
class UpperLegsRollAlignInputProcessor(val settings: Settings) : SkeletonInputProcessor {
/**
* First value is the BodyPart to be aligned.
*
* Second value is a source BodyPart
*/
private val bodyPartToSources = arrayOf(
BodyPart.LEFT_UPPER_LEG to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_LOWER_LEG,
)
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs
if (ratio == 0f) return
// Upper legs are written, lower legs are read, so the two never overlap
for (bodyPartToSource in bodyPartToSources) {
val bone = mutableInputSkeleton[bodyPartToSource.first] ?: continue
if (!bone.isRotationActive) continue
val sourceRotation = mutableInputSkeleton[bodyPartToSource.second]?.rotation ?: continue
val alignedRotation = alignRoll(bone.rotation, sourceRotation)
mutableInputSkeleton[bodyPartToSource.first] = bone.copy(rotation = bone.rotation.interpR(alignedRotation, ratio))
}
}
}
@@ -4,12 +4,12 @@ import dev.slimevr.Phase1ContextProvider
import dev.slimevr.config.Settings
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.skeleton.computedprocessors.UpperLegsTwistComputedProcessor
import dev.slimevr.skeleton.computedprocessors.VelocityComputedProcessor
import dev.slimevr.skeleton.fkprocessors.FootPlantFkProcessor
import dev.slimevr.skeleton.fkprocessors.LocalizerFkProcessor
import dev.slimevr.skeleton.fkprocessors.ToeSnapFkProcessor
import dev.slimevr.skeleton.inputprocessors.ArmsInputProcessor
import dev.slimevr.skeleton.inputprocessors.BoneOffsetInputProcessor
import dev.slimevr.skeleton.inputprocessors.ConstraintInputProcessor
import dev.slimevr.skeleton.inputprocessors.DirectLinkInputProcessor
import dev.slimevr.skeleton.inputprocessors.FallbackInputProcessor
@@ -19,7 +19,6 @@ import dev.slimevr.skeleton.inputprocessors.HeadPositionFallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.NeckInputProcessor
import dev.slimevr.skeleton.inputprocessors.SpineInputProcessor
import dev.slimevr.skeleton.inputprocessors.ToesInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor
import dev.slimevr.skeleton.targetprocessors.FloorClipTargetProcessor
import dev.slimevr.skeleton.targetprocessors.PositionalTargetProcessor
import dev.slimevr.skeleton.targetprocessors.SkatingCorrectionTargetProcessor
@@ -48,7 +47,6 @@ data class BoneInput(
val bodyPart: BodyPart,
val headOffset: Vector3,
val offset: Vector3,
val boneOffset: Vector3,
val poseTime: ComparableTimeMark?,
val rotation: Quaternion,
val acceleration: Vector3,
@@ -64,7 +62,6 @@ data class BoneState(
val bodyPart: BodyPart,
val headOffset: Vector3,
val offset: Vector3,
val boneOffset: Vector3,
val rotation: Quaternion,
val acceleration: Vector3,
val headPosition: Vector3,
@@ -114,7 +111,6 @@ val DEFAULT_BONE_INPUT = BoneInput(
bodyPart = BodyPart.NONE,
headOffset = Vector3.ZERO,
offset = Vector3.ZERO,
boneOffset = Vector3.ZERO,
poseTime = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
@@ -155,7 +151,6 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO
bodyPart = bone.bodyPart,
headOffset = bone.headOffset,
offset = bone.offset,
boneOffset = bone.boneOffset,
rotation = bone.rotation,
acceleration = bone.acceleration,
headPosition = headPosition,
@@ -181,7 +176,6 @@ fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton,
sealed interface SkeletonActions {
data class SetBonePose(
val bodyPart: BodyPart,
val boneOffset: Vector3?,
val rotation: Quaternion?,
val acceleration: Vector3?,
val position: Vector3?,
@@ -275,7 +269,6 @@ class Skeleton(
// Run before FK on the inputs
inputProcessors = listOf(
FilteringInputProcessor(settings),
BoneOffsetInputProcessor(),
HeadPositionFallbackInputProcessor(),
FallbackInputProcessor(),
SpineInputProcessor(settings),
@@ -285,7 +278,6 @@ class Skeleton(
FingersInputProcessor(),
ToesInputProcessor(),
ConstraintInputProcessor(settings),
UpperLegsRollAlignInputProcessor(settings),
),
// Run on the result of FK and persist
fkComputedProcessors = listOf(
@@ -305,6 +297,7 @@ class Skeleton(
),
// Run on the result of IK and persist.
ikComputedProcessors = listOf(
UpperLegsTwistComputedProcessor(settings),
VelocityComputedProcessor(),
),
),
@@ -11,7 +11,6 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
state.copy(
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = action.boneOffset ?: bone.boneOffset,
poseTime = timeSource.markNow(),
rotation = action.rotation ?: bone.rotation,
acceleration = action.acceleration ?: bone.acceleration,
@@ -29,7 +28,6 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
state.copy(
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = Vector3.ZERO,
poseTime = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
@@ -82,10 +80,7 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
is SkeletonActions.ResetFloorLevel -> {
val skeletonHeight = state.skeletonHeight
val headHeight = state.boneInputs[BodyPart.HEAD]?.let {
val headOffset = it.rotation.sandwich(it.boneOffset).y
it.position?.y?.plus(headOffset)
} ?: skeletonHeight
val headHeight = state.boneInputs[BodyPart.HEAD]?.position?.y ?: skeletonHeight
state.copy(floorLevel = headHeight - skeletonHeight)
}
@@ -43,7 +43,7 @@ class PositionalTargetProcessor(
for ((bodyPart, target) in bodyParts) {
// TODO Use active rotations as IK constraints instead and fill in the blanks
// Disable if you have arm trackers
if (requiredInactive[bodyPart]?.any { inputSkeleton[it]?.isRotationActive == true } == true) return
if (requiredInactive[bodyPart]?.any { inputSkeleton[it]?.isRotationActive == true } == true) continue
mutableIkTargets[target] = inputSkeleton[bodyPart]?.position ?: continue
}
@@ -310,10 +310,8 @@ class SkatingCorrectionTargetProcessor(val settings: Settings, val skeleton: Ske
}
override fun reset(resetType: ResetType) {
if (resetType == ResetType.FULL) {
lastProcessTime = timeSource.markNow()
lockState.clear()
releaseSmoothing.clear()
}
lastProcessTime = timeSource.markNow()
lockState.clear()
releaseSmoothing.clear()
}
}
@@ -54,7 +54,7 @@ private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMas
trackerId = tracker.id.toUShort(),
status = if (trackerMask.status) tracker.status else TrackerStatus.NONE,
rotation = if (trackerMask.rotation) tracker.rawRotation.toQuat() else null,
position = if (trackerMask.position && tracker.position != null) tracker.position.toVec3f() else null,
position = if (trackerMask.position && tracker.rawPosition != null) tracker.rawPosition.toVec3f() else null,
info = if (trackerMask.info) {
TrackerInfo(
isImu = tracker.imuType != null,
@@ -67,7 +67,6 @@ private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMas
customName = tracker.customName,
lastMountingMethod = tracker.lastMountingMethod,
magnetometer = tracker.magStatus,
dataType = tracker.trackerDataType,
boneOffset = (tracker.boneOffsets[tracker.bodyPart] ?: Vector3.ZERO).toVec3f(),
)
} else {
@@ -11,6 +11,7 @@ import dev.slimevr.solarxr.toQuaternion
import dev.slimevr.solarxr.toVector3
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.driverTrackerHardwareId
import dev.slimevr.util.inFloatingSeconds
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
@@ -100,9 +101,10 @@ class DriverIncomingTrackersBehaviour(
return@onDriverMessage
}
val hardwareId = req.hardwareIdentifier
val trackerHardwareId = driverTrackerHardwareId(hardwareId)
val existing = server.context.state.value.trackers.values
.find { it.context.state.value.hardwareId == hardwareId }
.find { it.context.state.value.hardwareId == trackerHardwareId }
if (existing != null) {
val trackerState = existing.context.state.value
// Tracker is in use by another driver right now
@@ -149,7 +151,7 @@ class DriverIncomingTrackersBehaviour(
intendedBodyPart = req.bodyPart,
intendedBoneOffset = offset?.boneOffset,
deviceId = deviceId,
hardwareId = hardwareId,
hardwareId = trackerHardwareId,
origin = DeviceOrigin.DRIVER,
driverName = driverName,
appContext = appContext,
@@ -189,8 +191,8 @@ class DriverIncomingTrackersBehaviour(
val trackerId = event.trackerId.toInt()
if (trackerId == 0) return@on
// Map velocity to accel
val acceleration = event.linearVelocity?.let { velocity ->
// use linear acceleration if available, otherwise use calculated acceleration from velocity
val acceleration = event.linearAcceleration?.toVector3() ?: event.linearVelocity?.let { velocity ->
val now = timeSource.markNow()
val velocity = velocity.toVector3()
val lastVelocity = lastVelocities[trackerId]
@@ -36,9 +36,9 @@ import dev.slimevr.solarxr.rpc.SettingsResetBehaviour
import dev.slimevr.solarxr.rpc.SkeletonProportionsBehaviour
import dev.slimevr.solarxr.rpc.SkeletonSettingsBehaviour
import dev.slimevr.solarxr.rpc.StayAlignedBehaviour
import dev.slimevr.solarxr.rpc.TapDetectionBehaviour
import dev.slimevr.solarxr.rpc.TelemetryBehaviour
import dev.slimevr.solarxr.rpc.TimeoutSettingsBehaviour
import dev.slimevr.solarxr.rpc.TrackerActionBehaviour
import dev.slimevr.solarxr.rpc.TrackerImuTelemetryBehaviour
import dev.slimevr.solarxr.rpc.TrackingChecklistBehaviour
import dev.slimevr.solarxr.rpc.UpdateTrackerBehaviour
@@ -190,7 +190,7 @@ class SolarXRBridge(
)
}
add(ResetsBehaviour(appContext.config.settings))
add(TapDetectionBehaviour(appContext.config.settings, appContext.tapDetectionManager))
add(TrackerActionBehaviour(appContext.config.settings, appContext.trackerActionManager))
add(VrcOscBehaviour(appContext.config.settings, appContext.vrcOscManager))
add(VmcBehaviour(appContext.config.settings, appContext.vmcManager))
add(HeightCalibrationBehaviour(appContext.heightCalibrationManager))
@@ -21,7 +21,7 @@ private fun buildSettingsDefaultsResponse(): SettingsDefaultsResponse {
skeleton = buildSkeletonSettingsResponse(settings.skeletonConfig),
resets = buildResetsSettingsResponse(settings.resetsConfig),
stayAligned = buildStayAlignedSettingsResponse(settings.stayAlignedConfig, user),
tapDetection = buildTapDetectionSettingsResponse(settings.tapDetectionConfig),
trackerAction = buildTrackerActionSettingsResponse(settings.trackerActionConfig),
timeout = buildTimeoutSettingsResponse(settings.trackersConfig),
hid = buildHidSettingsResponse(settings.hidConfig),
driver = buildDriverSettingsResponse(settings.driverConfig),
@@ -1,5 +1,6 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.config.MIN_USER_HEIGHT
import dev.slimevr.config.UserConfig
import dev.slimevr.config.UserConfigActions
import dev.slimevr.config.withDefaultProportions
@@ -29,8 +30,6 @@ import solarxr_protocol.rpc.SkeletonProportionsRequest
import solarxr_protocol.rpc.SkeletonProportionsResetAllRequest
import solarxr_protocol.rpc.SkeletonProportionsResponse
private const val MIN_HEIGHT = 0.9f
class SkeletonProportionsBehaviour(
private val userConfig: UserConfig,
private val skeleton: Skeleton,
@@ -70,7 +69,7 @@ class SkeletonProportionsBehaviour(
val headHeight = req.headHeight ?: return@on
val floorHeight = req.floorHeight ?: 0f
val height = headHeight - floorHeight
if (height >= MIN_HEIGHT) {
if (height >= MIN_USER_HEIGHT) {
userConfig.context.dispatch(
UserConfigActions.Update { withUserHeight(this, height) },
)
@@ -80,7 +79,7 @@ class SkeletonProportionsBehaviour(
receiver.rpcDispatcher.on<SkeletonProportionsResetAllRequest> {
val height = userConfig.context.state.value.data.userHeight
if (height >= MIN_HEIGHT) {
if (height >= MIN_USER_HEIGHT) {
userConfig.context.dispatch(UserConfigActions.Update { withDefaultProportions(this) })
}
}.launchIn(receiver.context.scope)
@@ -2,74 +2,95 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsActions
import dev.slimevr.config.TapDetectionConfig
import dev.slimevr.config.TrackerActionConfig
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.tapdetection.TapDetectionActions
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionActions
import dev.slimevr.trackeraction.TrackerActionManager
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.rpc.ChangeTapDetectionSettingsRequest
import solarxr_protocol.rpc.TapDetectionSettingsRequest
import solarxr_protocol.rpc.TapDetectionSettingsResponse
import solarxr_protocol.rpc.TapDetectionSetupModeRequest
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.rpc.ChangeTrackerActionSettingsRequest
import solarxr_protocol.rpc.TrackerActionSettings
import solarxr_protocol.rpc.TrackerActionSettingsRequest
import solarxr_protocol.rpc.TrackerActionSettingsResponse
import solarxr_protocol.rpc.TrackerActionSetupModeRequest
internal fun buildTapDetectionSettingsResponse(config: TapDetectionConfig) = TapDetectionSettingsResponse(
yawResetDelay = config.yawResetDelay,
fullResetDelay = config.fullResetDelay,
mountingResetDelay = config.mountingResetDelay,
yawResetEnabled = config.yawResetEnabled,
fullResetEnabled = config.fullResetEnabled,
mountingResetEnabled = config.mountingResetEnabled,
yawResetTaps = config.yawResetTaps.toUByte(),
fullResetTaps = config.fullResetTaps.toUByte(),
mountingResetTaps = config.mountingResetTaps.toUByte(),
yawResetTracker = config.yawResetBodyPart,
fullResetTracker = config.fullResetBodyPart,
mountingResetTracker = config.mountingResetBodyPart,
numberTrackersOverThreshold = config.numberTrackersOverThreshold.toUByte(),
internal fun buildTrackerActionSettingsResponse(config: TrackerActionConfig) = TrackerActionSettingsResponse(
yawResetAction = TrackerActionSettings(
enabled = config.yawResetAction.enabled,
delay = config.yawResetAction.delay,
bodyPart = config.yawResetAction.bodyPart ?: BodyPart.NONE,
method = config.yawResetAction.method,
taps = config.yawResetAction.taps.toUByte(),
),
fullResetAction = TrackerActionSettings(
enabled = config.fullResetAction.enabled,
delay = config.fullResetAction.delay,
bodyPart = config.fullResetAction.bodyPart ?: BodyPart.NONE,
method = config.fullResetAction.method,
taps = config.fullResetAction.taps.toUByte(),
),
mountingResetAction = TrackerActionSettings(
enabled = config.mountingResetAction.enabled,
delay = config.mountingResetAction.delay,
bodyPart = config.mountingResetAction.bodyPart ?: BodyPart.NONE,
method = config.mountingResetAction.method,
taps = config.mountingResetAction.taps.toUByte(),
),
tapsTrackersOverThreshold = config.tapsTrackersOverThreshold.toUByte(),
)
class TapDetectionBehaviour(
class TrackerActionBehaviour(
private val settings: Settings,
private val tapDetectionManager: TapDetectionManager,
private val trackerActionManager: TrackerActionManager,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
// Send config
receiver.onRpc<TapDetectionSettingsRequest> { _, txId ->
receiver.sendRpc(buildTapDetectionSettingsResponse(settings.context.state.value.data.tapDetectionConfig), txId)
receiver.onRpc<TrackerActionSettingsRequest> { _, txId ->
receiver.sendRpc(buildTrackerActionSettingsResponse(settings.context.state.value.data.trackerActionConfig), txId)
}.launchIn(receiver.context.scope)
// Push config changes, including profile switches
settings.context.state
.map { buildTapDetectionSettingsResponse(it.data.tapDetectionConfig) }
.map { buildTrackerActionSettingsResponse(it.data.trackerActionConfig) }
.distinctUntilChanged()
.drop(1)
.onEach(receiver::sendRpc)
.launchIn(receiver.context.scope)
// Receive config
receiver.rpcDispatcher.on<ChangeTapDetectionSettingsRequest> { req ->
receiver.rpcDispatcher.on<ChangeTrackerActionSettingsRequest> { req ->
settings.context.dispatch(
SettingsActions.Update {
copy(
tapDetectionConfig = TapDetectionConfig(
yawResetDelay = req.yawResetDelay ?: 0f,
fullResetDelay = req.fullResetDelay ?: 0f,
mountingResetDelay = req.mountingResetDelay ?: 0f,
yawResetEnabled = req.yawResetEnabled == true,
fullResetEnabled = req.fullResetEnabled == true,
mountingResetEnabled = req.mountingResetEnabled == true,
yawResetTaps = req.yawResetTaps?.toInt() ?: 2,
fullResetTaps = req.fullResetTaps?.toInt() ?: 2,
mountingResetTaps = req.mountingResetTaps?.toInt() ?: 2,
yawResetBodyPart = req.yawResetTracker,
fullResetBodyPart = req.fullResetTracker,
mountingResetBodyPart = req.mountingResetTracker,
numberTrackersOverThreshold = req.numberTrackersOverThreshold?.toInt() ?: 1,
trackerActionConfig = TrackerActionConfig(
yawResetAction = dev.slimevr.config.TrackerActionSettings(
enabled = req.yawResetAction?.enabled == true,
delay = req.yawResetAction?.delay ?: 0f,
bodyPart = req.yawResetAction?.bodyPart,
method = req.yawResetAction?.method ?: TrackerActionMethod.TAP,
taps = req.yawResetAction?.taps?.toInt() ?: 2,
),
fullResetAction = dev.slimevr.config.TrackerActionSettings(
enabled = req.fullResetAction?.enabled == true,
delay = req.fullResetAction?.delay ?: 0f,
bodyPart = req.fullResetAction?.bodyPart,
method = req.fullResetAction?.method ?: TrackerActionMethod.TAP,
taps = req.fullResetAction?.taps?.toInt() ?: 2,
),
mountingResetAction = dev.slimevr.config.TrackerActionSettings(
enabled = req.mountingResetAction?.enabled == true,
delay = req.mountingResetAction?.delay ?: 0f,
bodyPart = req.mountingResetAction?.bodyPart,
method = req.mountingResetAction?.method ?: TrackerActionMethod.TAP,
taps = req.mountingResetAction?.taps?.toInt() ?: 2,
),
tapsTrackersOverThreshold = req.tapsTrackersOverThreshold.toInt(),
),
)
},
@@ -77,8 +98,8 @@ class TapDetectionBehaviour(
}.launchIn(receiver.context.scope)
// Setup Mode (tap/button press to assign)
receiver.rpcDispatcher.on<TapDetectionSetupModeRequest> { req ->
tapDetectionManager.context.dispatch(TapDetectionActions.SetSetupMode(req.setupMode == true))
receiver.rpcDispatcher.on<TrackerActionSetupModeRequest> { req ->
trackerActionManager.context.dispatch(TrackerActionActions.SetSetupMode(req.setupMode))
}.launchIn(receiver.context.scope)
}
}
@@ -8,7 +8,7 @@ import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.solarxr.toVector3
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ResetTrackerAssignments
@@ -31,7 +31,7 @@ class UpdateTrackerBehaviour(
val state = it.context.state.value
it != tracker &&
state.bodyPart == bodyPart &&
state.status.isActive()
isPresent(state.status)
}.forEach {
it.context.dispatch(
TrackerActions.Update { copy(bodyPart = null) },
@@ -1,76 +0,0 @@
package dev.slimevr.tapdetection
import dev.slimevr.Phase1ContextProvider
import dev.slimevr.VRServer
import dev.slimevr.config.Settings
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.resets.ResetsManager
import dev.slimevr.tracker.Tracker
import kotlinx.coroutines.CoroutineScope
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.TapDetectionSetupNotification
import kotlin.collections.listOf
data class TapDetectionState(
val setupMode: Boolean = false,
val yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST,
val fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG,
val mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG,
)
sealed interface TapDetectionActions {
data class SetSetupMode(val setupMode: Boolean) : TapDetectionActions
data class UpdateBodyParts(val yawResetBodyPart: BodyPart?, val fullResetBodyPart: BodyPart?, val mountingResetBodyPart: BodyPart?) : TapDetectionActions
}
typealias TapDetectionContext = Context<TapDetectionState, TapDetectionActions>
typealias TapDetectionBehaviour = Behaviour<TapDetectionManager>
class TapDetectionManager(val context: TapDetectionContext, val server: VRServer, val resetsManager: ResetsManager, val settings: Settings) {
fun startObserving() = context.observeAll(this)
suspend fun actionTriggered(trackerId: Int, sourceName: String = "TapDetection") {
val tracker = server.getTracker(trackerId) ?: return
val state = context.state.value
// If it's in setup mode, tap/button press to assign
if (state.setupMode) {
server.sendSolarxrRpc(
TapDetectionSetupNotification(
trackerId.toUShort(),
),
)
return
}
val bodyPart = tracker.context.state.value.bodyPart ?: return
val tapDetectionConfig = settings.context.state.value.data.tapDetectionConfig
val (resetType, actionDelay) = when (bodyPart) {
state.yawResetBodyPart if tapDetectionConfig.yawResetEnabled -> ResetType.YAW to tapDetectionConfig.yawResetDelay
state.fullResetBodyPart if tapDetectionConfig.fullResetEnabled -> ResetType.FULL to tapDetectionConfig.fullResetDelay
state.mountingResetBodyPart if tapDetectionConfig.mountingResetEnabled -> ResetType.MOUNTING to tapDetectionConfig.mountingResetDelay
else -> return
}
resetsManager.scheduleReset(
sourceName,
resetType,
actionDelay,
)
}
companion object {
fun create(ctx: Phase1ContextProvider, resetsManager: ResetsManager, scope: CoroutineScope): TapDetectionManager {
val context = Context.create(
initialState = TapDetectionState(),
scope = scope,
reducer = ::reduce,
behaviours = listOf(TapDetectionBasicBehaviour()),
name = "TapDetectionManager",
)
return TapDetectionManager(context, ctx.server, resetsManager, ctx.config.settings)
}
}
}
@@ -1,6 +0,0 @@
package dev.slimevr.tapdetection
fun reduce(state: TapDetectionState, action: TapDetectionActions): TapDetectionState = when (action) {
is TapDetectionActions.SetSetupMode -> state.copy(setupMode = action.setupMode)
is TapDetectionActions.UpdateBodyParts -> state.copy(yawResetBodyPart = action.yawResetBodyPart, fullResetBodyPart = action.fullResetBodyPart, mountingResetBodyPart = action.mountingResetBodyPart)
}
@@ -3,7 +3,7 @@ package dev.slimevr.tracker.behaviours
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
@@ -15,13 +15,13 @@ class TrackerAssignmentConflictBehaviour : TrackerBehaviour {
override fun observe(receiver: Tracker) {
val server = receiver.appContext.server
receiver.context.state
.distinctUntilChanged { old, new -> old.status.isActive() == new.status.isActive() }
.distinctUntilChanged { old, new -> isPresent(old.status) == isPresent(new.status) }
.onEach { state ->
val bodyPart = state.bodyPart ?: return@onEach
val bodyPartTaken = server.context.state.value.trackers.values.any { other ->
val otherState = other.context.state.value
otherState.id != state.id && otherState.bodyPart == bodyPart && otherState.status.isActive()
otherState.id != state.id && otherState.bodyPart == bodyPart && isPresent(otherState.status)
}
if (bodyPartTaken) {
receiver.context.dispatch(TrackerActions.Update { copy(bodyPart = null) })
@@ -17,7 +17,7 @@ import kotlin.time.Duration.Companion.seconds
/**
* Detects whether a tracker is at rest or rotating.
* Used for Stay Aligned and TapDetection.
* Used for Stay Aligned.
*/
class TrackerMotionDetectionBehaviour : TrackerBehaviour {
@@ -79,8 +79,6 @@ class TrackerMotionDetectionBehaviour : TrackerBehaviour {
*/
private fun isRotating(lastRotation: RawRotation, rotation: RawRotation) = Angle.absBetween(lastRotation, rotation) > MAX_ROTATION
// TODO : these values may need fine-tuning for TapDetection
// or maybe need multiple motion detector with an abstract class
companion object {
val MAX_ROTATION = Angle.ofDeg(2f)
val ENTER_REST_TIME = 1.seconds
@@ -3,14 +3,13 @@ package dev.slimevr.tracker.behaviours
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerStatus
/**
* Marks the calibration stale when the tracker starts being used on a body part: when it connects
@@ -24,7 +23,7 @@ class TrackerStaleCalibrationBehaviour : TrackerBehaviour {
override fun observe(receiver: Tracker) {
var previous: Placement? = null
receiver.context.state
.map { Placement(it.status.isActive() || it.status == TrackerStatus.OCCLUDED, it.bodyPart) }
.map { Placement(isPresent(it.status), it.bodyPart) }
.distinctUntilChanged()
.onEach { placement ->
val last = previous
@@ -63,8 +63,6 @@ class TrackerStayAlignedBehaviour(
*/
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeRun(receiver: Tracker) {
var lastRotationTime = timeSource.markNow()
val serverFlow = receiver.appContext.server.context.state
val enabledFlow = settings.context.state.map { it.data.stayAlignedConfig.enabled }.distinctUntilChanged()
@@ -76,6 +74,7 @@ class TrackerStayAlignedBehaviour(
// Ignore every other emission for performance (50FPS instead of 100FPS when at 100TPS)
var index = 0
var lastRotationTime = timeSource.markNow()
receiver.context.state
.distinctUntilChangedBy { it.rawRotation }
.filter { index++ % 2 == 0 }
@@ -5,6 +5,7 @@ import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -13,7 +14,6 @@ import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerStatus
class TrackerToSkeletonBehaviour : TrackerBehaviour {
var lastBodyPartSent: BodyPart? = null
@@ -26,7 +26,7 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
// Tell the skeleton the tracker has stopped sending data to the last bone it was sending data to.
lastBodyPartSent?.let {
val trackerState = receiver.context.state.value
if ((!trackerState.status.isActive() && trackerState.status != TrackerStatus.OCCLUDED) || trackerState.bodyPart != lastBodyPartSent) {
if (!isPresent(trackerState.status) || trackerState.bodyPart != lastBodyPartSent) {
receiver.appContext.skeleton.context.dispatch(
SkeletonActions.DisableBone(it),
)
@@ -46,7 +46,6 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
val pendingResets = trackerState.pendingSkeletonResets
val bonePoseActions = SkeletonActions.SetBonePose(
bodyPart,
trackerState.boneOffsets[bodyPart],
trackerState.rotation,
trackerState.acceleration,
trackerState.position,
@@ -0,0 +1,7 @@
package dev.slimevr.tracker
fun udpTrackerHardwareId(deviceHardwareId: String, sensorId: Int): String = "udp:$deviceHardwareId:$sensorId"
fun hidTrackerHardwareId(address: String): String = "hid:$address"
fun driverTrackerHardwareId(hardwareIdentifier: String): String = "driver:$hardwareIdentifier"
@@ -27,11 +27,10 @@ import solarxr_protocol.datatypes.MagnetometerStatus
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
import solarxr_protocol.datatypes.hardware_info.TrackerDataType
import solarxr_protocol.rpc.ResetType
import kotlin.time.Duration
// A tracker is initialized as ROTATING to prevent TapDetection and Stay Aligned from running immediately.
// A tracker is initialized as ROTATING to prevent Stay Aligned from running immediately.
enum class Motion {
ROTATING,
RESTING,
@@ -66,7 +65,6 @@ data class TrackerState(
val intendedBodyPart: BodyPart?,
val boneOffsets: Map<BodyPart, Vector3>,
val customName: String?,
val trackerDataType: TrackerDataType, // TODO flex sensors
val lastMountingMethod: MountingMethod,
val mountingOrientation: HeadingAlignment,
val lastReference: Quaternion?,
@@ -77,6 +75,7 @@ data class TrackerState(
val rawAcceleration: RawAcceleration?,
val acceleration: CalibratedAcceleration?,
val rawMagnetometer: Vector3,
val rawPosition: Vector3?,
val position: Vector3?,
val imuTemp: Float?,
val accumulatedTicks: UShort,
@@ -209,7 +208,6 @@ class Tracker(
intendedBodyPart = null,
boneOffsets = emptyMap(),
customName = null,
trackerDataType = TrackerDataType.ROTATION,
lastMountingMethod = MountingMethod.MANUAL,
mountingOrientation = Quaternion.IDENTITY,
lastReference = Quaternion.IDENTITY,
@@ -220,6 +218,7 @@ class Tracker(
rawAcceleration = null,
acceleration = null,
rawMagnetometer = Vector3.ZERO,
rawPosition = null,
position = null,
imuTemp = null,
accumulatedTicks = 0u,
@@ -38,7 +38,7 @@ fun reduce(
// Other inputs
val rawAcceleration: RawAcceleration? = action.acceleration ?: state.rawAcceleration
val rawMagnetometer = action.magnetometer ?: state.rawMagnetometer
val position = action.position ?: state.position
val rawPosition = action.position ?: state.rawPosition
// Rotation calibration: going from raw rotation to rotation since reset
val rotation: CalibratedRotation =
@@ -67,12 +67,25 @@ fun reduce(
state.acceleration
}
val position =
if (action.position != null) {
val boneOffset = state.boneOffsets[state.bodyPart]
if (boneOffset != null) {
action.position + rotation.sandwich(boneOffset)
} else {
action.position
}
} else {
state.position
}
state.copy(
rawRotation = rawRotation,
rotation = rotation,
rawAcceleration = rawAcceleration,
acceleration = acceleration,
rawMagnetometer = rawMagnetometer,
rawPosition = rawPosition,
position = position,
accumulatedTicks = accumulatedTicks,
rotationDirty = false,
@@ -252,6 +265,7 @@ fun reduce(
state.copy(
sessionCalibration = state.sessionCalibration.copy(headingCorrection = action.heading),
yawResetSmoothing = if (action.done) null else state.yawResetSmoothing,
pendingSkeletonResets = if (action.done) state.pendingSkeletonResets + ResetType.YAW else state.pendingSkeletonResets,
rotationDirty = true,
)
}
@@ -32,22 +32,24 @@ object StayAlignedDefaults {
val IMU_TO_YAW_CORRECTION = buildMap {
// Mag is enabled on MPU9250 but server doesn't know about it
set(ImuType.MPU9250, YAW_CORRECTION_IMU_DISABLED)
set(ImuType.MPU6050, YAW_CORRECTION_IMU_BAD)
set(ImuType.MPU6500, YAW_CORRECTION_IMU_BAD)
set(ImuType.BNO055, YAW_CORRECTION_IMU_BAD)
set(ImuType.BMI160, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM20948, YAW_CORRECTION_IMU_BAD)
set(ImuType.LSM6DS3TRC, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM42688, YAW_CORRECTION_IMU_OK)
set(ImuType.BMI270, YAW_CORRECTION_IMU_OK)
set(ImuType.LSM6DSO, YAW_CORRECTION_IMU_OK)
set(ImuType.BNO080, YAW_CORRECTION_IMU_GOOD)
set(ImuType.BNO085, YAW_CORRECTION_IMU_GOOD)
set(ImuType.BNO055, YAW_CORRECTION_IMU_BAD)
set(ImuType.MPU6050, YAW_CORRECTION_IMU_BAD)
set(ImuType.BNO086, YAW_CORRECTION_IMU_GOOD)
set(ImuType.BMI160, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM20948, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM42688, YAW_CORRECTION_IMU_OK)
set(ImuType.BMI270, YAW_CORRECTION_IMU_OK)
set(ImuType.LSM6DS3TRC, YAW_CORRECTION_IMU_BAD)
set(ImuType.LSM6DSV, YAW_CORRECTION_IMU_GOOD)
set(ImuType.LSM6DSO, YAW_CORRECTION_IMU_OK)
set(ImuType.LSM6DSR, YAW_CORRECTION_IMU_GOOD)
set(ImuType.ICM45686, YAW_CORRECTION_IMU_GOOD)
set(ImuType.ICM45605, YAW_CORRECTION_IMU_GOOD)
// ADC_RESISTANCE is a flex sensor so it has no yaw drift
set(ImuType.ADC_RESISTANCE, YAW_CORRECTION_IMU_DISABLED)
set(ImuType.ICM55686, YAW_CORRECTION_IMU_GOOD)
}
@@ -1,6 +1,6 @@
package dev.slimevr.tapdetection
package dev.slimevr.trackeraction
import dev.slimevr.config.TapDetectionConfig
import dev.slimevr.config.TrackerActionConfig
import dev.slimevr.tracker.TrackerState
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Vector3
@@ -13,16 +13,14 @@ import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.TapDetectionSetupNotification
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeMark
class TapDetectionBasicBehaviour : TapDetectionBehaviour {
class TapDetectionBehaviour : TrackerActionBehaviour {
data class TrackerTapDetectionState(
var trackerId: Int,
var performsReset: Boolean = false,
@@ -34,8 +32,8 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
// Loads TapDetection config and initializes a tracker's state
private fun createTrackerTapDetectionState(
tapDetectionConfig: TapDetectionConfig,
tapDetectionState: TapDetectionState,
tapDetectionConfig: TrackerActionConfig,
tapDetectionState: TrackerActionState,
trackerState: TrackerState,
): TrackerTapDetectionState {
// This holds a tracker's config and state for tap detection
@@ -44,19 +42,19 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
// setupMode uses defaults
if (!tapDetectionState.setupMode) {
when (trackerState.bodyPart) {
tapDetectionState.yawResetBodyPart if tapDetectionConfig.yawResetEnabled -> {
tapDetectionState.yawResetBodyPart if tapDetectionConfig.yawResetAction.enabled -> {
trackerTapDetectionState.performsReset = true
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.yawResetTaps
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.yawResetAction.taps
}
tapDetectionState.fullResetBodyPart if tapDetectionConfig.fullResetEnabled -> {
tapDetectionState.fullResetBodyPart if tapDetectionConfig.fullResetAction.enabled -> {
trackerTapDetectionState.performsReset = true
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.fullResetTaps
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.fullResetAction.taps
}
tapDetectionState.mountingResetBodyPart if tapDetectionConfig.mountingResetEnabled -> {
tapDetectionState.mountingResetBodyPart if tapDetectionConfig.mountingResetAction.enabled -> {
trackerTapDetectionState.performsReset = true
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.mountingResetTaps
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.mountingResetAction.taps
}
else -> {}
@@ -82,9 +80,9 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
)
@OptIn(ExperimentalCoroutinesApi::class)
override fun observe(receiver: TapDetectionManager) {
override fun observe(receiver: TrackerActionManager) {
val tapConfigFlow = receiver.settings.context.state
.map { it.data.tapDetectionConfig }
.map { it.data.trackerActionConfig }
.distinctUntilChanged()
val setupModeFlow = receiver.context.state
.map { it.setupMode }
@@ -110,19 +108,19 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
combine(tapConfigFlow, setupModeFlow, okTrackersFlow, ::Triple).onEach { (tapDetectionConfig, setupMode, trackers) ->
if (setupMode) {
receiver.context.dispatch(TapDetectionActions.UpdateBodyParts(null, null, null))
receiver.context.dispatch(TrackerActionActions.UpdateBodyParts(null, null, null))
return@onEach
}
val trackersBodyParts = trackers.map { it.context.state.value.bodyPart }.toSet()
val yawResetBodyPart = arrayOf(tapDetectionConfig.yawResetBodyPart, BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.HIP, BodyPart.LOWER_WAIST, BodyPart.UPPER_WAIST)
val yawResetBodyPart = arrayOf(tapDetectionConfig.yawResetAction.bodyPart, BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.HIP, BodyPart.UPPER_WAIST, BodyPart.LOWER_WAIST)
.firstOrNull { it in trackersBodyParts } ?: BodyPart.UPPER_CHEST
val fullResetBodyPart = arrayOf(tapDetectionConfig.fullResetBodyPart, BodyPart.LEFT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG)
val fullResetBodyPart = arrayOf(tapDetectionConfig.fullResetAction.bodyPart, BodyPart.LEFT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG)
.firstOrNull { it in trackersBodyParts } ?: BodyPart.LEFT_UPPER_LEG
val mountingResetBodyPart = arrayOf(tapDetectionConfig.mountingResetBodyPart, BodyPart.RIGHT_UPPER_LEG, BodyPart.RIGHT_LOWER_LEG)
val mountingResetBodyPart = arrayOf(tapDetectionConfig.mountingResetAction.bodyPart, BodyPart.RIGHT_UPPER_LEG, BodyPart.RIGHT_LOWER_LEG)
.firstOrNull { it in trackersBodyParts } ?: BodyPart.RIGHT_UPPER_LEG
receiver.context.dispatch(TapDetectionActions.UpdateBodyParts(yawResetBodyPart, fullResetBodyPart, mountingResetBodyPart))
receiver.context.dispatch(TrackerActionActions.UpdateBodyParts(yawResetBodyPart, fullResetBodyPart, mountingResetBodyPart))
}.launchIn(receiver.context.scope)
// Outer flow is refreshed whenever TapDetection config, setupMode, or a tracker's bodyPart or status changes
@@ -134,7 +132,7 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
)
.flatMapLatest { (tapDetectionConfig, tapDetectionState, trackers) ->
// To keep track of which trackers are moving
val numberTrackersOverThreshold = tapDetectionConfig.numberTrackersOverThreshold
val tapsTrackersOverThreshold = tapDetectionConfig.tapsTrackersOverThreshold
val bodyPartsToCheck = falsePositiveBodyParts + tapDetectionState.yawResetBodyPart + tapDetectionState.fullResetBodyPart + tapDetectionState.mountingResetBodyPart
val trackersOverThreshold = mutableSetOf<Int>()
@@ -169,14 +167,14 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
val othersOverThreshold = trackersOverThreshold.count() - if (isOverThreshold) 1 else 0
val tapTriggered = runTapDetection(
timeSource.markNow(),
othersOverThreshold >= numberTrackersOverThreshold,
othersOverThreshold >= tapsTrackersOverThreshold,
trackerTapDetectionState,
rawAcceleration,
thresholdMultiplier,
)
if (tapTriggered) {
receiver.actionTriggered(trackerTapDetectionState.trackerId)
receiver.actionTriggered(trackerTapDetectionState.trackerId, "TapDetection", TrackerActionMethod.TAP)
}
}
}
@@ -0,0 +1,83 @@
package dev.slimevr.trackeraction
import dev.slimevr.Phase1ContextProvider
import dev.slimevr.VRServer
import dev.slimevr.config.Settings
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.resets.ResetsManager
import kotlinx.coroutines.CoroutineScope
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.TrackerActionSetupNotification
import kotlin.collections.listOf
data class TrackerActionState(
val setupMode: Boolean = false,
val yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST,
val fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG,
val mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG,
)
sealed interface TrackerActionActions {
data class SetSetupMode(val setupMode: Boolean) : TrackerActionActions
data class UpdateBodyParts(val yawResetBodyPart: BodyPart?, val fullResetBodyPart: BodyPart?, val mountingResetBodyPart: BodyPart?) : TrackerActionActions
}
typealias TrackerActionContext = Context<TrackerActionState, TrackerActionActions>
typealias TrackerActionBehaviour = Behaviour<TrackerActionManager>
class TrackerActionManager(val context: TrackerActionContext, val server: VRServer, val resetsManager: ResetsManager, val settings: Settings) {
fun startObserving() = context.observeAll(this)
suspend fun actionTriggered(trackerId: Int, sourceName: String, sourceMethod: TrackerActionMethod) {
val tracker = server.getTracker(trackerId) ?: return
val state = context.state.value
// If it's in setup mode, tap/button press to assign
if (state.setupMode) {
server.sendSolarxrRpc(
TrackerActionSetupNotification(
trackerId.toUShort(),
),
)
return
}
val bodyPart = tracker.context.state.value.bodyPart ?: return
val trackerActionConfig = settings.context.state.value.data.trackerActionConfig
val (resetType, actionDelay) = when (bodyPart) {
state.yawResetBodyPart if trackerActionConfig.yawResetAction.enabled -> ResetType.YAW to trackerActionConfig.yawResetAction.delay
state.fullResetBodyPart if trackerActionConfig.fullResetAction.enabled -> ResetType.FULL to trackerActionConfig.fullResetAction.delay
state.mountingResetBodyPart if trackerActionConfig.mountingResetAction.enabled -> ResetType.MOUNTING to trackerActionConfig.mountingResetAction.delay
else -> return
}
val method = when (resetType) {
ResetType.YAW -> trackerActionConfig.yawResetAction.method
ResetType.FULL -> trackerActionConfig.fullResetAction.method
ResetType.MOUNTING -> trackerActionConfig.mountingResetAction.method
}
if (method == sourceMethod || method == TrackerActionMethod.BOTH) {
resetsManager.scheduleReset(
"TrackerAction ($sourceName)",
resetType,
actionDelay,
)
}
}
companion object {
fun create(ctx: Phase1ContextProvider, resetsManager: ResetsManager, scope: CoroutineScope): TrackerActionManager {
val context = Context.create(
initialState = TrackerActionState(),
scope = scope,
reducer = ::reduce,
behaviours = listOf(TapDetectionBehaviour()),
name = "TrackerActionManager",
)
return TrackerActionManager(context, ctx.server, resetsManager, ctx.config.settings)
}
}
}
@@ -0,0 +1,6 @@
package dev.slimevr.trackeraction
fun reduce(state: TrackerActionState, action: TrackerActionActions): TrackerActionState = when (action) {
is TrackerActionActions.SetSetupMode -> state.copy(setupMode = action.setupMode)
is TrackerActionActions.UpdateBodyParts -> state.copy(yawResetBodyPart = action.yawResetBodyPart, fullResetBodyPart = action.fullResetBodyPart, mountingResetBodyPart = action.mountingResetBodyPart)
}
@@ -7,6 +7,7 @@ import dev.slimevr.device.DeviceActions
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.udpTrackerHardwareId
import dev.slimevr.util.udpHardwareId
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
@@ -43,7 +44,7 @@ fun getCorrectedAcceleration(acceleration: Vector3, protocolVersion: Int) = if (
internal fun assignTracker(receiver: UDPConnection, device: Device, info: SensorInfo): Tracker {
val deviceState = device.context.state.value
val deviceHardwareId = deviceState.hardwareId ?: udpHardwareId(deviceState.macAddress, deviceState.address)
val hardwareId = "$deviceHardwareId:${info.sensorId}"
val hardwareId = udpTrackerHardwareId(deviceHardwareId, info.sensorId)
val existingTracker = receiver.appContext.server.context.state.value.trackers.values
.find { t -> t.context.state.value.deviceId == deviceState.id && t.context.state.value.hardwareId == hardwareId }
@@ -6,10 +6,9 @@ import dev.slimevr.config.DevicesConfigActions
import dev.slimevr.device.Device
import dev.slimevr.logging.AppLogger
import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import kotlinx.coroutines.cancel
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
private fun findUdpDevices(appContext: AppContextProvider, predicate: (String) -> Boolean): List<Device> = appContext.server.context.state.value.devices.values.filter { device ->
val state = device.context.state.value
@@ -35,7 +34,7 @@ fun removeUdpDevice(appContext: AppContextProvider, device: Device) {
// The tracker's own skeleton behaviour dies with its scope, so release its bone here
trackerStates
.filter { it.status.isActive() || it.status == TrackerStatus.OCCLUDED }
.filter { isPresent(it.status) }
.mapNotNull { it.bodyPart }
.forEach { bodyPart ->
appContext.skeleton.context.dispatch(SkeletonActions.DisableBone(bodyPart))
@@ -3,3 +3,6 @@ package dev.slimevr.util
import solarxr_protocol.datatypes.TrackerStatus
fun TrackerStatus.isActive() = this == TrackerStatus.OK || this == TrackerStatus.SLEEPING || this == TrackerStatus.TIMED_OUT
/** Active, or occluded and expected back. A present tracker keeps its bone and its body part. */
fun isPresent(status: TrackerStatus) = status.isActive() || status == TrackerStatus.OCCLUDED
@@ -123,6 +123,8 @@ class VRCOSCManager(
context.observeAll(this)
}
// TODO limit to once every 300ms to prevent lerping on VRChat's side
// https://docs.vrchat.com/docs/osc-trackers#receiving-head-data
fun yawAlign(referenceRotation: Quaternion) {
context.scope.launch {
events.emit(VRCOSCEvent.YawAlign(referenceRotation))
@@ -39,7 +39,6 @@ import dev.slimevr.skeleton.buildBones
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.stepmounting.StepMountingState
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.tracker.Motion
import dev.slimevr.tracker.SessionCalibration
import dev.slimevr.tracker.StayAlignedData
@@ -48,6 +47,7 @@ import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.tracker.behaviours.TrackerRotationRefreshBehaviour
import dev.slimevr.tracker.behaviours.TrackerStaleCalibrationBehaviour
import dev.slimevr.tracker.behaviours.TrackerTpsBehaviour
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpPeer
import dev.slimevr.udp.UdpServer
@@ -315,7 +315,7 @@ abstract class TestAppContext : AppContextProvider {
override val vmcManager: VMCManager get() = error("not used in test")
override val vrcOscManager: VRCOSCManager get() = error("not used in test")
override val resetsManager: ResetsManager get() = error("not used in test")
override val tapDetectionManager: TapDetectionManager get() = error("not used in test")
override val trackerActionManager: TrackerActionManager get() = error("not used in test")
override val boneRouting: BoneRoutingManager get() = error("not used in test")
override val stepMountingManager: StepMountingManager get() = error("not used in test")
override val logSources: List<LogSourceProvider> = emptyList()
@@ -0,0 +1,45 @@
package dev.slimevr.config
import kotlinx.coroutines.test.runTest
import solarxr_protocol.datatypes.BodyPart
import kotlin.test.Test
import kotlin.test.assertEquals
class DevicesConfigMigrationTest {
@Test
fun `version 1 tracker ids get the prefix of their origin`() = runTest {
val storage = MemoryStorage()
storage.files[DEVICES_CONFIG_PATH] = """
{
"version": 1,
"allowedUdpDevices": ["AA:BB:CC:DD:EE:01"],
"trackers": {
"AA:BB:CC:DD:EE:01:0": { "bodyPart": "HIP" },
"192.168.1.20:1": { "bodyPart": "LEFT_FOOT" },
"A1B2C3D4E5F6": { "bodyPart": "RIGHT_FOOT" },
"0000A1B2C3D4E5F6": { "bodyPart": "LEFT_HAND" },
"LHR-1A2B3C4D": { "bodyPart": "LOWER_CHEST" },
"vmc:tracker:abc": { "bodyPart": "HEAD" },
"vrcosc:vrsystem:head": { "bodyPart": "NECK" }
}
}
""".trimIndent()
val devices = AppConfig.create(backgroundScope, storage).devices.context.state.value
assertEquals(
mapOf(
"udp:AA:BB:CC:DD:EE:01:0" to BodyPart.HIP,
"udp:192.168.1.20:1" to BodyPart.LEFT_FOOT,
"hid:A1B2C3D4E5F6" to BodyPart.RIGHT_FOOT,
"hid:0000A1B2C3D4E5F6" to BodyPart.LEFT_HAND,
"driver:LHR-1A2B3C4D" to BodyPart.LOWER_CHEST,
"vmc:tracker:abc" to BodyPart.HEAD,
"vrcosc:vrsystem:head" to BodyPart.NECK,
),
devices.trackers.mapValues { it.value.bodyPart },
)
assertEquals(setOf("AA:BB:CC:DD:EE:01"), devices.allowedUdpDevices)
assertEquals(2, devices.version)
}
}
@@ -0,0 +1,304 @@
package dev.slimevr.config
import dev.slimevr.skeleton.computeAllDefaultProportionsByBone
import io.github.axisangles.ktmath.Quaternion
import kotlinx.coroutines.test.runTest
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.StayAlignedRelaxedPose
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
private val LEGACY_CONFIG = """
---
server:
trackerPort: 6969
useMagnetometerOnAllTrackers: true
filters:
type: "prediction"
amount: 1.0
vmc:
enabled: true
portIn: 39541
portOut: 39538
address: "192.168.1.20"
anchorHip: false
vrmJson: "{\"nodes\":[]}"
mirrorTracking: true
skeleton:
toggles:
floorClip: false
selfLocalization: true
toeSnap: true
enforceConstraints: false
extendedSpine: false
values:
kneeTrackerAnkleAveraging: 0.6
kneeAnkleAveraging: 0.2
offsets:
chestLength: 0.42
hmdHeight: 1.72
floorHeight: 0.02
legTweaks:
correctionStrength: 0.8
tapDetection:
yawResetDelay: 0.4
fullResetDelay: 2.0
mountingResetDelay: 1.0
yawResetEnabled: false
fullResetEnabled: true
mountingResetEnabled: true
yawResetTracker: "CHEST"
mountingResetTracker: "WAIST"
fullResetTracker: "LEFT_UPPER_LEG"
setupMode: false
yawResetTaps: 4
fullResetTaps: 3
mountingResetTaps: 5
numberTrackersOverThreshold: 2
resetsConfig:
resetMountingFeet: true
mode: "TPOSE_DOWN"
yawResetSmoothTime: 0.5
saveMountingReset: true
resetHmdPitch: true
lastMountingMethod: "AUTOMATIC"
stayAlignedConfig:
enabled: true
standingRelaxedPose:
enabled: true
upperLegAngleInDeg: 4.5
lowerLegAngleInDeg: -2.0
footAngleInDeg: 10.0
sittingRelaxedPose:
enabled: false
upperLegAngleInDeg: 0.0
lowerLegAngleInDeg: 0.0
footAngleInDeg: 0.0
flatRelaxedPose:
enabled: false
upperLegAngleInDeg: 0.0
lowerLegAngleInDeg: 0.0
footAngleInDeg: 0.0
setupComplete: true
hidConfig:
trackersOverHID: true
trackers:
udp://AA:BB:CC:DD:EE:01/0:
customName: "Chest"
designation: "body:chest"
hide: false
adjustment: null
mountingOrientation:
x: 0.0
"y": 1.0
z: -0.0
w: -4.371139E-8
mountingResetOrientation:
x: 0.0
"y": 0.3
z: 0.0
w: 0.95
allowDriftCompensation: true
shouldHaveMagEnabled: null
udp://AA:BB:CC:DD:EE:01/1:
customName: null
designation: "body:waist"
hide: false
adjustment: null
mountingOrientation: null
mountingResetOrientation: null
allowDriftCompensation: true
shouldHaveMagEnabled: null
udp://AA:BB:CC:DD:EE:02/0:
designation: "body:upper_chest"
"123456ABCDEF/0":
designation: "body:left_foot"
ABCDEF123456/0:
customName: null
designation: null
mountingOrientation: null
HMD:
designation: "body:head"
PICO_CONTROLLER_LEFT:
designation: "body:left_hand"
knownDevices:
- "AA:BB:CC:DD:EE:01"
- "aa:bb:cc:dd:ee:02"
velocityConfig:
sendDerivedVelocity: true
vrcOSC:
enabled: true
overlay:
mirrored: false
visible: false
modelVersion: "15"
""".trimIndent()
class LegacyConfigTest {
private val migration = assertNotNull(migrateLegacyConfig(LEGACY_CONFIG))
@Test
fun `listed settings are imported`() {
val settings = migration.settings
assertTrue(settings.trackersConfig.globalMagEnabled)
assertTrue(settings.hidConfig.trackersOverHid)
assertTrue(settings.stayAlignedConfig.enabled)
val toggles = settings.skeletonConfig.toggles
assertFalse(toggles.floorClip)
assertTrue(toggles.mocapMode)
assertTrue(toggles.toeSnap)
assertFalse(toggles.enforceConstraints)
assertEquals(SkeletonTogglesConfig().skatingCorrection, toggles.skatingCorrection)
assertEquals(SkeletonTogglesConfig().footPlant, toggles.footPlant)
assertEquals(0.6f, settings.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs)
val resets = settings.resetsConfig
assertTrue(resets.resetMountingFeet)
assertEquals(ArmsMountingResetMode.SIDE, resets.armsMountingResetMode)
assertEquals(0.5f, resets.yawResetSmoothTime)
assertTrue(resets.saveMountingReset)
assertTrue(resets.resetHmdAttitude)
val tap = settings.trackerActionConfig
assertEquals(0.4f, tap.yawResetAction.delay)
assertEquals(2.0f, tap.fullResetAction.delay)
assertEquals(1.0f, tap.mountingResetAction.delay)
assertFalse(tap.yawResetAction.enabled)
assertEquals(BodyPart.UPPER_CHEST, tap.yawResetAction.bodyPart)
assertEquals(BodyPart.LOWER_WAIST, tap.mountingResetAction.bodyPart)
assertEquals(BodyPart.LEFT_UPPER_LEG, tap.fullResetAction.bodyPart)
assertEquals(4, tap.yawResetAction.taps)
assertEquals(5, tap.mountingResetAction.taps)
assertEquals(2, tap.tapsTrackersOverThreshold)
val vmc = settings.vmcConfig
assertTrue(vmc.enabled)
assertEquals(39541, vmc.portIn)
assertEquals(39538, vmc.portOut)
assertEquals("192.168.1.20", vmc.address)
assertFalse(vmc.anchorAtHips)
assertTrue(vmc.mirrorTracking)
assertEquals("{\"nodes\":[]}", vmc.vrmJson)
}
@Test
fun `unlisted settings keep the defaults`() {
val defaults = SettingsConfigState()
val settings = migration.settings
assertEquals(defaults.skeletonConfig.ratios.copy(interpolateUpperLegsTwistWithLowerLegs = 0.6f), settings.skeletonConfig.ratios)
assertEquals(defaults.driverConfig, settings.driverConfig)
assertEquals(defaults.vrcOscConfig, settings.vrcOscConfig)
assertEquals(defaults.boneRoutingConfig, settings.boneRoutingConfig)
assertEquals(defaults.trackersConfig.timeoutDelay, settings.trackersConfig.timeoutDelay)
assertEquals(defaults.resetsConfig.mountingMethod, settings.resetsConfig.mountingMethod)
}
@Test
fun `an uncalibrated height keeps the default user`() {
val yaml = LEGACY_CONFIG.replace("hmdHeight: 1.72", "hmdHeight: -1.0").replace("floorHeight: 0.02", "floorHeight: 0.0")
val user = assertNotNull(migrateLegacyConfig(yaml)).user
assertEquals(UserConfigData().userHeight, user.userHeight)
assertEquals(UserConfigData().proportions, user.proportions)
}
@Test
fun `a null vrm is not imported`() {
val yaml = LEGACY_CONFIG.replace("vrmJson: \"{\\\"nodes\\\":[]}\"", "vrmJson: null")
assertNull(assertNotNull(migrateLegacyConfig(yaml)).settings.vmcConfig.vrmJson)
}
@Test
fun `user height is the old hmd height above the floor`() {
// hmdHeight 1.72 minus floorHeight 0.02 in the fixture
assertEquals(1.70f, migration.user.userHeight, 0.0001f)
}
@Test
fun `proportions are the defaults for the imported height`() {
val proportions = migration.user.proportions
assertEquals(computeAllDefaultProportionsByBone(1.70f), proportions)
assertNotEquals(UserConfigData().proportions, proportions)
}
@Test
fun `recorded stay aligned poses are imported`() {
val poses = migration.user.stayAlignedPoses
assertEquals(setOf(StayAlignedRelaxedPose.STANDING), poses.keys)
assertEquals(StayAlignedPoseConfig(recorded = true, enabled = true, upperLegAngleInDeg = 4.5f, lowerLegAngleInDeg = -2.0f, footAngleInDeg = 10.0f), poses[StayAlignedRelaxedPose.STANDING])
}
@Test
fun `udp and hid trackers map to their hardware ids`() {
val trackers = migration.devices.trackers
assertEquals(setOf("udp:AA:BB:CC:DD:EE:01:0", "udp:AA:BB:CC:DD:EE:01:1", "udp:AA:BB:CC:DD:EE:02:0", "hid:123456ABCDEF", "hid:ABCDEF123456"), trackers.keys)
val chest = trackers.getValue("udp:AA:BB:CC:DD:EE:01:0")
assertEquals(BodyPart.UPPER_CHEST, chest.bodyPart)
assertEquals("Chest", chest.customName)
assertEquals(Quaternion(-4.371139E-8f, 0f, 1f, 0f), chest.mountingOrientation)
assertNull(chest.mountingResetOrientation)
assertNull(chest.magEnabled)
assertEquals(BodyPart.LOWER_WAIST, trackers.getValue("udp:AA:BB:CC:DD:EE:01:1").bodyPart)
assertEquals(Quaternion.IDENTITY, trackers.getValue("udp:AA:BB:CC:DD:EE:01:1").mountingOrientation)
assertEquals(BodyPart.UPPER_CHEST, trackers.getValue("udp:AA:BB:CC:DD:EE:02:0").bodyPart)
assertEquals(BodyPart.LEFT_FOOT, trackers.getValue("hid:123456ABCDEF").bodyPart)
assertEquals(TrackerConfig(), trackers.getValue("hid:ABCDEF123456"))
assertEquals(setOf("AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"), migration.devices.allowedUdpDevices)
}
@Test
fun `a whole glTF JSON is trimmed to what the GUI sends`() {
val gltf = """{"asset":{"version":"2.0"},"materials":[{"name":"skin"}],"extensionsUsed":["VRMC_vrm"],"extensions":{"VRMC_vrm":{"specVersion":"1.0","humanoid":{"humanBones":{"hips":{"node":0}}}},"KHR_materials_unlit":{}},"nodes":[{"translation":[0.0,1.0,0.0]}]}"""
val yaml = LEGACY_CONFIG.replace("vrmJson: \"{\\\"nodes\\\":[]}\"", "vrmJson: '$gltf'")
val vrmJson = assertNotNull(assertNotNull(migrateLegacyConfig(yaml)).settings.vmcConfig.vrmJson)
assertEquals(
"""{"extensions":{"VRMC_vrm":{"specVersion":"1.0","humanoid":{"humanBones":{"hips":{"node":0}}}}},"extensionsUsed":["VRMC_vrm"],"nodes":[{"translation":[0.0,1.0,0.0]}]}""",
vrmJson,
)
}
@Test
fun `a config larger than 3 MB is still read`() {
val padding = "x".repeat(4 * 1024 * 1024)
val yaml = LEGACY_CONFIG.replace("vrmJson: \"{\\\"nodes\\\":[]}\"", "vrmJson: '{\"nodes\":[],\"padding\":\"$padding\"}'")
assertEquals("{\"nodes\":[]}", assertNotNull(migrateLegacyConfig(yaml)).settings.vmcConfig.vrmJson)
}
@Test
fun `configs older than version 14 are skipped`() {
assertNull(migrateLegacyConfig(LEGACY_CONFIG.replace("modelVersion: \"15\"", "modelVersion: \"13\"")))
assertNull(migrateLegacyConfig(LEGACY_CONFIG.replace("\nmodelVersion: \"15\"", "")))
}
@Test
fun `first start loads the imported config`() = runTest {
val storage = MemoryStorage()
storage.files[LEGACY_CONFIG_PATH] = LEGACY_CONFIG
val config = AppConfig.create(backgroundScope, storage)
assertEquals(migration.settings, config.settings.context.state.value.data)
assertEquals(migration.user, config.userConfig.context.state.value.data)
assertEquals(migration.devices, config.devices.context.state.value)
assertEquals(LEGACY_CONFIG, storage.files[LEGACY_CONFIG_PATH])
}
@Test
fun `an existing config is never overwritten by the import`() = runTest {
val storage = MemoryStorage()
AppConfig.create(backgroundScope, storage)
storage.files[LEGACY_CONFIG_PATH] = LEGACY_CONFIG
val config = AppConfig.create(backgroundScope, storage)
assertEquals(SettingsConfigState(), config.settings.context.state.value.data)
assertEquals(DevicesConfigState(), config.devices.context.state.value)
}
}
@@ -29,7 +29,7 @@ class SettingsDefaultsTest {
assertNotNull(defaults.skeleton)
assertNotNull(defaults.resets)
assertNotNull(defaults.stayAligned)
assertNotNull(defaults.tapDetection)
assertNotNull(defaults.trackerAction)
assertNotNull(defaults.timeout)
assertNotNull(defaults.hid)
assertNotNull(defaults.driver)
@@ -15,6 +15,7 @@ import dev.slimevr.context.Context
import dev.slimevr.device.Device
import dev.slimevr.solarxr.rpc.SettingsResetBehaviour
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.udpTrackerHardwareId
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
@@ -96,10 +97,11 @@ class SettingsResetTest {
protocolVersion = 21,
)
server.context.dispatch(VRServerActions.NewDevice(device.context.state.value.id, device))
val hardwareId = udpTrackerHardwareId(mac, 0)
val tracker = buildTestTracker(server.context.scope, bridge.appContext, config.settings, server.nextHandle())
tracker.context.dispatch(TrackerActions.Update { copy(deviceId = device.context.state.value.id, hardwareId = "$mac:0") })
tracker.context.dispatch(TrackerActions.Update { copy(deviceId = device.context.state.value.id, hardwareId = hardwareId) })
server.context.dispatch(VRServerActions.NewTracker(tracker.context.state.value.id, tracker))
config.devices.context.dispatch(DevicesConfigActions.UpdateTracker("$mac:0") { copy(customName = "Left foot") })
config.devices.context.dispatch(DevicesConfigActions.UpdateTracker(hardwareId) { copy(customName = "Left foot") })
config.globalConfig.context.dispatch(
GlobalConfigActions.SetErrorReporting(
changeConsent(config.globalConfig.context.state.value.errorReporting, ErrorReportingConsent.ALLOWED),
@@ -1,4 +1,4 @@
package dev.slimevr.tapdetection
package dev.slimevr.trackeraction
import io.github.axisangles.ktmath.Vector3
import kotlin.test.Test
@@ -14,19 +14,19 @@ class TapDetectionTest {
)
// Accel high enough to trigger a tap
val highAccel = Vector3(0f, 0f, TapDetectionBasicBehaviour.NEEDED_ACCEL_DELTA * 3f)
val highAccel = Vector3(0f, 0f, TapDetectionBehaviour.NEEDED_ACCEL_DELTA * 3f)
// Low accel needed as rest between taps
val lowAccel = Vector3.ZERO
// Accelerations needed for a tap happen with this delay
val accelDelay = TapDetectionBasicBehaviour.ACCEL_WINDOW * 0.9
val accelDelay = TapDetectionBehaviour.ACCEL_WINDOW * 0.9
// Delay between several taps
val tapDelay = TapDetectionBasicBehaviour.TAP_WINDOW_PER_TAP * 0.9
val tapDelay = TapDetectionBehaviour.TAP_WINDOW_PER_TAP * 0.9
// Too long of a delay between several taps
val tapTimeoutDelay = TapDetectionBasicBehaviour.TAP_WINDOW_PER_TAP * 1.1
val tapTimeoutDelay = TapDetectionBehaviour.TAP_WINDOW_PER_TAP * 1.1
/**
* Runs a sequence of tap events through TapDetection, asserting the results.
@@ -37,11 +37,11 @@ class TapDetectionTest {
bodyAccelerating: Boolean = false,
thresholdMultiplier: Float = 1f,
) {
val state = TapDetectionBasicBehaviour.TrackerTapDetectionState(
val state = TapDetectionBehaviour.TrackerTapDetectionState(
trackerId = 1,
tapsNeeded = tapsNeeded,
)
val behaviour = TapDetectionBasicBehaviour()
val behaviour = TapDetectionBehaviour()
val timeSource = TestTimeSource()
events.forEach { event ->
@@ -15,6 +15,7 @@ import dev.slimevr.skeleton.Skeleton
import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.udpTrackerHardwareId
import io.github.axisangles.ktmath.Quaternion
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -75,7 +76,7 @@ private fun addTracker(
status = status,
origin = device.context.state.value.origin,
)
val hardwareId = "$MAC:$sensorId"
val hardwareId = udpTrackerHardwareId(MAC, sensorId)
tracker.context.dispatch(TrackerActions.Update { copy(deviceId = device.context.state.value.id, hardwareId = hardwareId) })
appContext.server.context.dispatch(VRServerActions.NewTracker(id, tracker))
appContext.config.devices.context.dispatch(DevicesConfigActions.UpdateTracker(hardwareId) { copy(bodyPart = bodyPart) })
@@ -97,7 +98,7 @@ class ForgetDeviceTest {
// Same MAC over HID must survive a UDP forget
val hidDevice = addDevice(appContext, DeviceOrigin.HID)
val hidTracker = addTracker(appContext, hidDevice, 5)
appContext.skeleton.context.dispatch(SkeletonActions.SetBonePose(BodyPart.UPPER_CHEST, null, Quaternion.IDENTITY, null, null))
appContext.skeleton.context.dispatch(SkeletonActions.SetBonePose(BodyPart.UPPER_CHEST, Quaternion.IDENTITY, null, null))
runCurrent()
forgetUdpDevice(appContext, MAC)
@@ -110,7 +111,7 @@ class ForgetDeviceTest {
trackers.forEach { assertFalse(it.context.scope.isActive) }
assertTrue(hidDevice.context.scope.isActive)
assertFalse(MAC in devices.context.state.value.allowedUdpDevices)
assertEquals(setOf("$MAC:5"), devices.context.state.value.trackers.keys)
assertEquals(setOf(udpTrackerHardwareId(MAC, 5)), devices.context.state.value.trackers.keys)
assertEquals(false, appContext.skeleton.context.state.value.boneInputs[BodyPart.UPPER_CHEST]?.isRotationActive)
}
}
@@ -37,7 +37,6 @@ private fun bone(bodyPart: BodyPart, rotation: Quaternion = Quaternion.IDENTITY,
bodyPart = bodyPart,
headOffset = Vector3.ZERO,
offset = Vector3(0f, -0.1f, 0f),
boneOffset = Vector3.ZERO,
rotation = rotation,
acceleration = Vector3.ZERO,
headPosition = headPosition,
@@ -25,7 +25,6 @@ private fun bone(bodyPart: BodyPart, rotation: Quaternion = Quaternion.IDENTITY,
bodyPart = bodyPart,
headOffset = Vector3.ZERO,
offset = Vector3(0f, -0.1f, 0f),
boneOffset = Vector3.ZERO,
rotation = rotation,
acceleration = Vector3.ZERO,
headPosition = headPosition,
@@ -44,7 +44,7 @@ import dev.slimevr.sentry.registerErrorReportSnapshots
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpServer
import dev.slimevr.userLogDirectory
@@ -164,7 +164,7 @@ fun main(args: Array<String>) = runBlocking<Unit>(appCoroutineExceptionHandler +
)
val stepMountingManager = StepMountingManager.create(ctx = phase1, scope = this)
val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, vrcOscManager = vrcOscManager, stepMountingManager = stepMountingManager, scope = this)
val tapDetectionManager = TapDetectionManager.create(ctx = phase1, resetsManager = resetsManager, scope = this)
val trackerActionManager = TrackerActionManager.create(ctx = phase1, resetsManager = resetsManager, scope = this)
val keybindManager = KeybindManager.create(scope = this)
val serverInfos = ServerInfos(::resolveDesktopLocalIpAddress)
@@ -189,7 +189,7 @@ fun main(args: Array<String>) = runBlocking<Unit>(appCoroutineExceptionHandler +
vmcManager = vmcManager,
vrcOscManager = vrcOscManager,
resetsManager = resetsManager,
tapDetectionManager = tapDetectionManager,
trackerActionManager = trackerActionManager,
stepMountingManager = stepMountingManager,
logSources = listOf(serverLogSource) +
userLogDirectory()?.let { dir ->
@@ -45,8 +45,15 @@ private val STEAMVR_WEB_SERVER_STARTUP = 1.seconds
// Retry delay doubles from 1s up to 2^step seconds (16s)
private const val DRIVERS_RETRY_MAX_BACKOFF_STEP = 4L
private fun isProcessRunning(name: String): Boolean = ProcessHandle.allProcesses().anyMatch { proc ->
proc.info().command().orElse(null)?.substringAfterLast(File.separatorChar) == name
private fun isProcessRunning(name: String): Boolean = try {
ProcessHandle.allProcesses().anyMatch { proc ->
proc.info().command().orElse(null)?.substringAfterLast(File.separatorChar) == name
}
} catch (_: Exception) {
// Implementation of ProcessHandle.allProcesses may throw
// RuntimeException("snapshot not available") on Windows if
// CreateToolhelp32Snapshot or Process32First fails, ignore it
false
}
// No OS event for process start/exit, so this polls