mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-23 02:21:19 -08:00
Compare commits
115
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48255272d2 | ||
|
|
e4b0d0a58e | ||
|
|
ae9efb1a92 | ||
|
|
0368292bf1 | ||
|
|
d55c0ef494 | ||
|
|
7bc6d99f09 | ||
|
|
7cf14188e6 | ||
|
|
292da8d91f | ||
|
|
594391a647 | ||
|
|
e719fe38cf | ||
|
|
9667fd93be | ||
|
|
e2406cacac | ||
|
|
48b36961f7 | ||
|
|
128d5e58da | ||
|
|
c71f06cf71 | ||
|
|
78deb81e21 | ||
|
|
768a623cd2 | ||
|
|
3ea39549ba | ||
|
|
e2e0a3d87d | ||
|
|
2068b208f8 | ||
|
|
f44baef615 | ||
|
|
40848cd8a3 | ||
|
|
c9e0479a51 | ||
|
|
4e5f0736d9 | ||
|
|
4e84ebdfc9 | ||
|
|
999c27c36f | ||
|
|
64af814db0 | ||
|
|
0479b162b4 | ||
|
|
f2b86ec6fd | ||
|
|
e4482971b0 | ||
|
|
cf55f48e2f | ||
|
|
caf8435636 | ||
|
|
6b65058bb3 | ||
|
|
4fa3f83f95 | ||
|
|
4481aea2b3 | ||
|
|
8c1478d3e4 | ||
|
|
9942e843ff | ||
|
|
d0fa419131 | ||
|
|
834e5d340e | ||
|
|
1a65edb0d0 | ||
|
|
b87b1f3e42 | ||
|
|
f1578ed3fe | ||
|
|
178f40226b | ||
|
|
7c5d3219c3 | ||
|
|
1d8a441d01 | ||
|
|
c64fcb1f95 | ||
|
|
7e40b54c1b | ||
|
|
bcf4e9e027 | ||
|
|
456e09c1ed | ||
|
|
ab82ce59e7 | ||
|
|
24e7719ed9 | ||
|
|
33771abed1 | ||
|
|
2b5f3a12e1 | ||
|
|
e17c8c6ee0 | ||
|
|
b7fbe7832a | ||
|
|
fe4c9514a4 | ||
|
|
ae12d8afa2 | ||
|
|
005a9707ef | ||
|
|
ec6fe67afa | ||
|
|
ac15eb5266 | ||
|
|
1d312e3d50 | ||
|
|
7d75825b82 | ||
|
|
3586127381 | ||
|
|
0256c472e1 | ||
|
|
5a38235814 | ||
|
|
6e33631005 | ||
|
|
479b16f1e8 | ||
|
|
4edc23ad59 | ||
|
|
0ad0b3c07f | ||
|
|
9b63d21ce1 | ||
|
|
79d8d2f9ce | ||
|
|
5202013cf5 | ||
|
|
61c4e47984 | ||
|
|
a55c0849e6 | ||
|
|
eb4f977c50 | ||
|
|
babb269d72 | ||
|
|
7b7b36738c | ||
|
|
3e4219c48b | ||
|
|
5d0dc5bae7 | ||
|
|
0c0e2b8acb | ||
|
|
d58a0c88fa | ||
|
|
2bc5265ed6 | ||
|
|
088adb88ea | ||
|
|
0eea8b30cc | ||
|
|
aa1343b49c | ||
|
|
02df411819 | ||
|
|
c911a29d25 | ||
|
|
546101defa | ||
|
|
44a34d6142 | ||
|
|
6b159eb5a5 | ||
|
|
9b4274847b | ||
|
|
aa29c48983 | ||
|
|
9e1222eedb | ||
|
|
bb91af389a | ||
|
|
9fc9201e0b | ||
|
|
80a819cad9 | ||
|
|
661bb37760 | ||
|
|
4f8ac26653 | ||
|
|
5ddad57851 | ||
|
|
dbbcf677e1 | ||
|
|
54c043c127 | ||
|
|
e53fcf294b | ||
|
|
baea5d3227 | ||
|
|
d7570ad3f4 | ||
|
|
fe7ca9fc80 | ||
|
|
4c80f1c54c | ||
|
|
289a314608 | ||
|
|
2b27f4b157 | ||
|
|
3875fda909 | ||
|
|
b0c266039d | ||
|
|
bdb5715a9e | ||
|
|
4bef38a4fd | ||
|
|
e52e2f8bc0 | ||
|
|
f84ce0831e | ||
|
|
fe788ed3a7 |
No files matched your search
@@ -32,7 +32,7 @@ static void OnYawReset(BridgeTransport& conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::YAW, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
@@ -43,7 +43,7 @@ static void OnFullReset(BridgeTransport& conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::FULL, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
@@ -54,7 +54,7 @@ static void OnMountingCalibration(BridgeTransport& conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
@@ -67,7 +67,7 @@ static void OnFeetMountingCalibration(BridgeTransport& conn) {
|
||||
auto bodyParts = fbb.CreateVector(
|
||||
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, bodyParts, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
@@ -80,7 +80,7 @@ static void OnToggleTracking(BridgeTransport& conn) {
|
||||
|
||||
shouldPause = !shouldPause;
|
||||
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::SetPauseTrackingRequest, toggleReq.Union());
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::SetPauseTrackingRequest, toggleReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"@twemoji/svg": "^15.0.0",
|
||||
"ajv": "^8.17.1",
|
||||
"ansi-sequence-parser": "1.1.3",
|
||||
"browser-fs-access": "^0.35.0",
|
||||
"classnames": "^2.5.1",
|
||||
"convert": "^5.12.0",
|
||||
|
||||
@@ -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
|
||||
@@ -593,20 +592,10 @@ settings-general-mounting_method = Mounting calibration method
|
||||
settings-general-mounting_method-pose_only = Only used by pose mounting calibration.
|
||||
settings-general-mounting_method-description = What mounting calibration method to use to calibrate your trackers' mounting orientations.
|
||||
settings-general-tracker_mechanics-filtering = Filtering
|
||||
settings-general-tracker_mechanics-filtering-type = Filtering type
|
||||
# This also cares about multilines
|
||||
settings-general-tracker_mechanics-filtering-description =
|
||||
Choose the filtering type for your trackers.
|
||||
"{ settings-general-tracker_mechanics-filtering-type-smoothing }" makes movement smoother while "{ settings-general-tracker_mechanics-filtering-type-prediction }" minimizes latency.
|
||||
settings-general-tracker_mechanics-filtering-type-none = No filtering
|
||||
settings-general-tracker_mechanics-filtering-type-none-description = Use rotations as is. Will not do any filtering.
|
||||
settings-general-tracker_mechanics-filtering-type-smoothing = Smoothing
|
||||
settings-general-tracker_mechanics-filtering-type-smoothing-description = Smooths movements but adds some latency.
|
||||
settings-general-tracker_mechanics-filtering-type-prediction = Prediction
|
||||
settings-general-tracker_mechanics-filtering-type-prediction-description = Reduces latency and makes movements snappier, but increases jitter.
|
||||
settings-general-tracker_mechanics-filtering-amount = Filter strength
|
||||
settings-general-tracker_mechanics-filtering-amount-description = How strong the selected filter is. Higher values increase smoothing or prediction while lower ones make the effect more subtle.
|
||||
settings-general-tracker_mechanics-filtering-amount-no_filtering = Pick a filtering type to set its strength.
|
||||
settings-general-tracker_mechanics-filtering-smoothing-strength = Smoothing strength
|
||||
settings-general-tracker_mechanics-filtering-smoothing-strength-description = Smooths out movement. Set to 0 to disable.
|
||||
settings-general-tracker_mechanics-filtering-prediction-strength = Prediction strength
|
||||
settings-general-tracker_mechanics-filtering-prediction-strength-description = Compensates for latency. Set to 0 to disable.
|
||||
settings-general-fk_settings-reset_behaviour_group = Reset behaviour
|
||||
settings-general-tracker_mechanics-yaw-reset-smooth-time = Yaw reset smooth time
|
||||
settings-general-tracker_mechanics-yaw-reset-smooth-time-description = Smooths the trackers' rotations upon doing a yaw reset. 0s disables smoothing.
|
||||
@@ -788,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-based resets
|
||||
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker. 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 ->
|
||||
@@ -802,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
|
||||
@@ -933,6 +914,10 @@ settings-serial-send_command-warning =
|
||||
<b>Warning:</b> Running serial commands can lead to data loss or brick the trackers.
|
||||
settings-serial-send_command-warning-ok = I know what I'm doing
|
||||
settings-serial-send_command-warning-cancel = Cancel
|
||||
settings-serial-search = Search output
|
||||
settings-serial-commands = Commands
|
||||
settings-serial-module = Module
|
||||
settings-serial-module-all = All modules
|
||||
|
||||
## Logs settings
|
||||
settings-logs = Logs
|
||||
@@ -1041,9 +1026,10 @@ settings-osc-vrchat-status-output-last-frame = Last frame sent: {$elapsed}
|
||||
settings-osc-vrchat-status-output-no-frame = No frame sent yet.
|
||||
settings-osc-vrchat-status-source-manual = manual
|
||||
settings-osc-vrchat-status-source-auto = auto-detected
|
||||
settings-osc-vrchat-status-oscquery-disabled = OSCQuery off (manual network mode)
|
||||
settings-osc-vrchat-status-oscquery-disabled = OSCQuery off
|
||||
settings-osc-vrchat-status-oscquery-advertising = Advertising on port {$port}
|
||||
settings-osc-vrchat-status-oscquery-searching = No VRChat clients found yet.
|
||||
settings-osc-vrchat-status-oscquery-manual = Not looking for VRChat clients, sending to the manual address instead.
|
||||
settings-osc-vrchat-status-oscquery-discovered-title = Discovered VRChat clients:
|
||||
settings-osc-vrchat-status-oscquery-switch = Switch
|
||||
settings-osc-vrchat-status-network-mode = Network mode
|
||||
@@ -1168,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
|
||||
|
||||
@@ -1582,6 +1569,8 @@ home-settings = Home Page Settings
|
||||
home-settings-close = Close
|
||||
home-connection_group-wifi = Wi-Fi Trackers
|
||||
home-connection_group-driver = VR Devices
|
||||
home-connection_group-vmc = VMC Trackers
|
||||
home-connection_group-vrc = VRChat OSC Trackers
|
||||
home-new_trackers-count = { $count ->
|
||||
[one] { $count } new tracker
|
||||
*[other] { $count } new trackers
|
||||
@@ -1881,7 +1870,7 @@ tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED-open = Go to VRChat OSC Settings
|
||||
|
||||
tracking_checklist-ignore = Ignore
|
||||
|
||||
preview-mocap_mode_soon = Mocap Mode (Soon™)
|
||||
preview-recenter_mocap = Recenter Mocap Mode
|
||||
preview-disable_render = Disable rendering
|
||||
preview-disabled_render = Rendering disabled
|
||||
preview-render_mode = Change rendering mode
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Typography } from './commons/Typography';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import {
|
||||
RecenterMocapModeRequestT,
|
||||
RpcMessage,
|
||||
SkeletonProportionsRequestT,
|
||||
SkeletonProportionsResponseT,
|
||||
@@ -21,11 +22,11 @@ import { Tooltip } from './commons/Tooltip';
|
||||
import { Vector3 } from 'three';
|
||||
import { RecordIcon } from './commons/icon/RecordIcon';
|
||||
import { PauseIcon } from './commons/icon/PauseIcon';
|
||||
import { HumanIcon } from './commons/icon/HumanIcon';
|
||||
import { useConfig } from '@/hooks/config';
|
||||
import { useBHV } from '@/hooks/bvh';
|
||||
import { usePauseTracking } from '@/hooks/pause-tracking';
|
||||
import { PlayIcon } from './commons/icon/PlayIcon';
|
||||
import { RecenterIcon } from './commons/icon/RecenterIcon';
|
||||
|
||||
export function PreviewControls({ open }: { open: boolean }) {
|
||||
const [userHeight, setUserHeight] = useState('');
|
||||
@@ -117,6 +118,7 @@ export function PreviewControls({ open }: { open: boolean }) {
|
||||
</Clickable>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
<Tooltip
|
||||
content={
|
||||
<Typography
|
||||
@@ -137,18 +139,26 @@ export function PreviewControls({ open }: { open: boolean }) {
|
||||
{paused && <PlayIcon width={25} />}
|
||||
</Clickable>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip
|
||||
content={
|
||||
<Typography
|
||||
variant="section-title"
|
||||
id="preview-mocap_mode_soon"
|
||||
/>
|
||||
<Typography variant="section-title" id="preview-recenter_mocap" />
|
||||
}
|
||||
preferedDirection="top"
|
||||
>
|
||||
<div className="flex justify-center items-center w-10 h-10 rounded-full cursor-not-allowed">
|
||||
<HumanIcon width={20} />
|
||||
</div>
|
||||
<Clickable
|
||||
className={classNames(
|
||||
'flex justify-center items-center w-10 h-10 rounded-full hover:bg-background-60 cursor-pointer'
|
||||
)}
|
||||
onClick={() =>
|
||||
sendRPCPacket(
|
||||
RpcMessage.RecenterMocapModeRequest,
|
||||
new RecenterMocapModeRequestT()
|
||||
)
|
||||
}
|
||||
>
|
||||
<RecenterIcon width={24} />
|
||||
</Clickable>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -318,9 +318,10 @@ const DropdownList = forwardRef<HTMLDivElement, DropdownListProps>(function (
|
||||
);
|
||||
});
|
||||
|
||||
export function DropdownInside(
|
||||
props: DropdownProps & (DropdownSingleSelection | DropdownMultipleSelection)
|
||||
) {
|
||||
export type DropdownInsideProps = DropdownProps &
|
||||
(DropdownSingleSelection | DropdownMultipleSelection);
|
||||
|
||||
export function DropdownInside(props: DropdownInsideProps) {
|
||||
const {
|
||||
direction = 'up',
|
||||
variant = 'primary',
|
||||
|
||||
@@ -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]}
|
||||
/>
|
||||
|
||||
@@ -98,7 +98,7 @@ export function PopoverMenu({
|
||||
{
|
||||
positionAnchor: anchorName,
|
||||
positionArea: 'bottom span-left',
|
||||
positionTryFallbacks: 'flip-inline',
|
||||
positionTryFallbacks: 'flip-inline, flip-block',
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export function RecenterIcon({ width = 24 }: { width?: number }) {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={width}>
|
||||
<path d="M11,23V18.83L9.9,19.9L8.5,18.5L12,15l3.5,3.5l-1.4,1.4L13,18.83V23H11ZM5.5,15.5L4.1,14.1L5.18,13H1V11H5.18L4.1,9.9L5.5,8.5L9,12L5.5,15.5Zm13,0L15,12l3.5-3.5l1.4,1.4L18.83,11H23v2H18.83l1.08,1.1l-1.4,1.4Zm-6.5-2q-0.63,0-1.06-0.44T10.5,12t0.44-1.06T12,10.5t1.06,0.44T13.5,12t-0.44,1.06T12,13.5ZM12,9L8.5,5.5L9.9,4.1L11,5.18V1h2V5.18L14.1,4.1l1.4,1.4L12,9Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { ReactNode, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Clickable } from '@/components/commons/Clickable';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { ArrowDownIcon } from '@/components/commons/icon/ArrowIcons';
|
||||
|
||||
export function FollowList<T extends { id: number }>({
|
||||
rows,
|
||||
renderRow,
|
||||
}: {
|
||||
rows: T[];
|
||||
renderRow: (row: T) => ReactNode;
|
||||
}) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const lastScrollTop = useRef(0);
|
||||
const [atBottom, setAtBottom] = useState(true);
|
||||
const [lastSeenId, setLastSeenId] = useState(-1);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 20,
|
||||
overscan: 20,
|
||||
getItemKey: (index) => rows[index].id,
|
||||
});
|
||||
|
||||
const newestId = useMemo(
|
||||
() => rows.reduce((newest, row) => Math.max(newest, row.id), -1),
|
||||
[rows]
|
||||
);
|
||||
const unseen = useMemo(
|
||||
() => (atBottom ? 0 : rows.filter((row) => row.id > lastSeenId).length),
|
||||
[rows, atBottom, lastSeenId]
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!atBottom || rows.length === 0) return;
|
||||
virtualizer.scrollToIndex(rows.length - 1, { align: 'end' });
|
||||
setLastSeenId(newestId);
|
||||
}, [newestId, rows, atBottom]);
|
||||
|
||||
const onScroll = () => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const movedUp = el.scrollTop < lastScrollTop.current;
|
||||
lastScrollTop.current = el.scrollTop;
|
||||
const bottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 24;
|
||||
// The virtualizer's own corrections only move down, only the user scrolls up
|
||||
if (bottom) {
|
||||
setAtBottom(true);
|
||||
return;
|
||||
}
|
||||
if (movedUp) setAtBottom(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative flex-grow h-0 flex flex-col">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={onScroll}
|
||||
className="flex-grow overflow-auto font-mono text-[12px] leading-[1.55] select-text"
|
||||
>
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ height: virtualizer.getTotalSize() }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((item) => (
|
||||
<div
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute left-0 w-full"
|
||||
style={{ transform: `translateY(${item.start}px)` }}
|
||||
>
|
||||
{renderRow(rows[item.index])}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{unseen > 0 && (
|
||||
<Clickable
|
||||
onClick={() => setAtBottom(true)}
|
||||
className="absolute left-1/2 -translate-x-1/2 bottom-3 flex items-center gap-2 bg-accent-background-30 hover:bg-accent-background-20 rounded-full px-4 py-1.5 shadow-lg fill-background-10"
|
||||
>
|
||||
<ArrowDownIcon size={12} />
|
||||
<Typography id="settings-logs-new_lines" vars={{ count: unseen }} />
|
||||
</Clickable>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { LogLevel } from 'solarxr-protocol';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import {
|
||||
DropdownInside,
|
||||
DropdownInsideProps,
|
||||
} from '@/components/commons/Dropdown';
|
||||
import { InputInside } from '@/components/commons/Input';
|
||||
import { PopoverMenu } from '@/components/commons/PopoverMenu';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { TuneIcon } from '@/components/commons/icon/TuneIcon';
|
||||
import { LEVEL_FILTERS } from './log-line';
|
||||
|
||||
export type FilterPlace = 'inline' | 'drawer';
|
||||
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
|
||||
? Omit<T, K>
|
||||
: never;
|
||||
|
||||
export function FilterDropdown({
|
||||
place,
|
||||
name,
|
||||
...props
|
||||
}: { place: FilterPlace } & DistributiveOmit<
|
||||
DropdownInsideProps,
|
||||
| 'variant'
|
||||
| 'direction'
|
||||
| 'display'
|
||||
| 'menuWidth'
|
||||
| 'alignment'
|
||||
| 'inside'
|
||||
| 'placeholder'
|
||||
>) {
|
||||
return (
|
||||
<div className={place === 'inline' ? 'w-40' : undefined}>
|
||||
<DropdownInside
|
||||
{...props}
|
||||
name={`${name}-${place}`}
|
||||
variant={place === 'drawer' ? 'secondary' : 'primary'}
|
||||
direction="down"
|
||||
display="block"
|
||||
menuWidth={place === 'inline' ? 'w-60' : undefined}
|
||||
alignment="left"
|
||||
inside="label"
|
||||
placeholder=""
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LevelFilter({
|
||||
place,
|
||||
name,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
place: FilterPlace;
|
||||
name: string;
|
||||
value: LogLevel;
|
||||
onChange: (level: LogLevel) => void;
|
||||
}) {
|
||||
const { l10n } = useLocalization();
|
||||
return (
|
||||
<FilterDropdown
|
||||
place={place}
|
||||
name={name}
|
||||
label={l10n.getString('settings-logs-level')}
|
||||
value={String(value)}
|
||||
onChange={(level) => onChange(Number(level))}
|
||||
items={LEVEL_FILTERS.map(({ level, id }) => ({
|
||||
value: String(level),
|
||||
label: <Typography tag="span" id={id} />,
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function DotLabel({
|
||||
color,
|
||||
children,
|
||||
}: {
|
||||
color: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
<span
|
||||
className="w-2 h-2 rounded-full shrink-0"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<span className="truncate">{children}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function LogFilterBar({
|
||||
renderFilters,
|
||||
filtersActive,
|
||||
searchName,
|
||||
searchPlaceholder,
|
||||
query,
|
||||
onQueryChange,
|
||||
leading,
|
||||
trailing,
|
||||
}: {
|
||||
renderFilters: (place: FilterPlace) => ReactNode;
|
||||
filtersActive: boolean;
|
||||
searchName: string;
|
||||
searchPlaceholder: string;
|
||||
query: string;
|
||||
onQueryChange: (query: string) => void;
|
||||
leading?: ReactNode;
|
||||
trailing?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 items-center">
|
||||
{leading}
|
||||
<div className="contents mobile:hidden">{renderFilters('inline')}</div>
|
||||
<div className="flex-grow basis-48 min-w-0">
|
||||
<InputInside
|
||||
name={searchName}
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
value={query}
|
||||
onChange={(e) => onQueryChange((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="xs:hidden">
|
||||
<PopoverMenu
|
||||
drawerTitle={
|
||||
<Typography variant="section-title" id="settings-logs-filters" />
|
||||
}
|
||||
trigger={(triggerProps) => (
|
||||
<Button
|
||||
variant="secondary"
|
||||
{...triggerProps}
|
||||
id="settings-logs-filters"
|
||||
iconOnly
|
||||
icon={
|
||||
<span className="relative flex fill-background-10">
|
||||
<TuneIcon size={18} />
|
||||
{filtersActive && (
|
||||
<span className="absolute -top-1 -right-1 w-2 h-2 rounded-full bg-accent-background-10" />
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
{renderFilters('drawer')}
|
||||
</div>
|
||||
</PopoverMenu>
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode, useState } from 'react';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { PauseIcon } from '@/components/commons/icon/PauseIcon';
|
||||
import { PlayIcon } from '@/components/commons/icon/PlayIcon';
|
||||
import { TrashIcon } from '@/components/commons/icon/TrashIcon';
|
||||
|
||||
export type LogStatus = 'live' | 'paused' | 'file';
|
||||
|
||||
const STATUS_IDS: Record<LogStatus, string> = {
|
||||
live: 'settings-logs-status-live',
|
||||
paused: 'settings-logs-status-paused',
|
||||
file: 'settings-logs-status-file',
|
||||
};
|
||||
|
||||
export function LogFooter({
|
||||
status,
|
||||
shown,
|
||||
total,
|
||||
children,
|
||||
}: {
|
||||
status: LogStatus;
|
||||
shown: number;
|
||||
total: number;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const live = status === 'live';
|
||||
return (
|
||||
<div className="border-t-2 pt-2 mt-1.5 border-background-60 flex flex-wrap gap-2 items-center">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span
|
||||
className={classNames(
|
||||
'w-2 h-2 rounded-full',
|
||||
live ? 'bg-status-success animate-pulse' : 'bg-status-warning'
|
||||
)}
|
||||
/>
|
||||
<Typography
|
||||
tag="span"
|
||||
color={live ? 'text-status-success' : 'text-status-warning'}
|
||||
id={STATUS_IDS[status]}
|
||||
/>
|
||||
</span>
|
||||
<span className="min-w-[11ch] tabular-nums">
|
||||
<Typography
|
||||
tag="span"
|
||||
color="text-background-20"
|
||||
whitespace="whitespace-nowrap"
|
||||
id={
|
||||
shown === total
|
||||
? 'settings-logs-lines'
|
||||
: 'settings-logs-lines-filtered'
|
||||
}
|
||||
vars={{ shown, total }}
|
||||
/>
|
||||
</span>
|
||||
<div className="flex-grow" />
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ClearLogButton({
|
||||
onClick,
|
||||
disabled,
|
||||
iconOnly,
|
||||
}: {
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
iconOnly?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
icon={
|
||||
<span className="flex fill-background-10">
|
||||
<TrashIcon size={14} />
|
||||
</span>
|
||||
}
|
||||
id="settings-logs-clear"
|
||||
iconOnly={iconOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function PauseLogButton({
|
||||
paused,
|
||||
onToggle,
|
||||
iconOnly,
|
||||
}: {
|
||||
paused: boolean;
|
||||
onToggle: () => void;
|
||||
iconOnly?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={onToggle}
|
||||
icon={
|
||||
<span className="flex fill-background-10">
|
||||
{paused ? <PlayIcon width={14} /> : <PauseIcon width={14} />}
|
||||
</span>
|
||||
}
|
||||
id={paused ? 'settings-logs-resume' : 'settings-logs-pause'}
|
||||
iconOnly={iconOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function usePausableLines<T>(live: T[]) {
|
||||
// Rows shown while paused; the live list keeps growing underneath
|
||||
const [frozen, setFrozen] = useState<T[] | null>(null);
|
||||
return {
|
||||
lines: frozen ?? live,
|
||||
paused: frozen !== null,
|
||||
togglePause: () => setFrozen((current) => (current ? null : live)),
|
||||
clearFrozen: () => setFrozen((current) => current && []),
|
||||
resume: () => setFrozen(null),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import classNames from 'classnames';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Clickable } from '@/components/commons/Clickable';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { ArrowDownIcon } from '@/components/commons/icon/ArrowIcons';
|
||||
import { formatLogTime } from '@/hooks/logs';
|
||||
import { AnsiSpan } from '@/utils/ansi';
|
||||
import { FollowList } from './FollowList';
|
||||
import { LEVEL_CLASSES, LogViewLine } from './log-line';
|
||||
|
||||
const MAX_LABEL_WIDTH = 16;
|
||||
|
||||
function MessageSpans({ spans, query }: { spans: AnsiSpan[]; query: string }) {
|
||||
const text = spans.map((span) => span.text).join('');
|
||||
const matchAt = query ? text.toLowerCase().indexOf(query.toLowerCase()) : -1;
|
||||
const matchEnd = matchAt + query.length;
|
||||
let offset = 0;
|
||||
|
||||
return spans.map((span, i) => {
|
||||
const start = offset;
|
||||
offset += span.text.length;
|
||||
const from = Math.max(matchAt - start, 0);
|
||||
const to = Math.min(matchEnd - start, span.text.length);
|
||||
if (matchAt < 0 || from >= to) {
|
||||
return (
|
||||
<span key={i} style={span.style}>
|
||||
{span.text}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span key={i} style={span.style}>
|
||||
{span.text.slice(0, from)}
|
||||
<mark className="bg-status-warning/35 text-inherit rounded-sm">
|
||||
{span.text.slice(from, to)}
|
||||
</mark>
|
||||
{span.text.slice(to)}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function LogLineRow({
|
||||
line,
|
||||
query,
|
||||
labelWidth,
|
||||
expanded,
|
||||
onToggle,
|
||||
}: {
|
||||
line: LogViewLine;
|
||||
query: string;
|
||||
labelWidth: number;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const [time, millis] = formatLogTime(line.timeMs).split('.');
|
||||
const spans = line.spans ?? [{ text: line.message }];
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex items-baseline gap-2 px-1.5 py-px border-l-2 hover:bg-background-70',
|
||||
line.level === null ? 'border-transparent' : LEVEL_CLASSES[line.level]
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className="shrink-0 w-[13ch] mobile:w-[8ch] text-background-30 tabular-nums"
|
||||
title={line.timeTitle ?? undefined}
|
||||
>
|
||||
{time}
|
||||
<span className="mobile:hidden">.{millis}</span>
|
||||
</span>
|
||||
{labelWidth > 0 && (
|
||||
<>
|
||||
<span
|
||||
className={classNames(
|
||||
'shrink-0 w-2 h-2 rounded-full self-start mt-[calc((1lh_-_0.5rem)/2)]',
|
||||
line.label === null && 'border border-background-40'
|
||||
)}
|
||||
style={{ backgroundColor: line.color ?? undefined }}
|
||||
/>
|
||||
<span
|
||||
className={classNames(
|
||||
'shrink-0 truncate mobile:hidden',
|
||||
line.label === null ? 'text-background-40' : 'text-background-20'
|
||||
)}
|
||||
style={{ width: `${labelWidth}ch` }}
|
||||
title={line.label ?? undefined}
|
||||
>
|
||||
{line.label ?? '-'}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<div className="flex-1 min-w-0 whitespace-pre-wrap break-words">
|
||||
<MessageSpans spans={spans} query={query} />
|
||||
{line.message === '' && '\n'}
|
||||
{line.details && (
|
||||
<Clickable
|
||||
onClick={onToggle}
|
||||
expanded={expanded}
|
||||
className="ml-2 inline-flex items-center gap-1 fill-accent-background-10"
|
||||
>
|
||||
<Typography
|
||||
tag="span"
|
||||
color="text-accent-background-10"
|
||||
id={
|
||||
expanded
|
||||
? 'settings-logs-details-hide'
|
||||
: 'settings-logs-details-show'
|
||||
}
|
||||
/>
|
||||
<span
|
||||
className={classNames(
|
||||
'flex transition-transform',
|
||||
expanded && 'rotate-180'
|
||||
)}
|
||||
>
|
||||
<ArrowDownIcon size={10} />
|
||||
</span>
|
||||
</Clickable>
|
||||
)}
|
||||
{line.details && expanded && (
|
||||
<pre className="text-status-critical/85 overflow-x-auto mb-1">
|
||||
{line.details}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LogView({
|
||||
lines,
|
||||
query,
|
||||
}: {
|
||||
lines: LogViewLine[];
|
||||
query: string;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState<Set<number>>(new Set());
|
||||
const labelWidth = useMemo(
|
||||
() =>
|
||||
Math.min(
|
||||
MAX_LABEL_WIDTH,
|
||||
lines.reduce(
|
||||
(width, line) => Math.max(width, line.label?.length ?? 0),
|
||||
0
|
||||
)
|
||||
),
|
||||
[lines]
|
||||
);
|
||||
|
||||
const toggle = (id: number) =>
|
||||
setExpanded((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(id)) next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<FollowList
|
||||
rows={lines}
|
||||
renderRow={(line) => (
|
||||
<LogLineRow
|
||||
line={line}
|
||||
query={query}
|
||||
labelWidth={labelWidth}
|
||||
expanded={expanded.has(line.id)}
|
||||
onToggle={() => toggle(line.id)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { LogLevel } from 'solarxr-protocol';
|
||||
import { SERIES_COLORS } from '@/components/commons/charts/series-colors';
|
||||
import { AnsiSpan } from '@/utils/ansi';
|
||||
|
||||
export interface LogViewLine {
|
||||
id: number;
|
||||
timeMs: number;
|
||||
timeTitle: string | null;
|
||||
level: LogLevel | null;
|
||||
label: string | null;
|
||||
color: string | null;
|
||||
message: string;
|
||||
spans: AnsiSpan[] | null;
|
||||
details: string | null;
|
||||
}
|
||||
|
||||
export const LEVEL_CLASSES: Record<LogLevel, string> = {
|
||||
[LogLevel.TRACE]: 'border-transparent',
|
||||
[LogLevel.DEBUG]: 'border-transparent',
|
||||
[LogLevel.INFO]: 'border-background-50',
|
||||
[LogLevel.WARN]: 'border-status-warning bg-status-warning/5',
|
||||
[LogLevel.ERROR]: 'border-status-critical bg-status-critical/10',
|
||||
[LogLevel.FATAL]: 'border-status-critical bg-status-critical/10',
|
||||
};
|
||||
|
||||
export const LEVEL_FILTERS = [
|
||||
{ level: LogLevel.DEBUG, id: 'settings-logs-level-debug' },
|
||||
{ level: LogLevel.INFO, id: 'settings-logs-level-info' },
|
||||
{ level: LogLevel.WARN, id: 'settings-logs-level-warn' },
|
||||
{ level: LogLevel.ERROR, id: 'settings-logs-level-error' },
|
||||
];
|
||||
|
||||
export function passesLevel(level: LogLevel | null, minLevel: LogLevel) {
|
||||
return level === null || level >= minLevel;
|
||||
}
|
||||
|
||||
export function passesQuery(text: string, query: string) {
|
||||
return !query || text.toLowerCase().includes(query.toLowerCase());
|
||||
}
|
||||
|
||||
export function nameColor(name: string) {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < name.length; i++) {
|
||||
hash = (hash * 31 + name.charCodeAt(i)) | 0;
|
||||
}
|
||||
return SERIES_COLORS[Math.abs(hash) % SERIES_COLORS.length];
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { AnsiSpan, parseAnsi, stripAnsi } from '@/utils/ansi';
|
||||
import { LogLineParser } from '@/utils/log-line-parsers';
|
||||
import { LogViewLine, nameColor } from './log-line';
|
||||
|
||||
export interface TextLogLine extends LogViewLine {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface TextLogState {
|
||||
lines: TextLogLine[];
|
||||
// Raw tail after the last newline, still being written by the device
|
||||
pending: string;
|
||||
pendingTimeMs: number;
|
||||
nextId: number;
|
||||
}
|
||||
|
||||
export const EMPTY_TEXT_LOG: TextLogState = {
|
||||
lines: [],
|
||||
pending: '',
|
||||
pendingTimeMs: 0,
|
||||
nextId: 0,
|
||||
};
|
||||
|
||||
function dropChars(spans: AnsiSpan[], count: number) {
|
||||
let left = count;
|
||||
const kept: AnsiSpan[] = [];
|
||||
for (const span of spans) {
|
||||
if (left >= span.text.length) {
|
||||
left -= span.text.length;
|
||||
continue;
|
||||
}
|
||||
kept.push(left > 0 ? { ...span, text: span.text.slice(left) } : span);
|
||||
left = 0;
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
function takeChars(spans: AnsiSpan[], count: number) {
|
||||
let left = count;
|
||||
const kept: AnsiSpan[] = [];
|
||||
for (const span of spans) {
|
||||
if (left <= 0) break;
|
||||
kept.push(
|
||||
span.text.length > left ? { ...span, text: span.text.slice(0, left) } : span
|
||||
);
|
||||
left -= span.text.length;
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
// Dots or blanks before a line start are progress output, not a cut line
|
||||
function lineStarts(text: string, parser: LogLineParser) {
|
||||
const starts = [0];
|
||||
const pattern = new RegExp(parser.lineStart.source, 'g');
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
const at = match.index ?? 0;
|
||||
const before = text.slice(starts[starts.length - 1], at);
|
||||
if (at > 0 && !/^[.\s]*$/.test(before)) starts.push(at);
|
||||
}
|
||||
return starts;
|
||||
}
|
||||
|
||||
function toTextLine(
|
||||
spans: AnsiSpan[],
|
||||
id: number,
|
||||
timeMs: number,
|
||||
parser: LogLineParser | null
|
||||
): TextLogLine {
|
||||
const text = spans.map((span) => span.text).join('');
|
||||
const parsed = parser?.parse(text);
|
||||
const message = parsed?.message ?? text;
|
||||
const label = parsed?.label ?? null;
|
||||
return {
|
||||
id,
|
||||
timeMs,
|
||||
timeTitle: parsed?.timeTitle ?? null,
|
||||
level: parsed?.level ?? null,
|
||||
label,
|
||||
color: label ? nameColor(label) : null,
|
||||
message,
|
||||
spans: dropChars(spans, text.length - message.length),
|
||||
details: null,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTextLines(
|
||||
raw: string,
|
||||
firstId: number,
|
||||
timeMs: number,
|
||||
parser: LogLineParser | null
|
||||
) {
|
||||
const spans = parseAnsi(raw);
|
||||
const text = spans.map((span) => span.text).join('');
|
||||
const starts = parser ? lineStarts(text, parser) : [0];
|
||||
return starts.map((start, i) => {
|
||||
const end = starts[i + 1] ?? text.length;
|
||||
const lineSpans = takeChars(dropChars(spans, start), end - start);
|
||||
return toTextLine(lineSpans, firstId + i, timeMs, parser);
|
||||
});
|
||||
}
|
||||
|
||||
export function appendTextLog(
|
||||
state: TextLogState,
|
||||
chunk: string,
|
||||
nowMs: number,
|
||||
parser: LogLineParser | null,
|
||||
maxLines: number
|
||||
): TextLogState {
|
||||
const parts = (state.pending + chunk).split('\n');
|
||||
const pending = parts.pop() ?? '';
|
||||
// The first line may have started in an earlier chunk
|
||||
const firstTimeMs = state.pending ? state.pendingTimeMs : nowMs;
|
||||
let { nextId } = state;
|
||||
const added = parts.flatMap((raw, i) => {
|
||||
const lines = parseTextLines(raw, nextId, i === 0 ? firstTimeMs : nowMs, parser);
|
||||
nextId += lines.length;
|
||||
return lines;
|
||||
});
|
||||
return {
|
||||
lines: [...state.lines, ...added].slice(-maxLines),
|
||||
pending,
|
||||
pendingTimeMs: parts.length === 0 ? firstTimeMs : nowMs,
|
||||
nextId,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearTextLog(state: TextLogState): TextLogState {
|
||||
return { ...EMPTY_TEXT_LOG, nextId: state.nextId };
|
||||
}
|
||||
|
||||
export function textLogLines(
|
||||
state: TextLogState,
|
||||
parser: LogLineParser | null
|
||||
): TextLogLine[] {
|
||||
if (!stripAnsi(state.pending)) return state.lines;
|
||||
return [
|
||||
...state.lines,
|
||||
...parseTextLines(state.pending, state.nextId, state.pendingTimeMs, parser),
|
||||
];
|
||||
}
|
||||
@@ -300,7 +300,7 @@ export function SelectSourceStep({
|
||||
</Localized>
|
||||
<div className="flex flex-col gap-4 md:max-h-[305px] overflow-y-auto bg-background-80 rounded-lg p-4">
|
||||
{possibleVersions?.map(
|
||||
({ name, disabled, latest, prerelease }, i) => (
|
||||
({ name, disabled, latest, prerelease }) => (
|
||||
<Selector
|
||||
active={partialBoard?.version === name}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -137,7 +137,7 @@ export function AppearanceSettings() {
|
||||
const themes = [
|
||||
{ value: 'slime', colors: '!bg-slime' },
|
||||
{ value: 'space', colors: '!bg-space' },
|
||||
{ value: 'midnight', colors: '!bg-midnight' },
|
||||
{ value: 'oled', colors: '!bg-oled' },
|
||||
{ value: 'light', colors: '!bg-light' },
|
||||
{ value: 'fire', colors: '!bg-fire' },
|
||||
{ value: 'citrus', colors: '!bg-citrus' },
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { defineSettingsPage } from '@/components/settings/settings-definitions';
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
KeyboardEvent,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import {
|
||||
@@ -16,6 +24,7 @@ import {
|
||||
SerialTrackerCustomCommandRequestT,
|
||||
SerialDeviceType,
|
||||
SerialKeepaliveRequestT,
|
||||
LogLevel,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useSerialDevices } from '@/hooks/serial';
|
||||
@@ -27,17 +36,57 @@ import { BaseModal } from '@/components/commons/BaseModal';
|
||||
import { WarningBox } from '@/components/commons/TipBox';
|
||||
import { saveFile } from '@/utils/save-file';
|
||||
import { waitUntil } from '@/utils/a11y';
|
||||
import { Input } from '@/components/commons/Input';
|
||||
import { PauseIcon } from '@/components/commons/icon/PauseIcon';
|
||||
import { PlayIcon } from '@/components/commons/icon/PlayIcon';
|
||||
import { PopoverMenu, PopoverMenuItem } from '@/components/commons/PopoverMenu';
|
||||
import { ArrowDownIcon } from '@/components/commons/icon/ArrowIcons';
|
||||
import { DownloadIcon } from '@/components/commons/icon/DownloadIcon';
|
||||
import { USBIcon } from '@/components/commons/icon/UsbIcon';
|
||||
import { ButterflyIcon } from '@/components/commons/icon/ButterflyIcon';
|
||||
import { SlimeNormalIcon } from '@/components/commons/icon/SlimeNormalIcon';
|
||||
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPagePaneLayout';
|
||||
import { LogView } from '@/components/commons/log-view/LogView';
|
||||
import {
|
||||
DotLabel,
|
||||
FilterDropdown,
|
||||
FilterPlace,
|
||||
LevelFilter,
|
||||
LogFilterBar,
|
||||
} from '@/components/commons/log-view/LogFilterBar';
|
||||
import {
|
||||
ClearLogButton,
|
||||
LogFooter,
|
||||
PauseLogButton,
|
||||
usePausableLines,
|
||||
} from '@/components/commons/log-view/LogFooter';
|
||||
import {
|
||||
nameColor,
|
||||
passesLevel,
|
||||
passesQuery,
|
||||
} from '@/components/commons/log-view/log-line';
|
||||
import {
|
||||
appendTextLog,
|
||||
clearTextLog,
|
||||
EMPTY_TEXT_LOG,
|
||||
textLogLines,
|
||||
} from '@/components/commons/log-view/text-log-stream';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
import {
|
||||
espLogParser,
|
||||
LogLineParser,
|
||||
zephyrLogParser,
|
||||
} from '@/utils/log-line-parsers';
|
||||
|
||||
export interface SerialForm {
|
||||
port: string;
|
||||
customCommand: string;
|
||||
}
|
||||
|
||||
interface SerialCommand {
|
||||
id: string;
|
||||
run: () => void;
|
||||
danger?: boolean;
|
||||
}
|
||||
|
||||
const MAX_COMMAND_HISTORY = 50;
|
||||
|
||||
const consoleStatusMessage: Partial<Record<SerialConsoleStatus, string>> = {
|
||||
[SerialConsoleStatus.OPENING]: 'settings-serial-opening',
|
||||
[SerialConsoleStatus.WAITING]: 'settings-serial-connection_lost',
|
||||
@@ -45,16 +94,45 @@ const consoleStatusMessage: Partial<Record<SerialConsoleStatus, string>> = {
|
||||
[SerialConsoleStatus.OPEN_FAILED]: 'settings-serial-open_failed',
|
||||
};
|
||||
|
||||
const MAX_CONSOLE_CHARS = 200_000;
|
||||
const MAX_CONSOLE_LINES = 5_000;
|
||||
|
||||
// Several of these fit in the server's grace window, so one dropped message costs nothing
|
||||
const SERIAL_KEEPALIVE_MS = 4_000;
|
||||
|
||||
function appendLog(content: string, log: string) {
|
||||
const next = content + log;
|
||||
if (next.length <= MAX_CONSOLE_CHARS) return next;
|
||||
const cut = next.indexOf('\n', next.length - MAX_CONSOLE_CHARS);
|
||||
return cut === -1 ? next : next.slice(cut + 1);
|
||||
const ALL_MODULES = '*';
|
||||
|
||||
const SERIAL_LOG_PARSERS: Record<SerialDeviceType, LogLineParser | null> = {
|
||||
[SerialDeviceType.ESP_TRACKER]: espLogParser,
|
||||
[SerialDeviceType.HID_RECEIVER]: zephyrLogParser,
|
||||
[SerialDeviceType.HID_TRACKER]: zephyrLogParser,
|
||||
[SerialDeviceType.UNKNOWN]: null,
|
||||
};
|
||||
|
||||
function serialLogParser(type: SerialDeviceType | undefined) {
|
||||
return SERIAL_LOG_PARSERS[type ?? SerialDeviceType.UNKNOWN];
|
||||
}
|
||||
|
||||
function SerialDeviceIcon({
|
||||
type,
|
||||
name,
|
||||
}: {
|
||||
type: SerialDeviceType;
|
||||
name: string;
|
||||
}) {
|
||||
switch (type) {
|
||||
case SerialDeviceType.ESP_TRACKER:
|
||||
return <SlimeNormalIcon width={16} />;
|
||||
case SerialDeviceType.HID_RECEIVER:
|
||||
return <USBIcon size={16} />;
|
||||
case SerialDeviceType.HID_TRACKER:
|
||||
return name.toLowerCase().includes('butterfly') ? (
|
||||
<ButterflyIcon width={16} />
|
||||
) : (
|
||||
<SlimeNormalIcon width={16} />
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const serialSettingsPage = defineSettingsPage({
|
||||
@@ -68,8 +146,7 @@ export function Serial() {
|
||||
const { state } = useLocation();
|
||||
|
||||
const { useRPCPacket, sendRPCPacket, useConnectedEffect } = useWebsocketAPI();
|
||||
const consoleRef = useRef<HTMLDivElement>(null);
|
||||
const [consoleContent, setConsole] = useState('');
|
||||
const [consoleState, setConsole] = useState(EMPTY_TEXT_LOG);
|
||||
|
||||
const [consoleStatus, setConsoleStatus] =
|
||||
useState<SerialConsoleStatus | null>(null);
|
||||
@@ -77,12 +154,24 @@ export function Serial() {
|
||||
SerialDeviceT,
|
||||
'pack'
|
||||
> | null>(null);
|
||||
const consoleLines = useMemo(
|
||||
() => textLogLines(consoleState, serialLogParser(openedSerialDevice?.type)),
|
||||
[consoleState, openedSerialDevice?.type]
|
||||
);
|
||||
const pausable = usePausableLines(consoleLines);
|
||||
|
||||
const [tryFactoryReset, setTryFactoryReset] = useState(false);
|
||||
const [trySendCustomCommand, setTrySendCustomCommand] = useState(false);
|
||||
|
||||
const [acceptedCustomCommandWarning, setAcceptedCustomCommandWarning] =
|
||||
useState(false);
|
||||
const [command, setCommand] = useState('');
|
||||
const [history, setHistory] = useState<string[]>([]);
|
||||
const [historyIndex, setHistoryIndex] = useState<number | null>(null);
|
||||
const [query, setQuery] = useState('');
|
||||
const [minLevel, setMinLevel] = useState(LogLevel.DEBUG);
|
||||
const [module, setModule] = useState(ALL_MODULES);
|
||||
const { isNmd: compactBar } = useBreakpoint('nmd');
|
||||
|
||||
const typedState: { serialPort?: string } | null = state;
|
||||
const { control, watch, setValue } = useForm<SerialForm>({
|
||||
@@ -90,11 +179,8 @@ export function Serial() {
|
||||
});
|
||||
|
||||
const port = watch('port');
|
||||
const customCommand = watch('customCommand');
|
||||
const serialDevices = useSerialDevices();
|
||||
|
||||
const [isPaused, setPaused] = useState(false);
|
||||
|
||||
// The server holds every port this page opened and takes them back if the keepalive stops, so a
|
||||
// tab that dies without unmounting doesn't leave them locked
|
||||
useConnectedEffect(() => {
|
||||
@@ -119,7 +205,9 @@ export function Serial() {
|
||||
|
||||
useConnectedEffect(() => {
|
||||
if (!port) return;
|
||||
setConsole('');
|
||||
setConsole(EMPTY_TEXT_LOG);
|
||||
pausable.resume();
|
||||
setModule(ALL_MODULES);
|
||||
setOpenedSerialDevice(null);
|
||||
setConsoleStatus(SerialConsoleStatus.OPENING);
|
||||
const req = new OpenSerialRequestT();
|
||||
@@ -138,42 +226,22 @@ export function Serial() {
|
||||
}
|
||||
|
||||
if (data.log) {
|
||||
setConsole((console) => appendLog(console, data.log as string));
|
||||
const log = data.log as string;
|
||||
const nowMs = Date.now();
|
||||
const parser = serialLogParser(data.device?.type);
|
||||
setConsole((console) =>
|
||||
appendTextLog(console, log, nowMs, parser, MAX_CONSOLE_LINES)
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPaused) {
|
||||
return;
|
||||
}
|
||||
if (!consoleRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
consoleRef.current.scrollTo({
|
||||
top: consoleRef.current.scrollHeight,
|
||||
});
|
||||
}, [consoleContent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!consoleRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
consoleRef.current.addEventListener('scroll', () => {
|
||||
if (!consoleRef.current) {
|
||||
return;
|
||||
}
|
||||
const bottomAllowance = 10;
|
||||
setPaused(
|
||||
consoleRef.current.scrollTop +
|
||||
consoleRef.current.getBoundingClientRect().height <
|
||||
consoleRef.current.scrollHeight - bottomAllowance
|
||||
);
|
||||
});
|
||||
}, [consoleRef.current]);
|
||||
|
||||
const sendCommand = (text: string) => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT(text)
|
||||
);
|
||||
};
|
||||
const reboot = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerRebootRequest,
|
||||
@@ -202,92 +270,173 @@ export function Serial() {
|
||||
new SerialTrackerGetWifiScanRequestT()
|
||||
);
|
||||
};
|
||||
|
||||
const sendCustomSerialCommand = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT(customCommand)
|
||||
sendCommand(command);
|
||||
setHistory((current) =>
|
||||
[...current.filter((entry) => entry !== command), command].slice(
|
||||
-MAX_COMMAND_HISTORY
|
||||
)
|
||||
);
|
||||
|
||||
setHistoryIndex(null);
|
||||
setTrySendCustomCommand(false);
|
||||
setValue('customCommand', '');
|
||||
setCommand('');
|
||||
};
|
||||
|
||||
// HID
|
||||
const enterPairing = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('pair')
|
||||
);
|
||||
};
|
||||
const dfu = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('dfu')
|
||||
);
|
||||
};
|
||||
const meow = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('meow')
|
||||
);
|
||||
const browseHistory = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'ArrowUp') {
|
||||
if (history.length === 0) return;
|
||||
e.preventDefault();
|
||||
const index =
|
||||
historyIndex === null
|
||||
? history.length - 1
|
||||
: Math.max(historyIndex - 1, 0);
|
||||
setHistoryIndex(index);
|
||||
setCommand(history[index]);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'ArrowDown') {
|
||||
if (historyIndex === null) return;
|
||||
e.preventDefault();
|
||||
const index = historyIndex + 1;
|
||||
if (index >= history.length) {
|
||||
setHistoryIndex(null);
|
||||
setCommand('');
|
||||
return;
|
||||
}
|
||||
setHistoryIndex(index);
|
||||
setCommand(history[index]);
|
||||
}
|
||||
};
|
||||
|
||||
// HID receiver
|
||||
const exitPairing = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('exit')
|
||||
);
|
||||
const clearConsole = () => {
|
||||
setConsole(clearTextLog);
|
||||
pausable.clearFrozen();
|
||||
};
|
||||
|
||||
// HID tracker
|
||||
const calibrate = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('calibrate')
|
||||
);
|
||||
};
|
||||
const sixSideCalibrate = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('6-side')
|
||||
);
|
||||
};
|
||||
|
||||
const consoleContentRef = useRef(consoleContent);
|
||||
const consoleLinesRef = useRef(consoleLines);
|
||||
useLayoutEffect(() => {
|
||||
consoleContentRef.current = consoleContent;
|
||||
}, [consoleContent]);
|
||||
consoleLinesRef.current = consoleLines;
|
||||
}, [consoleLines]);
|
||||
const consoleText = () =>
|
||||
consoleLinesRef.current.map((line) => line.text).join('\n');
|
||||
|
||||
const saveLogToFile = async () => {
|
||||
// Check if we have getInfos and fetch them if we don't
|
||||
if (!consoleContentRef.current.includes('GET INFO')) {
|
||||
if (!consoleText().includes('GET INFO')) {
|
||||
getInfos();
|
||||
await waitUntil(
|
||||
() => consoleContentRef.current.includes('GET INFO'),
|
||||
100,
|
||||
10
|
||||
);
|
||||
await waitUntil(() => consoleText().includes('GET INFO'), 100, 10);
|
||||
}
|
||||
|
||||
const blob = new Blob([consoleContentRef.current], {
|
||||
const blob = new Blob([consoleText()], {
|
||||
type: 'text/plain',
|
||||
});
|
||||
await saveFile(blob, 'serial-logs.txt', ['.txt']);
|
||||
};
|
||||
|
||||
const deviceType = openedSerialDevice?.type;
|
||||
const isEspDevice = deviceType === SerialDeviceType.ESP_TRACKER;
|
||||
// Pairing, DFU and calibration are HID firmware commands, unrecognized devices get none of them
|
||||
const isHidDevice =
|
||||
openedSerialDevice?.type === SerialDeviceType.HID_RECEIVER ||
|
||||
openedSerialDevice?.type === SerialDeviceType.HID_TRACKER;
|
||||
deviceType === SerialDeviceType.HID_RECEIVER ||
|
||||
deviceType === SerialDeviceType.HID_TRACKER;
|
||||
|
||||
const pauseScroll = () => {
|
||||
setPaused(!isPaused);
|
||||
const commands: SerialCommand[] = [
|
||||
{ id: 'settings-serial-reboot', run: reboot },
|
||||
...(isEspDevice
|
||||
? [{ id: 'settings-serial-get_wifi_scan', run: getWifiScan }]
|
||||
: []),
|
||||
...(isHidDevice
|
||||
? [
|
||||
{
|
||||
id: 'settings-serial-enter_pairing',
|
||||
run: () => sendCommand('pair'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(deviceType === SerialDeviceType.HID_RECEIVER
|
||||
? [{ id: 'settings-serial-exit_pairing', run: () => sendCommand('exit') }]
|
||||
: []),
|
||||
...(deviceType === SerialDeviceType.HID_TRACKER
|
||||
? [
|
||||
{
|
||||
id: 'settings-serial-calibrate',
|
||||
run: () => sendCommand('calibrate'),
|
||||
},
|
||||
{
|
||||
id: 'settings-serial-six_side_calibrate',
|
||||
run: () => sendCommand('6-side'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(isHidDevice
|
||||
? [
|
||||
{ id: 'settings-serial-dfu', run: () => sendCommand('dfu') },
|
||||
{ id: 'settings-serial-meow', run: () => sendCommand('meow') },
|
||||
]
|
||||
: []),
|
||||
...(isEspDevice
|
||||
? [
|
||||
{
|
||||
id: 'settings-serial-factory_reset',
|
||||
run: () => setTryFactoryReset(true),
|
||||
danger: true,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
consoleRef.current?.scrollTo({
|
||||
top: consoleRef.current.scrollHeight,
|
||||
});
|
||||
};
|
||||
const modules = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
consoleLines.flatMap((line) => (line.label ? [line.label] : []))
|
||||
),
|
||||
].sort((a, b) => a.localeCompare(b)),
|
||||
[consoleLines]
|
||||
);
|
||||
const visibleLines = useMemo(
|
||||
() =>
|
||||
pausable.lines.filter(
|
||||
(line) =>
|
||||
passesLevel(line.level, minLevel) &&
|
||||
(module === ALL_MODULES || line.label === module) &&
|
||||
passesQuery(line.text, query)
|
||||
),
|
||||
[pausable.lines, minLevel, module, query]
|
||||
);
|
||||
|
||||
const filtersActive = minLevel !== LogLevel.DEBUG || module !== ALL_MODULES;
|
||||
|
||||
const renderFilters = (place: FilterPlace) => (
|
||||
<>
|
||||
<LevelFilter
|
||||
place={place}
|
||||
name="serial-level"
|
||||
value={minLevel}
|
||||
onChange={setMinLevel}
|
||||
/>
|
||||
{modules.length > 0 && (
|
||||
<FilterDropdown
|
||||
place={place}
|
||||
name="serial-module"
|
||||
label={l10n.getString('settings-serial-module')}
|
||||
value={module}
|
||||
onChange={setModule}
|
||||
items={[
|
||||
{
|
||||
value: ALL_MODULES,
|
||||
label: <Typography tag="span" id="settings-serial-module-all" />,
|
||||
},
|
||||
...modules.map((name) => ({
|
||||
value: name,
|
||||
label: <DotLabel color={nameColor(name)}>{name}</DotLabel>,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -360,146 +509,171 @@ export function Serial() {
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<div className="bg-background-80 rounded-lg flex-grow h-0 flex flex-col p-2">
|
||||
<div
|
||||
className="flex-grow overflow-x-auto overflow-y-auto"
|
||||
ref={consoleRef}
|
||||
>
|
||||
<div className="flex select-text">
|
||||
<pre>
|
||||
{openedSerialDevice !== null
|
||||
? consoleContent
|
||||
: l10n.getString(
|
||||
(consoleStatus !== null &&
|
||||
consoleStatusMessage[consoleStatus]) ||
|
||||
'settings-serial-no_port'
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t-2 pt-2 border-background-60 border-solid gap-2 flex flex-row">
|
||||
<div className="xs:flex flex-grow xs:flex-wrap gap-2 grid grid-cols-2">
|
||||
{openedSerialDevice !== null && (
|
||||
<>
|
||||
<Button variant="quaternary" onClick={reboot}>
|
||||
{l10n.getString('settings-serial-reboot')}
|
||||
</Button>
|
||||
{openedSerialDevice?.type ===
|
||||
SerialDeviceType.ESP_TRACKER && (
|
||||
<>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={() => setTryFactoryReset(true)}
|
||||
>
|
||||
{l10n.getString('settings-serial-factory_reset')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={getWifiScan}>
|
||||
{l10n.getString('settings-serial-get_wifi_scan')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{isHidDevice && (
|
||||
<Button variant="quaternary" onClick={enterPairing}>
|
||||
{l10n.getString('settings-serial-enter_pairing')}
|
||||
</Button>
|
||||
)}
|
||||
{openedSerialDevice?.type ===
|
||||
SerialDeviceType.HID_RECEIVER && (
|
||||
<Button variant="quaternary" onClick={exitPairing}>
|
||||
{l10n.getString('settings-serial-exit_pairing')}
|
||||
</Button>
|
||||
)}
|
||||
{openedSerialDevice?.type ===
|
||||
SerialDeviceType.HID_TRACKER && (
|
||||
<>
|
||||
<Button variant="quaternary" onClick={calibrate}>
|
||||
{l10n.getString('settings-serial-calibrate')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={sixSideCalibrate}>
|
||||
{l10n.getString('settings-serial-six_side_calibrate')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{isHidDevice && (
|
||||
<>
|
||||
<Button variant="quaternary" onClick={dfu}>
|
||||
{l10n.getString('settings-serial-dfu')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={meow}>
|
||||
{l10n.getString('settings-serial-meow')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={saveLogToFile}
|
||||
disabled={
|
||||
openedSerialDevice === null || !consoleContent.trim()
|
||||
}
|
||||
>
|
||||
{l10n.getString('settings-serial-save_logs')}
|
||||
</Button>
|
||||
<div className="ml-auto">
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={pauseScroll}
|
||||
icon={
|
||||
isPaused ? (
|
||||
<PlayIcon width={16} />
|
||||
) : (
|
||||
<PauseIcon width={16} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<form
|
||||
className="w-full flex flex-row gap-2 mobile:col-span-2"
|
||||
onSubmit={(e) => {
|
||||
if (openedSerialDevice === null) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
if (!acceptedCustomCommandWarning) {
|
||||
setTrySendCustomCommand(true);
|
||||
} else {
|
||||
sendCustomSerialCommand();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex-grow">
|
||||
<Input
|
||||
control={control}
|
||||
name="customCommand"
|
||||
className="flex-grow"
|
||||
placeholder={l10n.getString(
|
||||
'settings-serial-send_command-placeholder'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
disabled={openedSerialDevice === null}
|
||||
type="submit"
|
||||
>
|
||||
{l10n.getString('settings-serial-send_command')}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="w-full mobile:col-span-2">
|
||||
<div className="flex flex-col gap-2 flex-grow h-0">
|
||||
<LogFilterBar
|
||||
renderFilters={renderFilters}
|
||||
filtersActive={filtersActive}
|
||||
searchName="serial-search"
|
||||
searchPlaceholder={l10n.getString('settings-serial-search')}
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
leading={
|
||||
<div className="w-72 mobile:w-full">
|
||||
<Dropdown
|
||||
control={control}
|
||||
name="port"
|
||||
display="block"
|
||||
direction="down"
|
||||
placeholder={l10n.getString('settings-serial-serial_select')}
|
||||
items={(serialDevices ?? []).map((device) => ({
|
||||
label: device.name?.toString() || 'error',
|
||||
label: (
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
<span className="flex w-4 shrink-0 justify-center fill-background-10">
|
||||
<SerialDeviceIcon
|
||||
type={device.type}
|
||||
name={device.name?.toString() ?? ''}
|
||||
/>
|
||||
</span>
|
||||
<span className="truncate">
|
||||
{device.name?.toString() || 'error'}
|
||||
</span>
|
||||
</span>
|
||||
),
|
||||
value: device.port?.toString() || 'error',
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<div className="bg-background-80 rounded-lg flex-grow h-0 min-h-[160px] flex flex-col p-2">
|
||||
{openedSerialDevice !== null ? (
|
||||
<LogView lines={visibleLines} query={query} />
|
||||
) : (
|
||||
<div className="flex-grow">
|
||||
<pre>
|
||||
{l10n.getString(
|
||||
(consoleStatus !== null &&
|
||||
consoleStatusMessage[consoleStatus]) ||
|
||||
'settings-serial-no_port'
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
{openedSerialDevice !== null && (
|
||||
<>
|
||||
<div className="mt-1.5 flex gap-2 items-stretch">
|
||||
<form
|
||||
className="flex-grow min-w-0 flex items-center gap-2 bg-background-70 rounded-md pl-3 font-mono text-[12px] focus-within:ring-2 focus-within:ring-accent-background-30"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (!command.trim()) return;
|
||||
if (!acceptedCustomCommandWarning) {
|
||||
setTrySendCustomCommand(true);
|
||||
return;
|
||||
}
|
||||
sendCustomSerialCommand();
|
||||
}}
|
||||
>
|
||||
<span className="text-background-10 select-none">></span>
|
||||
<input
|
||||
className="flex-grow min-w-0 bg-transparent border-0 outline-none focus:ring-0 px-0 py-2 text-[12px] text-background-10 placeholder:text-background-10"
|
||||
value={command}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={l10n.getString(
|
||||
'settings-serial-send_command-placeholder'
|
||||
)}
|
||||
onChange={(e) => {
|
||||
setCommand(e.target.value);
|
||||
setHistoryIndex(null);
|
||||
}}
|
||||
onKeyDown={browseHistory}
|
||||
/>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
size="small"
|
||||
type="submit"
|
||||
disabled={!command.trim()}
|
||||
id="settings-serial-send_command"
|
||||
/>
|
||||
</form>
|
||||
<PopoverMenu
|
||||
drawerTitle={
|
||||
<Typography
|
||||
variant="section-title"
|
||||
id="settings-serial-commands"
|
||||
/>
|
||||
}
|
||||
trigger={(triggerProps, open) => (
|
||||
<Button variant="primary" size="small" {...triggerProps}>
|
||||
<span className="flex items-center gap-2">
|
||||
<Typography
|
||||
tag="span"
|
||||
id="settings-serial-commands"
|
||||
/>
|
||||
<span
|
||||
className={classNames(
|
||||
'flex fill-background-10 transition-transform',
|
||||
open && 'rotate-180'
|
||||
)}
|
||||
>
|
||||
<ArrowDownIcon size={12} />
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
>
|
||||
{({ close }) =>
|
||||
commands.map(({ id, run, danger }) => (
|
||||
<PopoverMenuItem
|
||||
key={id}
|
||||
className={classNames(
|
||||
danger && 'border-t border-background-50'
|
||||
)}
|
||||
onClick={() => {
|
||||
close();
|
||||
run();
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
bold
|
||||
color={danger ? 'text-status-critical' : undefined}
|
||||
id={id}
|
||||
/>
|
||||
</PopoverMenuItem>
|
||||
))
|
||||
}
|
||||
</PopoverMenu>
|
||||
</div>
|
||||
<LogFooter
|
||||
status={pausable.paused ? 'paused' : 'live'}
|
||||
shown={visibleLines.length}
|
||||
total={pausable.lines.length}
|
||||
>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={saveLogToFile}
|
||||
disabled={!consoleLines.some((line) => line.text.trim())}
|
||||
icon={
|
||||
<DownloadIcon width={14} className="fill-background-10" />
|
||||
}
|
||||
id="settings-serial-save_logs"
|
||||
iconOnly={compactBar}
|
||||
/>
|
||||
<ClearLogButton
|
||||
onClick={clearConsole}
|
||||
disabled={consoleLines.length === 0}
|
||||
iconOnly={compactBar}
|
||||
/>
|
||||
<PauseLogButton
|
||||
paused={pausable.paused}
|
||||
onToggle={pausable.togglePause}
|
||||
iconOnly={compactBar}
|
||||
/>
|
||||
</LogFooter>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SettingsPagePaneLayout>
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { useEffect } from 'react';
|
||||
import { FieldPath, useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSkeletonSettingsRequestT,
|
||||
FilteringType,
|
||||
RpcMessage,
|
||||
SkeletonFilteringT,
|
||||
SkeletonRatiosT,
|
||||
SkeletonSettingsRequestT,
|
||||
SkeletonSettingsResponseT,
|
||||
@@ -16,7 +13,6 @@ import { useSettingsDefaults } from '@/hooks/settings-defaults';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { NumberSelector } from '@/components/commons/NumberSelector';
|
||||
import { Radio } from '@/components/commons/Radio';
|
||||
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPagePaneLayout';
|
||||
import { settingReset } from '@/components/settings/SettingReset';
|
||||
import {
|
||||
@@ -41,15 +37,13 @@ type SkeletonForm = {
|
||||
enforceConstraints: boolean;
|
||||
};
|
||||
ratios: {
|
||||
smoothingStrength: number;
|
||||
predictionStrength: number;
|
||||
imputeSpineFromUpperToLower: number;
|
||||
spineCurvature: number;
|
||||
interpolateUpperLegsTwistWithLowerLegs: number;
|
||||
skatingCorrectionStrength: number;
|
||||
};
|
||||
filtering: {
|
||||
type: number;
|
||||
amount: number;
|
||||
};
|
||||
};
|
||||
|
||||
// Exported so other components (e.g. StayAlignedSettings' debug copy) can
|
||||
@@ -64,7 +58,7 @@ const skeletonSettingsValueAtom = selectAtom(
|
||||
);
|
||||
|
||||
function toForm(settings: SkeletonSettingsResponseT): SkeletonForm {
|
||||
const { toggles, ratios, filtering } = settings;
|
||||
const { toggles, ratios } = settings;
|
||||
return {
|
||||
toggles: {
|
||||
floorClip: toggles?.floorClip ?? false,
|
||||
@@ -76,16 +70,14 @@ function toForm(settings: SkeletonSettingsResponseT): SkeletonForm {
|
||||
enforceConstraints: toggles?.enforceConstraints ?? false,
|
||||
},
|
||||
ratios: {
|
||||
smoothingStrength: ratios?.smoothingStrength ?? 0,
|
||||
predictionStrength: ratios?.predictionStrength ?? 0,
|
||||
imputeSpineFromUpperToLower: ratios?.imputeSpineFromUpperToLower ?? 0,
|
||||
spineCurvature: ratios?.spineCurvature ?? 0,
|
||||
interpolateUpperLegsTwistWithLowerLegs:
|
||||
ratios?.interpolateUpperLegsTwistWithLowerLegs ?? 0,
|
||||
skatingCorrectionStrength: ratios?.skatingCorrectionStrength ?? 0,
|
||||
},
|
||||
filtering: {
|
||||
type: filtering?.type ?? FilteringType.NONE,
|
||||
amount: filtering?.amount ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -96,15 +88,17 @@ export const trackingSettingsPage = defineSettingsPage({
|
||||
filtering: {
|
||||
title: 'settings-general-tracker_mechanics-filtering',
|
||||
rows: {
|
||||
type: {
|
||||
title: 'settings-general-tracker_mechanics-filtering-type',
|
||||
smoothing: {
|
||||
title:
|
||||
'settings-general-tracker_mechanics-filtering-smoothing-strength',
|
||||
description:
|
||||
'settings-general-tracker_mechanics-filtering-description',
|
||||
'settings-general-tracker_mechanics-filtering-smoothing-strength-description',
|
||||
},
|
||||
amount: {
|
||||
title: 'settings-general-tracker_mechanics-filtering-amount',
|
||||
prediction: {
|
||||
title:
|
||||
'settings-general-tracker_mechanics-filtering-prediction-strength',
|
||||
description:
|
||||
'settings-general-tracker_mechanics-filtering-amount-description',
|
||||
'settings-general-tracker_mechanics-filtering-prediction-strength-description',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -197,7 +191,6 @@ const { groups } = trackingSettingsPage;
|
||||
export function TrackingSettings() {
|
||||
const setSettings = useSetAtom(skeletonSettingsAtom);
|
||||
const settings = useAtomValue(skeletonSettingsValueAtom);
|
||||
const { l10n } = useLocalization();
|
||||
const { currentLocales } = useLocaleConfig();
|
||||
const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
|
||||
const defaults = useSettingsDefaults().skeleton;
|
||||
@@ -228,6 +221,8 @@ export function TrackingSettings() {
|
||||
settingsReq.toggles = toggles;
|
||||
|
||||
const ratios = new SkeletonRatiosT();
|
||||
ratios.smoothingStrength = values.ratios.smoothingStrength;
|
||||
ratios.predictionStrength = values.ratios.predictionStrength;
|
||||
ratios.imputeSpineFromUpperToLower =
|
||||
values.ratios.imputeSpineFromUpperToLower;
|
||||
ratios.spineCurvature = values.ratios.spineCurvature;
|
||||
@@ -236,11 +231,6 @@ export function TrackingSettings() {
|
||||
ratios.skatingCorrectionStrength = values.ratios.skatingCorrectionStrength;
|
||||
settingsReq.ratios = ratios;
|
||||
|
||||
const filtering = new SkeletonFilteringT();
|
||||
filtering.type = values.filtering.type;
|
||||
filtering.amount = values.filtering.amount;
|
||||
settingsReq.filtering = filtering;
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeSkeletonSettingsRequest, settingsReq);
|
||||
};
|
||||
|
||||
@@ -270,7 +260,6 @@ export function TrackingSettings() {
|
||||
}
|
||||
);
|
||||
|
||||
const filteringEnabled = watch('filtering.type') !== FilteringType.NONE;
|
||||
const skatingCorrection = watch('toggles.skatingCorrection');
|
||||
|
||||
const resetTo = (name: FieldPath<SkeletonForm>) =>
|
||||
@@ -320,52 +309,13 @@ export function TrackingSettings() {
|
||||
<div className="flex flex-col">
|
||||
<SettingsGroup group={groups.filtering}>
|
||||
<SettingRow
|
||||
setting={groups.filtering.rows.type}
|
||||
{...resetTo('filtering.type')}
|
||||
childrenDisabled={!filteringEnabled}
|
||||
below={
|
||||
<div className="flex md:flex-row flex-col gap-3">
|
||||
<Radio
|
||||
control={control}
|
||||
name="filtering.type"
|
||||
label={l10n.getString(
|
||||
'settings-general-tracker_mechanics-filtering-type-none'
|
||||
)}
|
||||
description={l10n.getString(
|
||||
'settings-general-tracker_mechanics-filtering-type-none-description'
|
||||
)}
|
||||
value={FilteringType.NONE}
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="filtering.type"
|
||||
label={l10n.getString(
|
||||
'settings-general-tracker_mechanics-filtering-type-smoothing'
|
||||
)}
|
||||
description={l10n.getString(
|
||||
'settings-general-tracker_mechanics-filtering-type-smoothing-description'
|
||||
)}
|
||||
value={FilteringType.SMOOTHING}
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="filtering.type"
|
||||
label={l10n.getString(
|
||||
'settings-general-tracker_mechanics-filtering-type-prediction'
|
||||
)}
|
||||
description={l10n.getString(
|
||||
'settings-general-tracker_mechanics-filtering-type-prediction-description'
|
||||
)}
|
||||
value={FilteringType.PREDICTION}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SettingRow
|
||||
setting={groups.filtering.rows.amount}
|
||||
{...stepper('filtering.amount')}
|
||||
/>
|
||||
</SettingRow>
|
||||
setting={groups.filtering.rows.smoothing}
|
||||
{...stepper('ratios.smoothingStrength')}
|
||||
/>
|
||||
<SettingRow
|
||||
setting={groups.filtering.rows.prediction}
|
||||
{...stepper('ratios.predictionStrength')}
|
||||
/>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup group={groups.legFk}>
|
||||
|
||||
@@ -278,7 +278,17 @@ function StatusCard({
|
||||
|
||||
<StatusRow
|
||||
label={<Typography variant="section-title">OSCQuery</Typography>}
|
||||
badge={<VrcBadge badge={OSCQUERY_BADGES[oscQueryState]} />}
|
||||
badge={
|
||||
<VrcBadge
|
||||
badge={
|
||||
// In manual mode we only advertise, there is nothing to search for
|
||||
targetSource === VRCOSCTargetSource.MANUAL &&
|
||||
oscQueryState === VRCOSCOscQueryState.SEARCHING
|
||||
? 'ready'
|
||||
: OSCQUERY_BADGES[oscQueryState]
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{oscQueryState === VRCOSCOscQueryState.DISABLED ? (
|
||||
<Typography id="settings-osc-vrchat-status-oscquery-disabled" />
|
||||
@@ -320,6 +330,8 @@ function StatusCard({
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : targetSource === VRCOSCTargetSource.MANUAL ? (
|
||||
<Typography id="settings-osc-vrchat-status-oscquery-manual" />
|
||||
) : (
|
||||
<Typography id="settings-osc-vrchat-status-oscquery-searching" />
|
||||
)}
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
+150
-82
@@ -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),
|
||||
@@ -1,20 +1,30 @@
|
||||
import classNames from 'classnames';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { LogLevel, LogSource } from 'solarxr-protocol';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { DropdownInside } from '@/components/commons/Dropdown';
|
||||
import { InputInside } from '@/components/commons/Input';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { PopoverMenu } from '@/components/commons/PopoverMenu';
|
||||
import { CopyIcon } from '@/components/commons/icon/CopyIcon';
|
||||
import { TuneIcon } from '@/components/commons/icon/TuneIcon';
|
||||
import { TrashIcon } from '@/components/commons/icon/TrashIcon';
|
||||
import { FolderIcon } from '@/components/commons/icon/FolderIcon';
|
||||
import { CheckIcon } from '@/components/commons/icon/CheckIcon';
|
||||
import { ArrowLeftIcon } from '@/components/commons/icon/ArrowIcons';
|
||||
import { PauseIcon } from '@/components/commons/icon/PauseIcon';
|
||||
import { PlayIcon } from '@/components/commons/icon/PlayIcon';
|
||||
import { LogView } from '@/components/commons/log-view/LogView';
|
||||
import {
|
||||
DotLabel,
|
||||
FilterDropdown,
|
||||
FilterPlace,
|
||||
LevelFilter,
|
||||
LogFilterBar,
|
||||
} from '@/components/commons/log-view/LogFilterBar';
|
||||
import {
|
||||
ClearLogButton,
|
||||
LogFooter,
|
||||
PauseLogButton,
|
||||
} from '@/components/commons/log-view/LogFooter';
|
||||
import {
|
||||
LogViewLine,
|
||||
passesLevel,
|
||||
passesQuery,
|
||||
} from '@/components/commons/log-view/log-line';
|
||||
import { useElectron } from '@/hooks/electron';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
import {
|
||||
@@ -25,17 +35,9 @@ import {
|
||||
sourceColor,
|
||||
} from '@/hooks/logs';
|
||||
import { error } from '@/utils/logging';
|
||||
import { LogList } from './LogList';
|
||||
|
||||
const ALL_LOGGERS = '*';
|
||||
|
||||
const LEVEL_FILTERS = [
|
||||
{ level: LogLevel.DEBUG, id: 'settings-logs-level-debug' },
|
||||
{ level: LogLevel.INFO, id: 'settings-logs-level-info' },
|
||||
{ level: LogLevel.WARN, id: 'settings-logs-level-warn' },
|
||||
{ level: LogLevel.ERROR, id: 'settings-logs-level-error' },
|
||||
];
|
||||
|
||||
export interface Viewing {
|
||||
file: LogFileRow;
|
||||
rows: LogRow[];
|
||||
@@ -46,7 +48,7 @@ function SourcesValue({ shown, total }: { shown: LogSource[]; total: number }) {
|
||||
return <Typography tag="span" id="settings-logs-source-all" />;
|
||||
}
|
||||
return (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="flex items-center gap-1.5 min-w-0">
|
||||
{shown.map((source) => (
|
||||
<span
|
||||
key={source}
|
||||
@@ -55,10 +57,13 @@ function SourcesValue({ shown, total }: { shown: LogSource[]; total: number }) {
|
||||
/>
|
||||
))}
|
||||
{shown.length === 1 && (
|
||||
<Typography
|
||||
tag="span"
|
||||
id={`settings-logs-source-${sourceKey(shown[0])}`}
|
||||
/>
|
||||
<span className="truncate">
|
||||
<Typography
|
||||
tag="span"
|
||||
whitespace="whitespace-nowrap"
|
||||
id={`settings-logs-source-${sourceKey(shown[0])}`}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
@@ -68,25 +73,6 @@ function loggerKey(row: LogRow) {
|
||||
return `${row.source}:${row.logger}`;
|
||||
}
|
||||
|
||||
function LoggerLabel({ row }: { row: LogRow }) {
|
||||
return (
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
<span
|
||||
className="w-2 h-2 rounded-full shrink-0"
|
||||
style={{ backgroundColor: sourceColor(row.source) }}
|
||||
/>
|
||||
{row.logger ? (
|
||||
<span className="truncate">{row.logger}</span>
|
||||
) : (
|
||||
<Typography
|
||||
tag="span"
|
||||
id={`settings-logs-source-${sourceKey(row.source)}`}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function LiveLogsTab({
|
||||
rows,
|
||||
sources,
|
||||
@@ -124,16 +110,37 @@ export function LiveLogsTab({
|
||||
);
|
||||
}, [rows]);
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const needle = query.toLowerCase();
|
||||
return rows.filter(
|
||||
(row) =>
|
||||
!hiddenSources.includes(row.source) &&
|
||||
row.level >= minLevel &&
|
||||
(logger === ALL_LOGGERS || loggerKey(row) === logger) &&
|
||||
(!needle || row.message.toLowerCase().includes(needle))
|
||||
);
|
||||
}, [rows, hiddenSources, minLevel, logger, query]);
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
rows.filter(
|
||||
(row) =>
|
||||
!hiddenSources.includes(row.source) &&
|
||||
passesLevel(row.level, minLevel) &&
|
||||
(logger === ALL_LOGGERS || loggerKey(row) === logger) &&
|
||||
passesQuery(row.message, query)
|
||||
),
|
||||
[rows, hiddenSources, minLevel, logger, query]
|
||||
);
|
||||
|
||||
const lines = useMemo(
|
||||
() =>
|
||||
visible.map(
|
||||
(row): LogViewLine => ({
|
||||
id: row.id,
|
||||
timeMs: row.timeMs,
|
||||
timeTitle: null,
|
||||
level: row.level,
|
||||
label:
|
||||
row.logger ||
|
||||
l10n.getString(`settings-logs-source-${sourceKey(row.source)}`),
|
||||
color: sourceColor(row.source),
|
||||
message: row.message,
|
||||
spans: null,
|
||||
details: row.stackTrace,
|
||||
})
|
||||
),
|
||||
[visible, l10n]
|
||||
);
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
@@ -149,150 +156,94 @@ export function LiveLogsTab({
|
||||
}
|
||||
};
|
||||
|
||||
const live = !viewing && !paused;
|
||||
|
||||
const filtersActive =
|
||||
hiddenSources.length > 0 ||
|
||||
minLevel !== LogLevel.INFO ||
|
||||
logger !== ALL_LOGGERS;
|
||||
|
||||
const renderFilters = (place: 'inline' | 'drawer') => (
|
||||
const renderFilters = (place: FilterPlace) => (
|
||||
<>
|
||||
{sources.length > 1 && (
|
||||
<div className={place === 'inline' ? 'w-40' : undefined}>
|
||||
<DropdownInside
|
||||
name={`logs-sources-${place}`}
|
||||
variant={place === 'drawer' ? 'secondary' : 'primary'}
|
||||
direction="down"
|
||||
display="block"
|
||||
menuWidth={place === 'inline' ? 'w-60' : undefined}
|
||||
alignment="left"
|
||||
label={l10n.getString('settings-logs-sources')}
|
||||
inside="label"
|
||||
placeholder=""
|
||||
multiple
|
||||
value={sources
|
||||
.filter((source) => !hiddenSources.includes(source))
|
||||
.map(String)}
|
||||
onChange={(values) =>
|
||||
setHiddenSources(
|
||||
sources.filter((source) => !values.includes(String(source)))
|
||||
)
|
||||
}
|
||||
renderValue={() => (
|
||||
<SourcesValue
|
||||
shown={sources.filter(
|
||||
(source) => !hiddenSources.includes(source)
|
||||
)}
|
||||
total={sources.length}
|
||||
/>
|
||||
)}
|
||||
items={sources.map((source) => ({
|
||||
value: String(source),
|
||||
label: (
|
||||
<span className="flex items-center gap-2">
|
||||
<span
|
||||
className="w-2 h-2 rounded-full shrink-0"
|
||||
style={{ backgroundColor: sourceColor(source) }}
|
||||
/>
|
||||
<Typography
|
||||
tag="span"
|
||||
id={`settings-logs-source-${sourceKey(source)}`}
|
||||
/>
|
||||
</span>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className={place === 'inline' ? 'w-40' : undefined}>
|
||||
<DropdownInside
|
||||
name={`logs-level-${place}`}
|
||||
variant={place === 'drawer' ? 'secondary' : 'primary'}
|
||||
direction="down"
|
||||
display="block"
|
||||
menuWidth={place === 'inline' ? 'w-60' : undefined}
|
||||
alignment="left"
|
||||
label={l10n.getString('settings-logs-level')}
|
||||
inside="label"
|
||||
placeholder=""
|
||||
value={String(minLevel)}
|
||||
onChange={(value) => setMinLevel(Number(value))}
|
||||
items={LEVEL_FILTERS.map(({ level, id }) => ({
|
||||
value: String(level),
|
||||
label: <Typography tag="span" id={id} />,
|
||||
<FilterDropdown
|
||||
place={place}
|
||||
name="logs-sources"
|
||||
label={l10n.getString('settings-logs-sources')}
|
||||
multiple
|
||||
value={sources
|
||||
.filter((source) => !hiddenSources.includes(source))
|
||||
.map(String)}
|
||||
onChange={(values) =>
|
||||
setHiddenSources(
|
||||
sources.filter((source) => !values.includes(String(source)))
|
||||
)
|
||||
}
|
||||
renderValue={() => (
|
||||
<SourcesValue
|
||||
shown={sources.filter(
|
||||
(source) => !hiddenSources.includes(source)
|
||||
)}
|
||||
total={sources.length}
|
||||
/>
|
||||
)}
|
||||
items={sources.map((source) => ({
|
||||
value: String(source),
|
||||
label: (
|
||||
<DotLabel color={sourceColor(source)}>
|
||||
<Typography
|
||||
tag="span"
|
||||
id={`settings-logs-source-${sourceKey(source)}`}
|
||||
/>
|
||||
</DotLabel>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
<div className={place === 'inline' ? 'w-40' : undefined}>
|
||||
<DropdownInside
|
||||
name={`logs-logger-${place}`}
|
||||
variant={place === 'drawer' ? 'secondary' : 'primary'}
|
||||
direction="down"
|
||||
display="block"
|
||||
menuWidth={place === 'inline' ? 'w-60' : undefined}
|
||||
alignment="left"
|
||||
label={l10n.getString('settings-logs-logger')}
|
||||
inside="label"
|
||||
placeholder=""
|
||||
value={logger}
|
||||
onChange={setLogger}
|
||||
items={[
|
||||
{
|
||||
value: ALL_LOGGERS,
|
||||
label: <Typography tag="span" id="settings-logs-logger-all" />,
|
||||
},
|
||||
...loggers.map(([key, row]) => ({
|
||||
value: key,
|
||||
label: <LoggerLabel row={row} />,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<LevelFilter
|
||||
place={place}
|
||||
name="logs-level"
|
||||
value={minLevel}
|
||||
onChange={setMinLevel}
|
||||
/>
|
||||
<FilterDropdown
|
||||
place={place}
|
||||
name="logs-logger"
|
||||
label={l10n.getString('settings-logs-logger')}
|
||||
value={logger}
|
||||
onChange={setLogger}
|
||||
items={[
|
||||
{
|
||||
value: ALL_LOGGERS,
|
||||
label: <Typography tag="span" id="settings-logs-logger-all" />,
|
||||
},
|
||||
...loggers.map(([key, row]) => ({
|
||||
value: key,
|
||||
label: (
|
||||
<DotLabel color={sourceColor(row.source)}>
|
||||
{row.logger || (
|
||||
<Typography
|
||||
tag="span"
|
||||
whitespace="whitespace-nowrap"
|
||||
id={`settings-logs-source-${sourceKey(row.source)}`}
|
||||
/>
|
||||
)}
|
||||
</DotLabel>
|
||||
),
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 flex-grow h-0">
|
||||
<div className="flex flex-wrap gap-2 items-center">
|
||||
<div className="contents mobile:hidden">{renderFilters('inline')}</div>
|
||||
<div className="flex-grow basis-48 min-w-0">
|
||||
<InputInside
|
||||
name="logs-search"
|
||||
type="text"
|
||||
placeholder={l10n.getString('settings-logs-search')}
|
||||
value={query}
|
||||
onChange={(e) => setQuery((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="xs:hidden">
|
||||
<PopoverMenu
|
||||
drawerTitle={
|
||||
<Typography variant="section-title" id="settings-logs-filters" />
|
||||
}
|
||||
trigger={(triggerProps) => (
|
||||
<Button
|
||||
variant="secondary"
|
||||
{...triggerProps}
|
||||
id="settings-logs-filters"
|
||||
iconOnly
|
||||
icon={
|
||||
<span className="relative flex fill-background-10">
|
||||
<TuneIcon size={18} />
|
||||
{filtersActive && (
|
||||
<span className="absolute -top-1 -right-1 w-2 h-2 rounded-full bg-accent-background-10" />
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
{renderFilters('drawer')}
|
||||
</div>
|
||||
</PopoverMenu>
|
||||
</div>
|
||||
</div>
|
||||
<LogFilterBar
|
||||
renderFilters={renderFilters}
|
||||
filtersActive={filtersActive}
|
||||
searchName="logs-search"
|
||||
searchPlaceholder={l10n.getString('settings-logs-search')}
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
/>
|
||||
|
||||
<div className="bg-background-80 rounded-lg flex-grow h-0 min-h-[160px] flex flex-col p-2">
|
||||
{viewing && (
|
||||
@@ -315,39 +266,13 @@ export function LiveLogsTab({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<LogList key={viewing ? 'file' : 'live'} rows={visible} query={query} />
|
||||
<LogView key={viewing ? 'file' : 'live'} lines={lines} query={query} />
|
||||
|
||||
<div className="border-t-2 pt-2 mt-1.5 border-background-60 flex flex-wrap gap-2 items-center">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span
|
||||
className={classNames(
|
||||
'w-2 h-2 rounded-full',
|
||||
live ? 'bg-status-success animate-pulse' : 'bg-status-warning'
|
||||
)}
|
||||
/>
|
||||
<Typography
|
||||
tag="span"
|
||||
color={live ? 'text-status-success' : 'text-status-warning'}
|
||||
id={
|
||||
viewing
|
||||
? 'settings-logs-status-file'
|
||||
: paused
|
||||
? 'settings-logs-status-paused'
|
||||
: 'settings-logs-status-live'
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
<Typography
|
||||
tag="span"
|
||||
color="text-background-20"
|
||||
id={
|
||||
visible.length === rows.length
|
||||
? 'settings-logs-lines'
|
||||
: 'settings-logs-lines-filtered'
|
||||
}
|
||||
vars={{ shown: visible.length, total: rows.length }}
|
||||
/>
|
||||
<div className="flex-grow" />
|
||||
<LogFooter
|
||||
status={viewing ? 'file' : paused ? 'paused' : 'live'}
|
||||
shown={visible.length}
|
||||
total={rows.length}
|
||||
>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
@@ -362,18 +287,7 @@ export function LiveLogsTab({
|
||||
iconOnly={compactBar}
|
||||
/>
|
||||
{!viewing && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={onClear}
|
||||
icon={
|
||||
<span className="flex fill-background-10">
|
||||
<TrashIcon size={14} />
|
||||
</span>
|
||||
}
|
||||
id="settings-logs-clear"
|
||||
iconOnly={compactBar}
|
||||
/>
|
||||
<ClearLogButton onClick={onClear} iconOnly={compactBar} />
|
||||
)}
|
||||
{electron.isElectron && (
|
||||
<Button
|
||||
@@ -390,20 +304,13 @@ export function LiveLogsTab({
|
||||
/>
|
||||
)}
|
||||
{!viewing && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={onTogglePause}
|
||||
icon={
|
||||
<span className="flex fill-background-10">
|
||||
{paused ? <PlayIcon width={14} /> : <PauseIcon width={14} />}
|
||||
</span>
|
||||
}
|
||||
id={paused ? 'settings-logs-resume' : 'settings-logs-pause'}
|
||||
<PauseLogButton
|
||||
paused={paused}
|
||||
onToggle={onTogglePause}
|
||||
iconOnly={compactBar}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</LogFooter>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
import { Localized } from '@fluent/react';
|
||||
import classNames from 'classnames';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { LogLevel } from 'solarxr-protocol';
|
||||
import { Clickable } from '@/components/commons/Clickable';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { ArrowDownIcon } from '@/components/commons/icon/ArrowIcons';
|
||||
import { formatLogTime, LogRow, sourceColor, sourceKey } from '@/hooks/logs';
|
||||
|
||||
const LEVEL_CLASSES: Record<LogLevel, string> = {
|
||||
[LogLevel.TRACE]: 'border-transparent',
|
||||
[LogLevel.DEBUG]: 'border-transparent',
|
||||
[LogLevel.INFO]: 'border-background-50',
|
||||
[LogLevel.WARN]: 'border-status-warning bg-status-warning/5',
|
||||
[LogLevel.ERROR]: 'border-status-critical bg-status-critical/10',
|
||||
[LogLevel.FATAL]: 'border-status-critical bg-status-critical/10',
|
||||
};
|
||||
|
||||
function LogRowView({
|
||||
row,
|
||||
expanded,
|
||||
onToggle,
|
||||
query,
|
||||
}: {
|
||||
row: LogRow;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
query: string;
|
||||
}) {
|
||||
const [time, millis] = formatLogTime(row.timeMs).split('.');
|
||||
const matchAt = query
|
||||
? row.message.toLowerCase().indexOf(query.toLowerCase())
|
||||
: -1;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex items-baseline gap-2 px-1.5 py-px border-l-2 hover:bg-background-70',
|
||||
LEVEL_CLASSES[row.level]
|
||||
)}
|
||||
>
|
||||
<span className="shrink-0 w-[13ch] mobile:w-[8ch] text-background-30 tabular-nums">
|
||||
{time}
|
||||
<span className="mobile:hidden">.{millis}</span>
|
||||
</span>
|
||||
<span
|
||||
className="shrink-0 w-2 h-2 rounded-full self-start mt-[calc((1lh_-_0.5rem)/2)]"
|
||||
style={{ backgroundColor: sourceColor(row.source) }}
|
||||
/>
|
||||
{row.logger ? (
|
||||
<span
|
||||
className="shrink-0 w-[16ch] text-background-20 truncate mobile:hidden"
|
||||
title={row.logger}
|
||||
>
|
||||
{row.logger}
|
||||
</span>
|
||||
) : (
|
||||
<Localized id={`settings-logs-source-${sourceKey(row.source)}`}>
|
||||
<span className="shrink-0 w-[16ch] text-background-20 truncate mobile:hidden" />
|
||||
</Localized>
|
||||
)}
|
||||
<div className="flex-1 min-w-0 whitespace-pre-wrap break-words">
|
||||
{matchAt < 0 ? (
|
||||
row.message
|
||||
) : (
|
||||
<>
|
||||
{row.message.slice(0, matchAt)}
|
||||
<mark className="bg-status-warning/35 text-inherit rounded-sm">
|
||||
{row.message.slice(matchAt, matchAt + query.length)}
|
||||
</mark>
|
||||
{row.message.slice(matchAt + query.length)}
|
||||
</>
|
||||
)}
|
||||
{row.stackTrace && (
|
||||
<Clickable
|
||||
onClick={onToggle}
|
||||
expanded={expanded}
|
||||
className="ml-2 inline-flex items-center gap-1 fill-accent-background-10"
|
||||
>
|
||||
<Typography
|
||||
tag="span"
|
||||
color="text-accent-background-10"
|
||||
id={
|
||||
expanded
|
||||
? 'settings-logs-details-hide'
|
||||
: 'settings-logs-details-show'
|
||||
}
|
||||
/>
|
||||
<span
|
||||
className={classNames(
|
||||
'flex transition-transform',
|
||||
expanded && 'rotate-180'
|
||||
)}
|
||||
>
|
||||
<ArrowDownIcon size={10} />
|
||||
</span>
|
||||
</Clickable>
|
||||
)}
|
||||
{row.stackTrace && expanded && (
|
||||
<pre className="text-status-critical/85 overflow-x-auto mb-1">
|
||||
{row.stackTrace}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LogList({ rows, query }: { rows: LogRow[]; query: string }) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const lastScrollTop = useRef(0);
|
||||
const [atBottom, setAtBottom] = useState(true);
|
||||
const [lastSeenId, setLastSeenId] = useState(-1);
|
||||
const [expanded, setExpanded] = useState<Set<number>>(new Set());
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 20,
|
||||
overscan: 20,
|
||||
getItemKey: (index) => rows[index].id,
|
||||
});
|
||||
|
||||
const newestId = useMemo(
|
||||
() => rows.reduce((newest, row) => Math.max(newest, row.id), -1),
|
||||
[rows]
|
||||
);
|
||||
const unseen = useMemo(
|
||||
() => (atBottom ? 0 : rows.filter((row) => row.id > lastSeenId).length),
|
||||
[rows, atBottom, lastSeenId]
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!atBottom || rows.length === 0) return;
|
||||
virtualizer.scrollToIndex(rows.length - 1, { align: 'end' });
|
||||
setLastSeenId(newestId);
|
||||
}, [newestId, rows.length, atBottom]);
|
||||
|
||||
const onScroll = () => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const movedUp = el.scrollTop < lastScrollTop.current;
|
||||
lastScrollTop.current = el.scrollTop;
|
||||
const bottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 24;
|
||||
// The virtualizer's own corrections only move down, only the user scrolls up
|
||||
if (bottom) {
|
||||
setAtBottom(true);
|
||||
return;
|
||||
}
|
||||
if (movedUp) setAtBottom(false);
|
||||
};
|
||||
|
||||
const toggle = (id: number) =>
|
||||
setExpanded((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(id)) next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="relative flex-grow h-0 flex flex-col">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={onScroll}
|
||||
className="flex-grow overflow-auto font-mono text-[12px] leading-[1.55] select-text"
|
||||
>
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ height: virtualizer.getTotalSize() }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
const row = rows[item.index];
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute left-0 w-full"
|
||||
style={{ transform: `translateY(${item.start}px)` }}
|
||||
>
|
||||
<LogRowView
|
||||
row={row}
|
||||
expanded={expanded.has(row.id)}
|
||||
onToggle={() => toggle(row.id)}
|
||||
query={query}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{unseen > 0 && (
|
||||
<Clickable
|
||||
onClick={() => setAtBottom(true)}
|
||||
className="absolute left-1/2 -translate-x-1/2 bottom-3 flex items-center gap-2 bg-accent-background-30 hover:bg-accent-background-20 rounded-full px-4 py-1.5 shadow-lg fill-background-10"
|
||||
>
|
||||
<ArrowDownIcon size={12} />
|
||||
<Typography id="settings-logs-new_lines" vars={{ count: unseen }} />
|
||||
</Clickable>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
useLogFileReader,
|
||||
useLogsInfo,
|
||||
zipLogFiles,
|
||||
LogRow,
|
||||
} from '@/hooks/logs';
|
||||
import { usePausableLines } from '@/components/commons/log-view/LogFooter';
|
||||
import { saveFile } from '@/utils/save-file';
|
||||
import { error } from '@/utils/logging';
|
||||
import { ExportMenu } from './ExportMenu';
|
||||
@@ -29,13 +29,12 @@ export const logsSettingsPage = defineSettingsPage({
|
||||
export function LogsSettings() {
|
||||
const { sources, files, refresh } = useLogsInfo();
|
||||
const [tab, setTab] = useState<'live' | 'files'>('live');
|
||||
// Rows shown while paused; the live list keeps growing underneath
|
||||
const [frozen, setFrozen] = useState<LogRow[] | null>(null);
|
||||
const [viewing, setViewing] = useState<Viewing | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
|
||||
const live = useLiveLogs(sources.filter((o) => o.live).map((o) => o.source));
|
||||
const pausable = usePausableLines(live.rows);
|
||||
const readFile = useLogFileReader();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -121,7 +120,7 @@ export function LogsSettings() {
|
||||
|
||||
{tab === 'live' ? (
|
||||
<LiveLogsTab
|
||||
rows={viewing?.rows ?? frozen ?? live.rows}
|
||||
rows={viewing?.rows ?? pausable.lines}
|
||||
sources={
|
||||
viewing ? [viewing.file.source] : sources.map((o) => o.source)
|
||||
}
|
||||
@@ -130,11 +129,11 @@ export function LogsSettings() {
|
||||
setViewing(null);
|
||||
setTab('files');
|
||||
}}
|
||||
paused={frozen !== null}
|
||||
onTogglePause={() => setFrozen((rows) => (rows ? null : live.rows))}
|
||||
paused={pausable.paused}
|
||||
onTogglePause={pausable.togglePause}
|
||||
onClear={() => {
|
||||
live.clear();
|
||||
if (frozen) setFrozen([]);
|
||||
pausable.clearFrozen();
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -95,7 +95,7 @@ function TrackerSmol({
|
||||
<div className="flex rounded-md py-1.5 px-3 w-full gap-4 h-[70px]">
|
||||
<div className="flex flex-col justify-center items-center fill-background-10 relative">
|
||||
{warning && (
|
||||
<div className="absolute -right-2 -bottom-3 text-status-warning ">
|
||||
<div className="absolute -right-2 -bottom-0.5 text-status-warning ">
|
||||
<WarningIcon width={20} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -15,6 +15,8 @@ import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
|
||||
import { MetricsIcon } from '@/components/commons/icon/MetricsIcon';
|
||||
import { DongleStatus } from 'solarxr-protocol';
|
||||
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
|
||||
import { VMCIcon } from '@/components/commons/icon/VMCIcon';
|
||||
import { VRCIcon } from '@/components/commons/icon/VRCIcon';
|
||||
|
||||
function isGroupDisconnected(group: TrackerConnectionGroupData) {
|
||||
return group.kind === 'dongle' && group.status === DongleStatus.DISCONNECTED;
|
||||
@@ -55,6 +57,16 @@ export function ConnectionGroupIcon({
|
||||
<WifiIcon variant="navbar" value={100} size={iconSize} />
|
||||
)}
|
||||
{kind === 'driver' && <HeadsetIcon width={iconSize} />}
|
||||
{kind === 'vmc' && (
|
||||
<div style={{ width: iconSize }}>
|
||||
<VMCIcon />
|
||||
</div>
|
||||
)}
|
||||
{kind === 'vrc' && (
|
||||
<div style={{ width: Math.round(size * 0.95) }}>
|
||||
<VRCIcon />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -175,14 +187,17 @@ export function TrackerConnectionGroupDefaultToolbox({
|
||||
|
||||
return (
|
||||
<TrackerConnectionGroupToolboxContainer>
|
||||
{group.kind !== 'driver' && onOpenMetrics && (
|
||||
<TrackerConnectionGroupToolboxButton
|
||||
labelId="tracker-connection-metrics"
|
||||
onClick={() => onOpenMetrics(group)}
|
||||
>
|
||||
<MetricsIcon size={16} />
|
||||
</TrackerConnectionGroupToolboxButton>
|
||||
)}
|
||||
{group.kind !== 'driver' &&
|
||||
group.kind !== 'vmc' &&
|
||||
group.kind !== 'vrc' &&
|
||||
onOpenMetrics && (
|
||||
<TrackerConnectionGroupToolboxButton
|
||||
labelId="tracker-connection-metrics"
|
||||
onClick={() => onOpenMetrics(group)}
|
||||
>
|
||||
<MetricsIcon size={16} />
|
||||
</TrackerConnectionGroupToolboxButton>
|
||||
)}
|
||||
{group.kind === 'dongle' && (
|
||||
<TrackerConnectionGroupToolboxButton
|
||||
labelId="tracker-connection-dongle_settings"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -117,7 +117,6 @@ export function useProvideOnboarding() {
|
||||
const skeletonReq = new ChangeSkeletonSettingsRequestT();
|
||||
skeletonReq.toggles = toggles;
|
||||
skeletonReq.ratios = skeletonSettings.ratios;
|
||||
skeletonReq.filtering = skeletonSettings.filtering;
|
||||
sendRPCPacket(RpcMessage.ChangeSkeletonSettingsRequest, skeletonReq);
|
||||
|
||||
setResetsSettings({
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -43,6 +43,7 @@ export const trackingchecklistIdtoLabel: Record<TrackingChecklistStepId, string>
|
||||
'tracking_checklist-STANDABLE_INSTALLED',
|
||||
[TrackingChecklistStepId.VRCHAT_OSC_TRACKING_DISABLED]:
|
||||
'tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED',
|
||||
[TrackingChecklistStepId.FIRMWARE_UPDATE]: 'tracking_checklist-FIRMWARE_UPDATE',
|
||||
};
|
||||
|
||||
export const trackingchecklistIdtoSettingsDescription: Record<
|
||||
@@ -77,6 +78,8 @@ export const trackingchecklistIdtoSettingsDescription: Record<
|
||||
'tracking_checklist-STANDABLE_INSTALLED-settings_desc',
|
||||
[TrackingChecklistStepId.VRCHAT_OSC_TRACKING_DISABLED]:
|
||||
'tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED-settings_desc',
|
||||
[TrackingChecklistStepId.FIRMWARE_UPDATE]:
|
||||
'tracking_checklist-FIRMWARE_UPDATE-settings_desc',
|
||||
};
|
||||
|
||||
export type TrackingChecklistStepStatus =
|
||||
|
||||
+22
-22
@@ -128,15 +128,15 @@ body {
|
||||
--background-40: 90, 87, 92;
|
||||
--background-50: 55, 53, 56;
|
||||
--background-60: 40, 39, 41;
|
||||
--background-70: 25, 25, 26;
|
||||
--background-80: 10, 10, 10;
|
||||
--background-70: 25, 24, 26;
|
||||
--background-80: 9, 9, 10;
|
||||
--background-90: 4, 4, 4;
|
||||
|
||||
--accent-background-10: 187, 138, 229;
|
||||
--accent-background-20: 157, 92, 212;
|
||||
--accent-background-30: 101, 69, 154;
|
||||
--accent-background-40: 98, 59, 131;
|
||||
--accent-background-50: 46, 33, 69;
|
||||
--accent-background-50: 44, 32, 66;
|
||||
|
||||
--success: 80, 232, 151;
|
||||
--warning: 255, 225, 53;
|
||||
@@ -147,28 +147,28 @@ body {
|
||||
--default-color: 255, 255, 255;
|
||||
}
|
||||
|
||||
:root[data-theme='midnight'] {
|
||||
:root[data-theme='oled'] {
|
||||
--background-10: 255, 255, 255;
|
||||
--background-20: 151, 148, 153;
|
||||
--background-30: 126, 124, 128;
|
||||
--background-40: 88, 87, 89;
|
||||
--background-50: 55, 54, 56;
|
||||
--background-60: 37, 37, 38;
|
||||
--background-70: 21, 20, 21;
|
||||
--background-80: 7, 7, 7;
|
||||
--background-20: 188, 184, 191;
|
||||
--background-30: 151, 147, 153;
|
||||
--background-40: 87, 85, 89;
|
||||
--background-50: 41, 41, 43;
|
||||
--background-60: 36, 36, 38;
|
||||
--background-70: 16, 16, 17;
|
||||
--background-80: 0, 0, 0;
|
||||
--background-90: 0, 0, 0;
|
||||
|
||||
--accent-background-10: 153, 151, 156;
|
||||
--accent-background-20: 116, 114, 117;
|
||||
--accent-background-30: 78, 77, 79;
|
||||
--accent-background-40: 73, 72, 74;
|
||||
--accent-background-50: 35, 35, 36;
|
||||
--accent-background-10: 170, 125, 209;
|
||||
--accent-background-20: 138, 80, 186;
|
||||
--accent-background-30: 72, 49, 110;
|
||||
--accent-background-40: 58, 34, 77;
|
||||
--accent-background-50: 27, 19, 41;
|
||||
|
||||
--success: 77, 227, 147;
|
||||
--warning: 255, 225, 53;
|
||||
--critical: 223, 109, 140;
|
||||
--special: 123, 121, 125;
|
||||
--window-icon-stroke: 172, 172, 172;
|
||||
--special: 140, 67, 204;
|
||||
--window-icon-stroke: 157, 109, 199;
|
||||
|
||||
--default-color: 255, 255, 255;
|
||||
}
|
||||
@@ -231,7 +231,7 @@ body {
|
||||
--background-40: 55, 166, 58;
|
||||
--background-50: 34, 102, 35;
|
||||
--background-60: 25, 77, 25;
|
||||
--background-70: 16, 46, 16;
|
||||
--background-70: 16, 43, 16;
|
||||
--background-80: 7, 20, 7;
|
||||
--background-90: 2, 6, 2;
|
||||
|
||||
@@ -332,11 +332,11 @@ body {
|
||||
--background-10: 255, 255, 255;
|
||||
--background-20: 230, 220, 220;
|
||||
--background-30: 199, 191, 191;
|
||||
--background-40: 115, 110, 110;
|
||||
--background-40: 112, 108, 108;
|
||||
--background-50: 61, 59, 59;
|
||||
--background-60: 46, 44, 44;
|
||||
--background-70: 28, 27, 27;
|
||||
--background-80: 13, 12, 12;
|
||||
--background-70: 27, 26, 26;
|
||||
--background-80: 12, 11, 11;
|
||||
--background-90: 4, 4, 4;
|
||||
|
||||
--accent-background-10: 235, 113, 42;
|
||||
|
||||
@@ -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;
|
||||
@@ -93,6 +93,8 @@ export type TrackerConnectionGroup = {
|
||||
}
|
||||
| { kind: 'wifi'; pending: UnknownDeviceT[] }
|
||||
| { kind: 'driver' }
|
||||
| { kind: 'vmc' }
|
||||
| { kind: 'vrc' }
|
||||
);
|
||||
|
||||
export function groupTrackersByConnection(
|
||||
@@ -124,11 +126,33 @@ export function groupTrackersByConnection(
|
||||
unassigned: [],
|
||||
};
|
||||
|
||||
const vmcGroup: Extract<TrackerConnectionGroup, { kind: 'vmc' }> = {
|
||||
key: 'vmc',
|
||||
kind: 'vmc',
|
||||
assigned: [],
|
||||
unassigned: [],
|
||||
};
|
||||
|
||||
const vrcGroup: Extract<TrackerConnectionGroup, { kind: 'vrc' }> = {
|
||||
key: 'vrc',
|
||||
kind: 'vrc',
|
||||
assigned: [],
|
||||
unassigned: [],
|
||||
};
|
||||
|
||||
const getGroup = (flatTracker: FlatDeviceTracker): TrackerConnectionGroup => {
|
||||
if (flatTracker.tracker.origin == DeviceOrigin.DRIVER) {
|
||||
return driverGroup;
|
||||
}
|
||||
|
||||
if (flatTracker.tracker.origin == DeviceOrigin.VMC) {
|
||||
return vmcGroup;
|
||||
}
|
||||
|
||||
if (flatTracker.tracker.origin == DeviceOrigin.VRC) {
|
||||
return vrcGroup;
|
||||
}
|
||||
|
||||
// 2. Dongle check
|
||||
const deviceId = flatTracker.device?.id;
|
||||
const dongle = deviceId != null ? dongleByDeviceId.get(deviceId) : undefined;
|
||||
@@ -172,13 +196,21 @@ export function groupTrackersByConnection(
|
||||
const activeGroups = [
|
||||
...dongleGroups.values(),
|
||||
...(isNotEmpty(wifiGroup) || pending.length > 0 ? [wifiGroup] : []),
|
||||
...(isNotEmpty(vmcGroup) ? [vmcGroup] : []),
|
||||
...(isNotEmpty(vrcGroup) ? [vrcGroup] : []),
|
||||
...(isNotEmpty(driverGroup) ? [driverGroup] : []),
|
||||
];
|
||||
|
||||
const sortRank = (group: TrackerConnectionGroup) => {
|
||||
if (group.kind === 'driver') return 3;
|
||||
if (group.kind === 'vrc') return 2;
|
||||
if (group.kind === 'vmc') return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
return activeGroups.sort((a, b) => {
|
||||
// Driver group always goes last
|
||||
if (a.kind === 'driver') return 1;
|
||||
if (b.kind === 'driver') return -1;
|
||||
const rankDiff = sortRank(a) - sortRank(b);
|
||||
if (rankDiff !== 0) return rankDiff;
|
||||
|
||||
// Otherwise sort descending by total tracker count
|
||||
return getTrackerCount(b) - getTrackerCount(a);
|
||||
@@ -201,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { CSSProperties } from 'react';
|
||||
import {
|
||||
createColorPalette,
|
||||
ParseToken,
|
||||
parseAnsiSequences,
|
||||
} from 'ansi-sequence-parser';
|
||||
|
||||
export interface AnsiSpan {
|
||||
text: string;
|
||||
style?: CSSProperties;
|
||||
}
|
||||
|
||||
const palette = createColorPalette({
|
||||
black: 'rgb(var(--background-40))',
|
||||
red: 'rgb(var(--critical))',
|
||||
green: 'rgb(var(--success))',
|
||||
yellow: 'rgb(var(--warning))',
|
||||
blue: '#60a5fa',
|
||||
magenta: '#c084fc',
|
||||
cyan: '#22d3ee',
|
||||
white: 'rgb(var(--background-10))',
|
||||
brightBlack: 'rgb(var(--background-30))',
|
||||
brightRed: 'rgb(var(--critical))',
|
||||
brightGreen: 'rgb(var(--success))',
|
||||
brightYellow: 'rgb(var(--warning))',
|
||||
brightBlue: '#93c5fd',
|
||||
brightMagenta: '#d8b4fe',
|
||||
brightCyan: '#67e8f9',
|
||||
brightWhite: 'rgb(var(--background-10))',
|
||||
});
|
||||
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const NON_SGR_CSI = /\x1b\[[0-?]*[ -/]*[@-ln-~]/g;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const STRAY_CONTROL = /[\x00-\x08\x0b-\x1a\x1c-\x1f\x7f]/g;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const LONE_ESC = /\x1b/g;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const BARE_RESET = /\x1b\[m/g;
|
||||
|
||||
function tokenCss(token: ParseToken): CSSProperties | undefined {
|
||||
const { foreground, background, decorations } = token;
|
||||
if (!foreground && !background && decorations.size === 0) return undefined;
|
||||
let color = foreground ? palette.value(foreground) : undefined;
|
||||
let backgroundColor = background ? palette.value(background) : undefined;
|
||||
if (decorations.has('reverse')) {
|
||||
[color, backgroundColor] = [
|
||||
backgroundColor ?? 'rgb(var(--background-80))',
|
||||
color ?? 'rgb(var(--background-10))',
|
||||
];
|
||||
}
|
||||
const lines = [
|
||||
decorations.has('underline') && 'underline',
|
||||
decorations.has('strikethrough') && 'line-through',
|
||||
decorations.has('overline') && 'overline',
|
||||
].filter(Boolean);
|
||||
return {
|
||||
color,
|
||||
backgroundColor,
|
||||
fontWeight: decorations.has('bold') ? 600 : undefined,
|
||||
opacity: decorations.has('dim') ? 0.65 : undefined,
|
||||
fontStyle: decorations.has('italic') ? 'italic' : undefined,
|
||||
textDecorationLine: lines.length > 0 ? lines.join(' ') : undefined,
|
||||
visibility: decorations.has('hidden') ? 'hidden' : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseAnsi(text: string): AnsiSpan[] {
|
||||
const clean = text
|
||||
.replace(NON_SGR_CSI, '')
|
||||
.replace(BARE_RESET, '\x1b[0m')
|
||||
.replace(STRAY_CONTROL, '');
|
||||
return parseAnsiSequences(clean).map((token) => ({
|
||||
text: token.value.replace(LONE_ESC, ''),
|
||||
style: tokenCss(token),
|
||||
}));
|
||||
}
|
||||
|
||||
export function stripAnsi(text: string) {
|
||||
return parseAnsi(text)
|
||||
.map((span) => span.text)
|
||||
.join('');
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { LogLevel } from 'solarxr-protocol';
|
||||
import { LogViewLine } from '@/components/commons/log-view/log-line';
|
||||
|
||||
export interface LogLineParser {
|
||||
parse: (text: string) => Partial<LogViewLine> | null;
|
||||
lineStart: RegExp;
|
||||
}
|
||||
|
||||
const ESP_LEVELS: Record<string, LogLevel> = {
|
||||
TRACE: LogLevel.TRACE,
|
||||
DEBUG: LogLevel.DEBUG,
|
||||
INFO: LogLevel.INFO,
|
||||
NOTICE: LogLevel.INFO,
|
||||
WARN: LogLevel.WARN,
|
||||
ERROR: LogLevel.ERROR,
|
||||
FATAL: LogLevel.FATAL,
|
||||
};
|
||||
|
||||
// Leading dots are progress output the firmware printed before the line, without a newline
|
||||
const ESP_PREFIX =
|
||||
/^\.*\[(TRACE|DEBUG|INFO|NOTICE|WARN|ERROR|FATAL)\s*\]\s*(?:\[([^\]]+)\]\s*)?/;
|
||||
|
||||
export const espLogParser: LogLineParser = {
|
||||
parse: (text) => {
|
||||
const match = ESP_PREFIX.exec(text);
|
||||
if (!match) return null;
|
||||
return {
|
||||
level: ESP_LEVELS[match[1]],
|
||||
label: match[2] ?? null,
|
||||
message: text.slice(match[0].length),
|
||||
};
|
||||
},
|
||||
lineStart: /\[(?:TRACE|DEBUG|INFO|NOTICE|WARN|ERROR|FATAL)\s*\] /,
|
||||
};
|
||||
|
||||
const ZEPHYR_LEVELS: Record<string, LogLevel> = {
|
||||
dbg: LogLevel.DEBUG,
|
||||
inf: LogLevel.INFO,
|
||||
wrn: LogLevel.WARN,
|
||||
err: LogLevel.ERROR,
|
||||
};
|
||||
|
||||
const ZEPHYR_PREFIX = /^(?:\[([\d:.,]+)\]\s*)?<(dbg|inf|wrn|err)>\s*(?:([\w.-]+):\s)?/;
|
||||
|
||||
export const zephyrLogParser: LogLineParser = {
|
||||
parse: (text) => {
|
||||
const match = ZEPHYR_PREFIX.exec(text);
|
||||
if (!match) return null;
|
||||
return {
|
||||
level: ZEPHYR_LEVELS[match[2]],
|
||||
label: match[3] ?? null,
|
||||
timeTitle: match[1] ?? null,
|
||||
message: text.slice(match[0].length),
|
||||
};
|
||||
},
|
||||
lineStart: /\[\d+:\d{2}:\d{2}\.\d{3},\d{3}\] <(?:dbg|inf|wrn|err)>/,
|
||||
};
|
||||
@@ -66,7 +66,7 @@ type ModelRatios = {
|
||||
};
|
||||
|
||||
const RIG_SHOULDER_WIDTH = 0.338;
|
||||
const RIG_HIP_WIDTH = 0.26;
|
||||
const RIG_HIP_WIDTH = 0.23;
|
||||
const RIG_HAND_LENGTH = 0.08;
|
||||
const RIG_FOOT_LENGTH = 0.13;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -125,7 +125,7 @@ const colors = {
|
||||
600: '#2a2a2a',
|
||||
700: '#1c1c1c',
|
||||
800: '#0e0e0e',
|
||||
900: '#040404',
|
||||
900: '#000000',
|
||||
},
|
||||
'dark-accent': {
|
||||
100: '#9e9e9e',
|
||||
@@ -320,7 +320,7 @@ const config = {
|
||||
backgroundImage: {
|
||||
slime: `linear-gradient(135deg, ${colors.purple[200]} 50%, ${colors['blue-gray'][700]} 50% 100%)`,
|
||||
space: `linear-gradient(135deg, ${colors.purple[200]} 50%, ${colors['dark-background'][700]} 50% 100%)`,
|
||||
midnight: `linear-gradient(135deg, ${colors['dark-accent'][500]} 50%, ${colors['dark-background'][700]} 50% 100%)`,
|
||||
oled: `linear-gradient(135deg, ${colors.purple[200]} 50%, ${colors['dark-background'][900]} 50% 100%)`,
|
||||
light: `linear-gradient(135deg, ${colors.purple[100]} 50%, ${colors['light-background'][700]} 50% 100%)`,
|
||||
citrus: `linear-gradient(135deg, ${colors['yellow-accent'][100]} 50%, ${colors['green-background'][300]} 50% 100%)`,
|
||||
fire: `linear-gradient(135deg, ${colors['orange-accent'][100]} 50%, ${colors['red-accent'][200]} 50% 100%)`,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
@@ -246,7 +246,7 @@ handleIpc(IPC_CHANNELS.GUI_LOG_UNSUBSCRIBE, (e) => stopGuiLogs(e.sender.id));
|
||||
handleIpc(IPC_CHANNELS.GET_FOLDER, (e, folder) => {
|
||||
switch (folder) {
|
||||
case 'config':
|
||||
return getGuiDataFolder();
|
||||
return getServerDataFolder();
|
||||
case 'logs':
|
||||
return getLogsFolder();
|
||||
case 'exe':
|
||||
@@ -603,6 +603,8 @@ app.whenReady().then(async () => {
|
||||
return new Response(response.body, { status: response.status, headers });
|
||||
});
|
||||
|
||||
rewriteCrowdinOrigin();
|
||||
|
||||
try {
|
||||
await createFolders();
|
||||
} catch (err) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
Generated
+8
@@ -160,6 +160,9 @@ importers:
|
||||
ajv:
|
||||
specifier: ^8.17.1
|
||||
version: 8.18.0
|
||||
ansi-sequence-parser:
|
||||
specifier: 1.1.3
|
||||
version: 1.1.3
|
||||
browser-fs-access:
|
||||
specifier: ^0.35.0
|
||||
version: 0.35.0
|
||||
@@ -2038,6 +2041,9 @@ packages:
|
||||
resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-+fksAx9eG3Ab6LDnLs3ZqZa8KVJ/jYnX+D4Qe1azX+LFGFAXqynCQLOdLpNYN/l9e7l6hMWwZbrnctqr6eSQSw==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -6770,6 +6776,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
color-convert: 2.0.1
|
||||
|
||||
@@ -167,9 +167,6 @@ dependencies {
|
||||
implementation("com.github.mik3y:usb-serial-for-android:3.7.0")
|
||||
implementation("com.github.loucass003:EspflashKotlin:v0.11.0")
|
||||
|
||||
// mDNS for OSCQuery, resolves to the NsdManager-backed android variant
|
||||
implementation("com.appstractive:dns-sd-kt:1.1.0")
|
||||
|
||||
// Logging
|
||||
implementation("io.klogging:klogging:0.11.7")
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
|
||||
<application
|
||||
android:name=".SlimeVRApplication"
|
||||
|
||||
@@ -13,8 +13,6 @@ import androidx.core.app.NotificationChannelCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import com.appstractive.dnssd.createNetService
|
||||
import com.appstractive.dnssd.discoverServices
|
||||
import dev.slimevr.AppContext
|
||||
import dev.slimevr.FeatureFlags
|
||||
import dev.slimevr.Phase1Context
|
||||
@@ -25,10 +23,12 @@ import dev.slimevr.android.buildinfo.SENTRY_RELEASE
|
||||
import dev.slimevr.android.config.AndroidConfigStorage
|
||||
import dev.slimevr.android.hid.createAndroidHIDManager
|
||||
import dev.slimevr.android.ipc.createAndroidSolarXRWebsocketServer
|
||||
import dev.slimevr.android.multicast.bindAndroidMulticast
|
||||
import dev.slimevr.android.serial.AndroidFirmwareFlasher
|
||||
import dev.slimevr.android.serial.createAndroidSerialServer
|
||||
import dev.slimevr.android.timing.createAndroidWaiter
|
||||
import dev.slimevr.android.udp.bindAndroidUdp
|
||||
import dev.slimevr.android.vrchat.observeAndroidLocalIpAddress
|
||||
import dev.slimevr.android.vrchat.resolveAndroidLocalIpAddress
|
||||
import dev.slimevr.bvh.BVHManager
|
||||
import dev.slimevr.config.AppConfig
|
||||
@@ -36,6 +36,7 @@ import dev.slimevr.firmware.FirmwareManager
|
||||
import dev.slimevr.heightcalibration.HeightCalibrationManager
|
||||
import dev.slimevr.keybind.KeybindManager
|
||||
import dev.slimevr.logging.ServerLogSource
|
||||
import dev.slimevr.mdns.createMdns
|
||||
import dev.slimevr.networkprofile.NetworkProfileManager
|
||||
import dev.slimevr.provisioning.ProvisioningManager
|
||||
import dev.slimevr.resets.ResetsManager
|
||||
@@ -46,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
|
||||
@@ -180,15 +181,17 @@ class ForegroundService : Service() {
|
||||
val boneRouting = BoneRoutingManager.create(scope = scope)
|
||||
val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = scope)
|
||||
val vmcManager = VMCManager.create(scope = scope)
|
||||
val localIpAddress = observeAndroidLocalIpAddress(context = this@ForegroundService, scope = scope)
|
||||
val mdns = createMdns(scope = scope, localAddress = localIpAddress, bind = ::bindAndroidMulticast)
|
||||
val vrcOscManager = VRCOSCManager.create(
|
||||
scope = scope,
|
||||
oscQueryAddress = resolveAndroidLocalIpAddress(),
|
||||
discoverServicesFlow = ::discoverServices,
|
||||
serviceFactory = ::createNetService,
|
||||
oscQueryAddress = localIpAddress,
|
||||
browse = mdns.browse,
|
||||
advertise = mdns.advertise,
|
||||
)
|
||||
val stepMountingManager = StepMountingManager.create(ctx = phase1, scope = scope)
|
||||
val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, stepMountingManager = stepMountingManager, scope = scope)
|
||||
val tapDetectionManager = TapDetectionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope)
|
||||
val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, vrcOscManager = vrcOscManager, stepMountingManager = stepMountingManager, scope = scope)
|
||||
val trackerActionManager = TrackerActionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope)
|
||||
val keybindManager = KeybindManager.create(scope = scope)
|
||||
val serverInfos = ServerInfos(::resolveAndroidLocalIpAddress)
|
||||
|
||||
@@ -218,7 +221,7 @@ class ForegroundService : Service() {
|
||||
vmcManager = vmcManager,
|
||||
vrcOscManager = vrcOscManager,
|
||||
resetsManager = resetsManager,
|
||||
tapDetectionManager = tapDetectionManager,
|
||||
trackerActionManager = trackerActionManager,
|
||||
stepMountingManager = stepMountingManager,
|
||||
logSources = listOf(serverLogSource),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package dev.slimevr.android.multicast
|
||||
|
||||
import dev.slimevr.multicast.MulticastSocket
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.NetworkInterface
|
||||
import java.net.StandardProtocolFamily
|
||||
import java.net.StandardSocketOptions
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.ClosedChannelException
|
||||
import java.nio.channels.DatagramChannel
|
||||
|
||||
private const val MAX_DATAGRAM_SIZE = 65_536
|
||||
|
||||
private class AndroidMulticastSocket(private val channel: DatagramChannel, private val group: InetSocketAddress) : MulticastSocket {
|
||||
override suspend fun listen(onPacket: (ByteArray) -> Unit) = withContext(Dispatchers.IO) {
|
||||
val buffer = ByteBuffer.allocate(MAX_DATAGRAM_SIZE)
|
||||
while (true) {
|
||||
buffer.clear()
|
||||
try {
|
||||
channel.receive(buffer)
|
||||
} catch (_: ClosedChannelException) {
|
||||
return@withContext
|
||||
}
|
||||
onPacket(buffer.array().copyOf(buffer.position()))
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun send(payload: ByteArray) {
|
||||
withContext(Dispatchers.IO) { channel.send(ByteBuffer.wrap(payload), group) }
|
||||
}
|
||||
|
||||
override suspend fun close() = withContext(Dispatchers.IO) { channel.close() }
|
||||
}
|
||||
|
||||
suspend fun bindAndroidMulticast(group: ByteArray, port: Int, interfaceAddress: String): MulticastSocket = withContext(Dispatchers.IO) {
|
||||
val groupAddress = InetAddress.getByAddress(group)
|
||||
val iface = requireNotNull(NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceAddress))) { "No network interface for $interfaceAddress" }
|
||||
val channel = DatagramChannel.open(StandardProtocolFamily.INET)
|
||||
.setOption(StandardSocketOptions.SO_REUSEADDR, true)
|
||||
.setOption(StandardSocketOptions.IP_MULTICAST_IF, iface)
|
||||
.setOption(StandardSocketOptions.IP_MULTICAST_LOOP, true)
|
||||
.bind(InetSocketAddress(InetAddress.getByAddress(ByteArray(4)), port))
|
||||
channel.join(groupAddress, iface)
|
||||
AndroidMulticastSocket(channel, InetSocketAddress(groupAddress, port))
|
||||
}
|
||||
@@ -1,5 +1,19 @@
|
||||
package dev.slimevr.android.vrchat
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.conflate
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import java.net.InetAddress
|
||||
import java.net.NetworkInterface
|
||||
import java.util.Collections
|
||||
@@ -18,3 +32,27 @@ fun resolveAndroidLocalIpAddress(): String = try {
|
||||
} catch (_: Exception) {
|
||||
InetAddress.getLoopbackAddress().hostAddress
|
||||
}
|
||||
|
||||
/** [resolveAndroidLocalIpAddress], resolved again whenever the default network or its addresses change. */
|
||||
fun observeAndroidLocalIpAddress(context: Context, scope: CoroutineScope): StateFlow<String> = callbackFlow {
|
||||
val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
trySend(Unit)
|
||||
}
|
||||
|
||||
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
|
||||
trySend(Unit)
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
trySend(Unit)
|
||||
}
|
||||
}
|
||||
connectivity.registerDefaultNetworkCallback(callback)
|
||||
awaitClose { connectivity.unregisterNetworkCallback(callback) }
|
||||
}
|
||||
.conflate()
|
||||
.map { resolveAndroidLocalIpAddress() }
|
||||
.flowOn(Dispatchers.IO)
|
||||
.stateIn(scope, SharingStarted.Eagerly, resolveAndroidLocalIpAddress())
|
||||
@@ -38,7 +38,6 @@ kotlin {
|
||||
implementation("com.mayakapps.kache:kache:2.1.1")
|
||||
implementation("io.klogging:klogging:0.11.7")
|
||||
implementation("io.sentry:sentry:${providers.gradleProperty("sentryVersion").get()}")
|
||||
api("com.appstractive:dns-sd-kt:1.1.0")
|
||||
|
||||
val ktorVersion = "3.4.1"
|
||||
implementation("io.ktor:ktor-client-core:$ktorVersion")
|
||||
@@ -53,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,8 +12,8 @@ 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.FilteringType
|
||||
import solarxr_protocol.rpc.KeybindId
|
||||
import solarxr_protocol.rpc.RoutingOutput
|
||||
|
||||
@@ -23,7 +23,7 @@ private const val SETTINGS_CONFIG_VERSION = 2
|
||||
data class TrackersConfig(
|
||||
val trackerPort: Int = 6969, // Not in SolarXR
|
||||
val globalMagEnabled: Boolean = false,
|
||||
val timeoutDelay: Float = 20.0f,
|
||||
val timeoutDelay: Float = 15f,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -48,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
|
||||
@@ -117,24 +116,18 @@ data class SkeletonTogglesConfig(
|
||||
// Used in SkeletonConfig
|
||||
@Serializable
|
||||
data class SkeletonRatiosConfig(
|
||||
val smoothingStrength: Float = 0.15f,
|
||||
val predictionStrength: Float = 0.30f,
|
||||
val spineCurvature: Float = 0.75f,
|
||||
val imputeSpineFromUpperToLower: Float = DEFAULT_SPINE_UPPER_LOWER,
|
||||
val interpolateUpperLegsTwistWithLowerLegs: Float = 0.85f,
|
||||
val skatingCorrectionStrength: Float = 0.5f,
|
||||
)
|
||||
|
||||
// Used in SkeletonConfig
|
||||
@Serializable
|
||||
data class SkeletonFilteringConfig(
|
||||
val type: FilteringType = FilteringType.NONE,
|
||||
val amount: Float = 0.25f,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SkeletonConfig(
|
||||
val toggles: SkeletonTogglesConfig = SkeletonTogglesConfig(),
|
||||
val ratios: SkeletonRatiosConfig = SkeletonRatiosConfig(),
|
||||
val filtering: SkeletonFilteringConfig = SkeletonFilteringConfig(),
|
||||
)
|
||||
|
||||
const val DEFAULT_VRC_OSC_PORT_OUT: Int = 9000
|
||||
@@ -177,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") }
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
package dev.slimevr.hid.behaviours.legacy
|
||||
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.hid.HIDDataLegacy
|
||||
import dev.slimevr.hid.HIDReceiver
|
||||
import dev.slimevr.hid.HIDReceiverBehaviour
|
||||
import dev.slimevr.hid.HIDRotationButtonLegacy
|
||||
import solarxr_protocol.rpc.TapDetectionSetupNotification
|
||||
import solarxr_protocol.datatypes.TrackerActionMethod
|
||||
|
||||
class HIDButtonLegacyBehaviour : HIDReceiverBehaviour {
|
||||
class HIDButtonLegacyBehaviour(private val appContext: AppContextProvider) : HIDReceiverBehaviour {
|
||||
private val lastButton = mutableMapOf<Int, Int>()
|
||||
|
||||
override fun observe(receiver: HIDReceiver) {
|
||||
@@ -23,10 +24,11 @@ class HIDButtonLegacyBehaviour : HIDReceiverBehaviour {
|
||||
lastButton[hidId] = button
|
||||
if (!fired) return
|
||||
|
||||
if (!receiver.appContext.tapDetectionManager.context.state.value.setupMode) return
|
||||
val tracker = receiver.getTracker(hidId) ?: return
|
||||
receiver.appContext.server.sendSolarxrRpc(
|
||||
TapDetectionSetupNotification(tracker.context.state.value.id.toUShort()),
|
||||
appContext.trackerActionManager.actionTriggered(
|
||||
tracker.context.state.value.id,
|
||||
"HIDButtonLegacy",
|
||||
TrackerActionMethod.BUTTON,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
package dev.slimevr.hid.behaviours.v3
|
||||
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.hid.HIDButton
|
||||
import dev.slimevr.hid.HIDReceiver
|
||||
import dev.slimevr.hid.HIDReceiverBehaviour
|
||||
import solarxr_protocol.rpc.TapDetectionSetupNotification
|
||||
import solarxr_protocol.datatypes.TrackerActionMethod
|
||||
|
||||
class HIDButtonV3Behaviour : HIDReceiverBehaviour {
|
||||
class HIDButtonV3Behaviour(private val appContext: AppContextProvider) : HIDReceiverBehaviour {
|
||||
override fun observe(receiver: HIDReceiver) {
|
||||
receiver.packetEvents.on<HIDButton> { packet ->
|
||||
if (!receiver.appContext.tapDetectionManager.context.state.value.setupMode) return@on
|
||||
val tracker = receiver.getTracker(packet.hidId) ?: return@on
|
||||
receiver.appContext.server.sendSolarxrRpc(
|
||||
TapDetectionSetupNotification(tracker.context.state.value.id.toUShort()),
|
||||
appContext.trackerActionManager.actionTriggered(
|
||||
tracker.context.state.value.id,
|
||||
"HIDButtonV3",
|
||||
TrackerActionMethod.BUTTON,
|
||||
)
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ interface HIDReceiverBehaviour : Behaviour<HIDReceiver> {
|
||||
}
|
||||
typealias HIDPacketDispatcher = EventDispatcher<HIDPacket>
|
||||
|
||||
private fun v3Behaviours(): List<HIDReceiverBehaviour> = listOf(
|
||||
private fun v3Behaviours(appContext: AppContextProvider): List<HIDReceiverBehaviour> = listOf(
|
||||
HIDDongleInfoBehaviour(),
|
||||
HIDTrackerListBehaviour(),
|
||||
HIDDeviceInfoV3Behaviour(),
|
||||
@@ -86,17 +86,17 @@ private fun v3Behaviours(): List<HIDReceiverBehaviour> = listOf(
|
||||
HIDRssiBehaviour(),
|
||||
HIDPacketLossBehaviour(),
|
||||
HIDSleepV3Behaviour(),
|
||||
HIDButtonV3Behaviour(),
|
||||
HIDButtonV3Behaviour(appContext),
|
||||
)
|
||||
|
||||
private fun legacyBehaviours(): List<HIDReceiverBehaviour> = listOf(
|
||||
private fun legacyBehaviours(appContext: AppContextProvider): List<HIDReceiverBehaviour> = listOf(
|
||||
HIDRegistrationBehaviour(),
|
||||
HIDDeviceInfoBehaviour(),
|
||||
HIDRotationBehaviour(),
|
||||
HIDBatteryBehaviour(),
|
||||
HIDStatusBehaviour(),
|
||||
HIDSleepLegacyBehaviour(),
|
||||
HIDButtonLegacyBehaviour(),
|
||||
HIDButtonLegacyBehaviour(appContext),
|
||||
)
|
||||
|
||||
class HIDReceiver(
|
||||
@@ -119,7 +119,7 @@ class HIDReceiver(
|
||||
AppLogger.hid.warn("HID protocol changed ($current -> $version) for ${context.state.value.serialNumber}; restart to re-wire")
|
||||
return
|
||||
}
|
||||
val behaviours = if (version == HID_PROTOCOL_V3) v3Behaviours() else legacyBehaviours()
|
||||
val behaviours = if (version == HID_PROTOCOL_V3) v3Behaviours(appContext) else legacyBehaviours(appContext)
|
||||
context.behaviours.addAll(behaviours)
|
||||
behaviours.forEach { it.observe(this) }
|
||||
context.dispatch(HIDReceiverActions.SetProtocolVersion(version))
|
||||
|
||||
@@ -29,6 +29,7 @@ object AppLogger {
|
||||
val bvh = logger("BVH")
|
||||
val vmc = logger("VMC")
|
||||
val oscQuery = logger("OSCQuery")
|
||||
val mdns = logger("mDNS")
|
||||
val install = logger("Install")
|
||||
val resets = logger("Resets")
|
||||
val keybind = logger("Keybind")
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
package dev.slimevr.mdns
|
||||
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.multicast.MulticastBind
|
||||
import dev.slimevr.multicast.MulticastSocket
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.channelFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.retryWhen
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import kotlinx.coroutines.flow.transformLatest
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
private const val MDNS_PORT = 5353
|
||||
private val MDNS_GROUP = byteArrayOf(224.toByte(), 0, 0, 251.toByte())
|
||||
private val MAX_QUERY_INTERVAL = 60.seconds
|
||||
private val REBIND_DELAY = 5.seconds
|
||||
|
||||
data class MdnsDiscoveredService(
|
||||
val name: String,
|
||||
val type: String,
|
||||
val host: String,
|
||||
val port: Int,
|
||||
val addresses: List<String>,
|
||||
val txt: Map<String, String>,
|
||||
)
|
||||
|
||||
/** Advertises a [type] (e.g. "_oscjson._tcp") service named [name] until cancelled, then says goodbye. */
|
||||
typealias MdnsAdvertise = suspend (type: String, name: String, port: Int, txt: Map<String, String>) -> Nothing
|
||||
|
||||
/** Services of [type] currently on the network, kept up to date (and queried for) while collected. */
|
||||
typealias MdnsBrowse = (type: String) -> Flow<List<MdnsDiscoveredService>>
|
||||
|
||||
interface Mdns {
|
||||
val advertise: MdnsAdvertise
|
||||
val browse: MdnsBrowse
|
||||
}
|
||||
|
||||
private typealias RecordCache = Map<Any, Pair<MdnsRecord, TimeSource.Monotonic.ValueTimeMark>>
|
||||
|
||||
private fun RecordCache.unexpired() = filterValues { (_, expiry) -> !expiry.hasPassedNow() }
|
||||
|
||||
private val ticks = flow {
|
||||
while (true) {
|
||||
emit(Unit)
|
||||
delay(1.seconds)
|
||||
}
|
||||
}
|
||||
|
||||
private enum class MdnsReply { SERVICE, HOST }
|
||||
|
||||
private class MdnsSocket(private val socket: MulticastSocket, val address: String) {
|
||||
suspend fun send(packet: ByteArray) {
|
||||
try {
|
||||
socket.send(packet)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
AppLogger.mdns.warn(e, "mDNS send failed on $address")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What to send back for [question] about [service], null when the question is not about it. */
|
||||
private fun replyFor(question: MdnsQuestion, service: MdnsService): MdnsReply? {
|
||||
fun asks(vararg types: MdnsRecordType) = question.type == MdnsRecordType.ANY || question.type in types
|
||||
return when {
|
||||
question.name.equals(service.type, ignoreCase = true) && asks(MdnsRecordType.PTR) -> MdnsReply.SERVICE
|
||||
question.name.equals(service.instance, ignoreCase = true) && asks(MdnsRecordType.SRV, MdnsRecordType.TXT) -> MdnsReply.SERVICE
|
||||
question.name.equals(service.host, ignoreCase = true) && asks(MdnsRecordType.A) -> MdnsReply.HOST
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun repliesTo(questions: List<MdnsQuestion>, services: List<MdnsService>): List<ByteArray> = questions
|
||||
.flatMap { question -> services.mapNotNull { service -> replyFor(question, service)?.let { service to it } } }
|
||||
.toSet()
|
||||
.map { (service, reply) ->
|
||||
when (reply) {
|
||||
MdnsReply.SERVICE -> buildServiceResponse(service)
|
||||
MdnsReply.HOST -> buildHostResponse(service)
|
||||
}
|
||||
}
|
||||
|
||||
private val MdnsRecord.cacheKey: Any
|
||||
get() = when (this) {
|
||||
is MdnsRecord.Service -> "SRV" to name.lowercase()
|
||||
is MdnsRecord.Text -> "TXT" to name.lowercase()
|
||||
is MdnsRecord.Pointer, is MdnsRecord.Address -> this
|
||||
}
|
||||
|
||||
private fun servicesOf(records: Collection<MdnsRecord>, type: String): List<MdnsDiscoveredService> {
|
||||
val typeName = "$type.local"
|
||||
return records.filterIsInstance<MdnsRecord.Pointer>()
|
||||
.filter { it.name.equals(typeName, ignoreCase = true) }
|
||||
.mapNotNull { pointer ->
|
||||
val srv = records.filterIsInstance<MdnsRecord.Service>().firstOrNull { it.name.equals(pointer.target, ignoreCase = true) }
|
||||
?: return@mapNotNull null
|
||||
MdnsDiscoveredService(
|
||||
name = pointer.target.dropLast(typeName.length + 1),
|
||||
type = type,
|
||||
host = srv.host,
|
||||
port = srv.port,
|
||||
addresses = records.filterIsInstance<MdnsRecord.Address>().filter { it.name.equals(srv.host, ignoreCase = true) }.map { it.address },
|
||||
txt = records.filterIsInstance<MdnsRecord.Text>().firstOrNull { it.name.equals(pointer.target, ignoreCase = true) }?.entries.orEmpty(),
|
||||
)
|
||||
}
|
||||
.distinctBy { it.name }
|
||||
.sortedBy { it.name }
|
||||
}
|
||||
|
||||
/** Questions still needed to resolve [type] instances we only know by PTR, or hosts we have no address for. */
|
||||
private fun missingQuestions(records: Collection<MdnsRecord>, type: String): List<MdnsQuestion> {
|
||||
val typeName = "$type.local"
|
||||
val services = records.filterIsInstance<MdnsRecord.Service>()
|
||||
val pointers = records.filterIsInstance<MdnsRecord.Pointer>().filter { it.name.equals(typeName, ignoreCase = true) }
|
||||
val unresolved = pointers
|
||||
.filter { pointer -> services.none { it.name.equals(pointer.target, ignoreCase = true) } }
|
||||
.map { MdnsQuestion(it.target, MdnsRecordType.SRV) }
|
||||
val addressless = services
|
||||
.filter { srv -> pointers.any { it.target.equals(srv.name, ignoreCase = true) } }
|
||||
.filter { srv -> records.none { it is MdnsRecord.Address && it.name.equals(srv.host, ignoreCase = true) } }
|
||||
.map { MdnsQuestion(it.host, MdnsRecordType.A) }
|
||||
return unresolved + addressless
|
||||
}
|
||||
|
||||
/**
|
||||
* mDNS on the interface owning the latest [localAddress], through one multicast socket opened with
|
||||
* [bind] while anything is advertised or browsed. The socket is bound again whenever the address
|
||||
* changes, and after [REBIND_DELAY] when binding or listening fails.
|
||||
*
|
||||
* Responses are DNS-SD style: PTR as the answer, SRV/TXT/A as additional records. VRChat
|
||||
* only reads SRV/TXT/A from the additional records and drops responses carrying
|
||||
* them as answers
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
fun createMdns(scope: CoroutineScope, localAddress: Flow<String>, bind: MulticastBind): Mdns {
|
||||
val published = MutableStateFlow<List<MdnsService>>(emptyList())
|
||||
val cache = MutableStateFlow<RecordCache>(emptyMap())
|
||||
|
||||
fun onPacket(opened: MdnsSocket, packet: ByteArray) {
|
||||
val (questions, records) = try {
|
||||
parseQueryQuestions(packet) to parseResponseRecords(packet)
|
||||
} catch (_: IndexOutOfBoundsException) {
|
||||
return // malformed packet from someone else on the network
|
||||
}
|
||||
if (records.isNotEmpty()) {
|
||||
cache.update { current ->
|
||||
records.fold(current.unexpired()) { acc, (record, ttl) ->
|
||||
if (ttl == Duration.ZERO) acc - record.cacheKey else acc + (record.cacheKey to (record to TimeSource.Monotonic.markNow() + ttl))
|
||||
}
|
||||
}
|
||||
}
|
||||
val replies = repliesTo(questions, published.value)
|
||||
if (replies.isNotEmpty()) scope.launch { replies.forEach { opened.send(it) } }
|
||||
}
|
||||
|
||||
val socket = localAddress.distinctUntilChanged().transformLatest { address ->
|
||||
val bound = bind(MDNS_GROUP, MDNS_PORT, address)
|
||||
val opened = MdnsSocket(bound, address)
|
||||
try {
|
||||
coroutineScope {
|
||||
launch { bound.listen { packet -> onPacket(opened, packet) } }
|
||||
try {
|
||||
emit(opened)
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
withContext(NonCancellable) {
|
||||
published.value.forEach { opened.send(buildServiceResponse(it, ttl = Duration.ZERO)) }
|
||||
bound.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
cache.value = emptyMap()
|
||||
}
|
||||
}.retryWhen { cause, _ ->
|
||||
AppLogger.mdns.warn(cause, "mDNS socket failed, binding again in $REBIND_DELAY")
|
||||
delay(REBIND_DELAY)
|
||||
true
|
||||
}.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
|
||||
|
||||
return object : Mdns {
|
||||
override val advertise: MdnsAdvertise = { type, name, port, txt ->
|
||||
socket.collectLatest { opened ->
|
||||
val service = MdnsService(
|
||||
type = "$type.local",
|
||||
instance = "$name.$type.local",
|
||||
host = "$name.local",
|
||||
address = opened.address,
|
||||
port = port,
|
||||
txt = txt,
|
||||
)
|
||||
published.update { it + service }
|
||||
try {
|
||||
// Announce twice, one second apart (RFC 6762 8.3)
|
||||
opened.send(buildServiceResponse(service))
|
||||
delay(1.seconds)
|
||||
opened.send(buildServiceResponse(service))
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
withContext(NonCancellable) { opened.send(buildServiceResponse(service, ttl = Duration.ZERO)) }
|
||||
published.update { it - service }
|
||||
}
|
||||
}
|
||||
awaitCancellation()
|
||||
}
|
||||
|
||||
override val browse: MdnsBrowse = { type ->
|
||||
channelFlow {
|
||||
socket.collectLatest { opened ->
|
||||
coroutineScope {
|
||||
launch {
|
||||
var interval = 1.seconds
|
||||
while (true) {
|
||||
opened.send(buildQuery("$type.local", MdnsRecordType.PTR))
|
||||
delay(interval)
|
||||
interval = (interval * 2).coerceAtMost(MAX_QUERY_INTERVAL)
|
||||
}
|
||||
}
|
||||
val asked = mutableSetOf<MdnsQuestion>()
|
||||
combine(cache, ticks) { entries, _ -> entries.unexpired().values.map { (record, _) -> record } }
|
||||
.distinctUntilChanged()
|
||||
.collect { records ->
|
||||
missingQuestions(records, type)
|
||||
.filter { asked.add(it) }
|
||||
.forEach { opened.send(buildQuery(it.name, requireNotNull(it.type))) }
|
||||
send(servicesOf(records, type))
|
||||
}
|
||||
}
|
||||
}
|
||||
}.distinctUntilChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package dev.slimevr.mdns
|
||||
|
||||
import kotlinx.io.Buffer
|
||||
import kotlinx.io.readByteArray
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
private const val CLASS_IN = 1
|
||||
|
||||
private val SERVICE_TTL = 75.minutes
|
||||
private val HOST_TTL = 2.minutes
|
||||
|
||||
internal enum class MdnsRecordType(val code: Int) {
|
||||
A(1),
|
||||
PTR(12),
|
||||
TXT(16),
|
||||
SRV(33),
|
||||
ANY(255),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromCode(code: Int) = entries.firstOrNull { it.code == code }
|
||||
}
|
||||
}
|
||||
|
||||
/** One of our published services, with fully qualified names ("…local"). */
|
||||
internal data class MdnsService(
|
||||
val type: String,
|
||||
val instance: String,
|
||||
val host: String,
|
||||
val address: String,
|
||||
val port: Int,
|
||||
val txt: Map<String, String>,
|
||||
)
|
||||
|
||||
/** [type] is null for record types we never answer. */
|
||||
internal data class MdnsQuestion(val name: String, val type: MdnsRecordType?)
|
||||
|
||||
/** The records we read from other responders; any other type is skipped. */
|
||||
internal sealed interface MdnsRecord {
|
||||
val name: String
|
||||
|
||||
data class Pointer(override val name: String, val target: String) : MdnsRecord
|
||||
data class Service(override val name: String, val port: Int, val host: String) : MdnsRecord
|
||||
data class Text(override val name: String, val entries: Map<String, String>) : MdnsRecord
|
||||
data class Address(override val name: String, val address: String) : MdnsRecord
|
||||
}
|
||||
|
||||
/** A TTL of zero is a goodbye: the record must be forgotten. */
|
||||
internal data class ReceivedRecord(val record: MdnsRecord, val ttl: Duration)
|
||||
|
||||
internal fun buildServiceResponse(service: MdnsService, ttl: Duration = SERVICE_TTL): ByteArray = buildPacket(flags = 0x8400, answers = 1, additional = 3) {
|
||||
writeRecord(service.type, MdnsRecordType.PTR, ttl, encodeName(service.instance))
|
||||
writeRecord(service.instance, MdnsRecordType.TXT, ttl, encodeTxt(service.txt))
|
||||
writeRecord(service.instance, MdnsRecordType.SRV, ttl, encodeSrv(service.port, service.host))
|
||||
writeRecord(service.host, MdnsRecordType.A, if (ttl == Duration.ZERO) Duration.ZERO else HOST_TTL, encodeIpv4(service.address))
|
||||
}
|
||||
|
||||
internal fun buildHostResponse(service: MdnsService): ByteArray = buildPacket(flags = 0x8400, answers = 1) {
|
||||
writeRecord(service.host, MdnsRecordType.A, HOST_TTL, encodeIpv4(service.address))
|
||||
}
|
||||
|
||||
internal fun buildQuery(name: String, type: MdnsRecordType): ByteArray = buildPacket(flags = 0, questions = 1) {
|
||||
write(encodeName(name))
|
||||
writeShort(type.code.toShort())
|
||||
writeShort(CLASS_IN.toShort())
|
||||
}
|
||||
|
||||
private fun buildPacket(flags: Int, questions: Int = 0, answers: Int = 0, additional: Int = 0, body: Buffer.() -> Unit): ByteArray = Buffer().apply {
|
||||
writeShort(0) // id
|
||||
writeShort(flags.toShort())
|
||||
writeShort(questions.toShort())
|
||||
writeShort(answers.toShort())
|
||||
writeShort(0) // authority
|
||||
writeShort(additional.toShort())
|
||||
body()
|
||||
}.readByteArray()
|
||||
|
||||
private fun Buffer.writeRecord(name: String, type: MdnsRecordType, ttl: Duration, data: ByteArray) {
|
||||
write(encodeName(name))
|
||||
writeShort(type.code.toShort())
|
||||
writeShort(CLASS_IN.toShort())
|
||||
writeInt(ttl.inWholeSeconds.toInt())
|
||||
writeShort(data.size.toShort())
|
||||
write(data)
|
||||
}
|
||||
|
||||
private fun encodeName(name: String): ByteArray = Buffer().apply {
|
||||
name.split('.').filter { it.isNotEmpty() }.forEach { label ->
|
||||
val bytes = label.encodeToByteArray()
|
||||
writeByte(bytes.size.toByte())
|
||||
write(bytes)
|
||||
}
|
||||
writeByte(0)
|
||||
}.readByteArray()
|
||||
|
||||
private fun encodeTxt(txt: Map<String, String>): ByteArray = Buffer().apply {
|
||||
txt.forEach { (key, value) ->
|
||||
val bytes = "$key=$value".encodeToByteArray()
|
||||
writeByte(bytes.size.toByte())
|
||||
write(bytes)
|
||||
}
|
||||
}.readByteArray()
|
||||
|
||||
private fun encodeSrv(port: Int, host: String): ByteArray = Buffer().apply {
|
||||
writeShort(0) // priority
|
||||
writeShort(0) // weight
|
||||
writeShort(port.toShort())
|
||||
write(encodeName(host))
|
||||
}.readByteArray()
|
||||
|
||||
private fun encodeIpv4(address: String): ByteArray {
|
||||
val octets = address.split('.').map { it.toInt() }
|
||||
require(octets.size == 4 && octets.all { it in 0..255 }) { "Not an IPv4 address: $address" }
|
||||
return ByteArray(4) { octets[it].toByte() }
|
||||
}
|
||||
|
||||
private fun ByteArray.isResponse() = u16(2) and 0x8000 != 0
|
||||
|
||||
internal fun parseQueryQuestions(packet: ByteArray): List<MdnsQuestion> {
|
||||
if (packet.size < 12 || packet.isResponse()) return emptyList()
|
||||
var offset = 12
|
||||
return List(packet.u16(4)) {
|
||||
val (name, end) = readName(packet, offset)
|
||||
offset = end + 4 // type + class
|
||||
MdnsQuestion(name, MdnsRecordType.fromCode(packet.u16(end)))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseResponseRecords(packet: ByteArray): List<ReceivedRecord> {
|
||||
if (packet.size < 12 || !packet.isResponse()) return emptyList()
|
||||
var offset = 12
|
||||
repeat(packet.u16(4)) { offset = readName(packet, offset).second + 4 }
|
||||
val count = packet.u16(6) + packet.u16(8) + packet.u16(10)
|
||||
return List(count) {
|
||||
val (name, end) = readName(packet, offset)
|
||||
val type = MdnsRecordType.fromCode(packet.u16(end))
|
||||
val ttl = ((packet.u16(end + 4).toLong() shl 16) or packet.u16(end + 6).toLong()).seconds
|
||||
val length = packet.u16(end + 8)
|
||||
val data = end + 10
|
||||
offset = data + length
|
||||
if (offset > packet.size) throw IndexOutOfBoundsException("mDNS record past end of packet")
|
||||
val record = when (type) {
|
||||
MdnsRecordType.PTR -> MdnsRecord.Pointer(name, readName(packet, data).first)
|
||||
MdnsRecordType.SRV -> MdnsRecord.Service(name, port = packet.u16(data + 4), host = readName(packet, data + 6).first)
|
||||
MdnsRecordType.TXT -> MdnsRecord.Text(name, decodeTxt(packet.copyOfRange(data, offset)))
|
||||
MdnsRecordType.A -> if (length == 4) MdnsRecord.Address(name, (0..3).joinToString(".") { (packet[data + it].toInt() and 0xFF).toString() }) else null
|
||||
else -> null
|
||||
}
|
||||
record?.let { ReceivedRecord(it, ttl) }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
private fun decodeTxt(data: ByteArray): Map<String, String> {
|
||||
val entries = mutableMapOf<String, String>()
|
||||
var offset = 0
|
||||
while (offset < data.size) {
|
||||
val length = data[offset].toInt() and 0xFF
|
||||
val entry = data.copyOfRange(offset + 1, offset + 1 + length).decodeToString()
|
||||
if (entry.isNotEmpty()) entries[entry.substringBefore('=')] = entry.substringAfter('=', "")
|
||||
offset += 1 + length
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
private fun readName(packet: ByteArray, start: Int): Pair<String, Int> {
|
||||
val labels = mutableListOf<String>()
|
||||
var offset = start
|
||||
var end = -1
|
||||
var jumps = 0
|
||||
while (true) {
|
||||
val length = packet[offset].toInt() and 0xFF
|
||||
when {
|
||||
length == 0 -> {
|
||||
if (end < 0) end = offset + 1
|
||||
return labels.joinToString(".") to end
|
||||
}
|
||||
|
||||
length and 0xC0 == 0xC0 -> {
|
||||
if (end < 0) end = offset + 2
|
||||
if (++jumps > 16) throw IndexOutOfBoundsException("mDNS name pointer loop")
|
||||
offset = ((length and 0x3F) shl 8) or (packet[offset + 1].toInt() and 0xFF)
|
||||
}
|
||||
|
||||
else -> {
|
||||
labels += packet.copyOfRange(offset + 1, offset + 1 + length).decodeToString()
|
||||
offset += 1 + length
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ByteArray.u16(offset: Int) = ((this[offset].toInt() and 0xFF) shl 8) or (this[offset + 1].toInt() and 0xFF)
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.slimevr.multicast
|
||||
|
||||
interface MulticastSocket {
|
||||
/** Calls [onPacket] for every datagram received on the group, until the socket closes. */
|
||||
suspend fun listen(onPacket: (ByteArray) -> Unit)
|
||||
|
||||
/** Sends [payload] to the group. */
|
||||
suspend fun send(payload: ByteArray)
|
||||
|
||||
suspend fun close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an IPv4 socket on [port], shared with other processes bound to it, joined to the [group]
|
||||
* multicast address on the interface owning [interfaceAddress]. Provided by each platform.
|
||||
*/
|
||||
typealias MulticastBind = suspend (group: ByteArray, port: Int, interfaceAddress: String) -> MulticastSocket
|
||||
@@ -23,13 +23,22 @@ class OscSender(private val address: String, private val port: Int) {
|
||||
suspend fun send(message: OscMessage) {
|
||||
val buf = Buffer()
|
||||
writeMessage(buf, message)
|
||||
socket().send(Datagram(buf, InetSocketAddress(address, port)))
|
||||
send(buf)
|
||||
}
|
||||
|
||||
suspend fun send(bundle: OscBundle) {
|
||||
val buf = Buffer()
|
||||
writeBundle(buf, bundle)
|
||||
socket().send(Datagram(buf, InetSocketAddress(address, port)))
|
||||
send(buf)
|
||||
}
|
||||
|
||||
private suspend fun send(buf: Buffer) {
|
||||
try {
|
||||
socket().send(Datagram(buf, InetSocketAddress(address, port)))
|
||||
} catch (e: Exception) {
|
||||
close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package dev.slimevr.oscquery
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.client.plugins.HttpTimeout
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
private val oscQueryHttpClient = HttpClient(CIO) {
|
||||
install(HttpTimeout) {
|
||||
connectTimeoutMillis = 2_000
|
||||
requestTimeoutMillis = 5_000
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OSC port of the OSCQuery host at [address]:[port], read from its HOST_INFO. Only OSC_PORT is read:
|
||||
* the rest varies between implementations (e.g. extension names we don't model).
|
||||
*/
|
||||
suspend fun fetchOscQueryOscPort(address: String, port: Int): Int {
|
||||
val host = if (':' in address) "[$address]" else address
|
||||
val hostInfo = oscQueryJson.parseToJsonElement(oscQueryHttpClient.get("http://$host:$port/?HOST_INFO").bodyAsText())
|
||||
return hostInfo.jsonObject.getValue("OSC_PORT").jsonPrimitive.int
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package dev.slimevr.oscquery
|
||||
|
||||
import com.appstractive.dnssd.DiscoveryEvent
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
|
||||
|
||||
class OscQueryDiscovery(
|
||||
private val discoverServicesFlow: (String) -> Flow<DiscoveryEvent>,
|
||||
private val serviceType: String = OSC_JSON_SERVICE_TYPE,
|
||||
private val serviceFilter: (String) -> Boolean = { true },
|
||||
) {
|
||||
private val mutableServices = MutableStateFlow<List<OscQueryService>>(emptyList())
|
||||
val services: StateFlow<List<OscQueryService>> = mutableServices.asStateFlow()
|
||||
|
||||
private var job: Job? = null
|
||||
|
||||
fun start(scope: CoroutineScope) {
|
||||
if (job != null) return
|
||||
job = scope.launch {
|
||||
discoverServicesFlow(serviceType).collect { event ->
|
||||
when (event) {
|
||||
is DiscoveryEvent.Discovered -> {
|
||||
if (!serviceFilter(event.service.name)) return@collect
|
||||
event.resolve()
|
||||
}
|
||||
|
||||
is DiscoveryEvent.Resolved -> onResolved(event)
|
||||
|
||||
is DiscoveryEvent.Removed -> onRemoved(event.service.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun close() {
|
||||
job?.cancelAndJoin()
|
||||
job = null
|
||||
mutableServices.value = emptyList()
|
||||
}
|
||||
|
||||
private fun onRemoved(name: String) {
|
||||
if (!serviceFilter(name)) return
|
||||
mutableServices.value = mutableServices.value.filterNot { entry -> entry.name == name }
|
||||
}
|
||||
|
||||
private suspend fun onResolved(event: DiscoveryEvent.Resolved) {
|
||||
val service = event.service
|
||||
val name = service.name
|
||||
if (!serviceFilter(name)) return
|
||||
|
||||
val resolved = OscQueryService(
|
||||
name = name,
|
||||
addresses = service.addresses,
|
||||
host = service.host,
|
||||
type = service.type,
|
||||
port = service.port,
|
||||
txt = service.txt.mapValues { (_, value) -> value?.decodeToString().orEmpty() },
|
||||
)
|
||||
AppLogger.oscQuery.info(
|
||||
"OSCQuery discovered service: name=$name address=${service.addresses.firstOrNull().orEmpty()} port=${service.port}",
|
||||
)
|
||||
mutableServices.value = mutableServices.value
|
||||
.filterNot { existing -> existing.name == name }
|
||||
.plus(resolved)
|
||||
.sortedBy { entry -> entry.name }
|
||||
}
|
||||
}
|
||||
@@ -84,12 +84,3 @@ data class OscQueryNode(
|
||||
return fullPath.substring(0, parentEnd).ifEmpty { "/" }
|
||||
}
|
||||
}
|
||||
|
||||
data class OscQueryService(
|
||||
val name: String,
|
||||
val addresses: List<String>,
|
||||
val host: String,
|
||||
val type: String,
|
||||
val port: Int,
|
||||
val txt: Map<String, String>,
|
||||
)
|
||||
@@ -1,35 +1,28 @@
|
||||
package dev.slimevr.oscquery
|
||||
|
||||
import com.appstractive.dnssd.NetService
|
||||
import dev.slimevr.mdns.MdnsAdvertise
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
|
||||
private const val OSC_UDP_SERVICE_TYPE = "_osc._udp"
|
||||
|
||||
typealias OscQueryServiceFactory = (
|
||||
type: String,
|
||||
name: String,
|
||||
port: Int,
|
||||
priority: Int,
|
||||
weight: Int,
|
||||
addresses: List<String>?,
|
||||
txt: Map<String, String>,
|
||||
) -> NetService
|
||||
|
||||
class OscQueryServer(
|
||||
private val name: String,
|
||||
private val address: String,
|
||||
private var oscPort: UShort,
|
||||
private val serviceFactory: OscQueryServiceFactory,
|
||||
private val localAddress: StateFlow<String>,
|
||||
oscPort: UShort,
|
||||
private val advertise: MdnsAdvertise,
|
||||
private val tree: OscQueryTree = OscQueryTree(),
|
||||
private val transport: OscQueryTransport = OscQueryTransport.UDP,
|
||||
) {
|
||||
private val httpServer = OscQueryHttpServer(hostInfo = ::buildHostInfo, tree = tree)
|
||||
private var oscQueryService: NetService? = null
|
||||
private var oscService: NetService? = null
|
||||
private var started = false
|
||||
private val oscPort = MutableStateFlow(oscPort)
|
||||
|
||||
val oscQueryPort: UShort
|
||||
get() = httpServer.port
|
||||
@@ -39,65 +32,44 @@ class OscQueryServer(
|
||||
fun removeNode(path: String): Boolean = tree.remove(path)
|
||||
|
||||
suspend fun start(scope: CoroutineScope) {
|
||||
if (started) return
|
||||
val httpPort = httpServer.start(scope)
|
||||
oscQueryService = createOscQueryService(httpPort).also { it.register() }
|
||||
oscService = createOscService(oscPort).also { it.register() }
|
||||
started = true
|
||||
httpServer.start(scope)
|
||||
}
|
||||
|
||||
suspend fun updateOscPort(port: UShort) {
|
||||
if (oscPort == port) return
|
||||
oscPort = port
|
||||
if (!started) return
|
||||
withContext(NonCancellable) {
|
||||
oscService?.unregister()
|
||||
oscService = createOscService(port).also { it.register() }
|
||||
suspend fun advertise(): Nothing {
|
||||
combine(localAddress, oscPort, ::Pair).collectLatest { (address, port) ->
|
||||
val instanceName = instanceName(name, address, port)
|
||||
coroutineScope {
|
||||
launch {
|
||||
advertise(
|
||||
OSC_JSON_SERVICE_TYPE,
|
||||
instanceName,
|
||||
oscQueryPort.toInt(),
|
||||
mapOf("txtvers" to "1", "osc_transport" to transport.name.lowercase(), "osc_port" to port.toString()),
|
||||
)
|
||||
}
|
||||
advertise(OSC_UDP_SERVICE_TYPE, instanceName, port.toInt(), mapOf("txtvers" to "1", "oscquery_port" to oscQueryPort.toString()))
|
||||
}
|
||||
}
|
||||
awaitCancellation()
|
||||
}
|
||||
|
||||
suspend fun close() {
|
||||
withContext(NonCancellable) {
|
||||
oscService?.unregister()
|
||||
oscService = null
|
||||
oscQueryService?.unregister()
|
||||
oscQueryService = null
|
||||
}
|
||||
fun updateOscPort(port: UShort) {
|
||||
oscPort.value = port
|
||||
}
|
||||
|
||||
fun close() {
|
||||
httpServer.close()
|
||||
started = false
|
||||
}
|
||||
|
||||
private fun createOscQueryService(httpPort: UShort) = createService(
|
||||
type = OSC_JSON_SERVICE_TYPE,
|
||||
name = "$name-$httpPort",
|
||||
port = httpPort.toInt(),
|
||||
txt = mapOf(
|
||||
"txtvers" to "1",
|
||||
"osc_transport" to transport.name.lowercase(),
|
||||
"osc_port" to oscPort.toString(),
|
||||
),
|
||||
)
|
||||
|
||||
private fun createOscService(port: UShort) = createService(
|
||||
type = OSC_UDP_SERVICE_TYPE,
|
||||
name = "$name-$oscQueryPort",
|
||||
port = port.toInt(),
|
||||
txt = mapOf(
|
||||
"txtvers" to "1",
|
||||
"oscquery_port" to oscQueryPort.toString(),
|
||||
),
|
||||
)
|
||||
|
||||
// Pin the advertised address to our resolved local IP. Otherwise dns-sd-kt
|
||||
// falls back to `getLocalAddresses().firstOrNull()` which iterates every NIC
|
||||
// and may pick a virtual / wrong-subnet adapter, making the service
|
||||
// unreachable from headsets on the actual LAN.
|
||||
private fun createService(type: String, name: String, port: Int, txt: Map<String, String>): NetService = serviceFactory(type, name, port, 0, 1, listOf(address), txt)
|
||||
|
||||
private fun buildHostInfo() = OscQueryHostInfo(
|
||||
name = name,
|
||||
oscIp = address,
|
||||
oscPort = oscPort,
|
||||
oscIp = localAddress.value,
|
||||
oscPort = oscPort.value,
|
||||
oscTransport = transport,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun instanceName(name: String, address: String, oscPort: UShort): String {
|
||||
val suffix = ("$address:$oscPort".hashCode().toUInt() % 0x1000000u).toString(16).uppercase().padStart(6, '0')
|
||||
return "$name-$suffix"
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import dev.slimevr.tracker.Tracker
|
||||
import dev.slimevr.tracker.TrackerActions
|
||||
import dev.slimevr.tracker.behaviours.TrackerRotationRefreshBehaviour
|
||||
import dev.slimevr.util.isActive
|
||||
import dev.slimevr.vrcosc.VRCOSCManager
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -45,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,
|
||||
@@ -66,6 +70,7 @@ class ResetsManager(
|
||||
val server: VRServer,
|
||||
val settings: Settings,
|
||||
val skeleton: Skeleton,
|
||||
val vrcOscManager: VRCOSCManager?,
|
||||
private val stepMountingManager: StepMountingManager,
|
||||
private val errorReporting: ErrorReportingManager,
|
||||
) {
|
||||
@@ -101,7 +106,7 @@ class ResetsManager(
|
||||
* resetSourceName is used for logging
|
||||
* If bodyParts is null, resets all trackers.
|
||||
*/
|
||||
suspend fun scheduleReset(resetSourceName: String, resetType: ResetType, delay: Float = 0f, bodyParts: List<BodyPart>? = null) {
|
||||
suspend fun scheduleReset(resetSourceName: String, resetType: ResetType, delay: Float = 0f, bodyParts: List<BodyPart>? = null, solarXRBridgeId: Int? = null, txId: UInt? = null) {
|
||||
val method = settings.context.state.value.data.resetsConfig.mountingMethod.takeIf { resetType == ResetType.MOUNTING }
|
||||
if (method == MountingMethod.UNKNOWN || method == MountingMethod.MANUAL) {
|
||||
AppLogger.resets.info("Ignoring mounting reset from $resetSourceName: the mounting method is $method")
|
||||
@@ -127,7 +132,7 @@ class ResetsManager(
|
||||
}
|
||||
|
||||
resetJob.cancelAndJoin()
|
||||
resetJob = context.scope.launch { runReset(resetSourceName, resetType, method, delay, bodyParts) }
|
||||
resetJob = context.scope.launch { runReset(resetSourceName, resetType, method, delay, bodyParts, solarXRBridgeId, txId) }
|
||||
}
|
||||
|
||||
suspend fun cancel() {
|
||||
@@ -135,7 +140,7 @@ class ResetsManager(
|
||||
resetJob.cancelAndJoin()
|
||||
}
|
||||
|
||||
private suspend fun runReset(resetSourceName: String, resetType: ResetType, method: MountingMethod?, delaySeconds: Float, bodyParts: List<BodyPart>?) {
|
||||
private suspend fun runReset(resetSourceName: String, resetType: ResetType, method: MountingMethod?, delaySeconds: Float, bodyParts: List<BodyPart>?, solarXRBridgeId: Int?, txId: UInt?) {
|
||||
val delayMs = (delaySeconds * 1000).toInt()
|
||||
var lastDetail: ResetDetail = CountdownDetail(0, delayMs)
|
||||
|
||||
@@ -143,7 +148,9 @@ class ResetsManager(
|
||||
lastDetail = detail
|
||||
val status = ResetStatusResponse(resetType, lifecycle, bodyParts, detail)
|
||||
context.dispatch(ResetsActions.SetStatus(status))
|
||||
server.sendSolarxrRpc(status)
|
||||
server.context.state.value.solarxr.values.forEach { bridge ->
|
||||
bridge.sendRpc(status, if (bridge.id == solarXRBridgeId) txId else null)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -170,7 +177,12 @@ class ResetsManager(
|
||||
return
|
||||
}
|
||||
} else {
|
||||
executeTrackerResets(resetType, method, bodyParts, config)
|
||||
val referenceRotation = executeTrackerResets(resetType, method, bodyParts, config)
|
||||
|
||||
// Yaw align VRCOSC
|
||||
if (resetType == ResetType.FULL || resetType == ResetType.YAW) {
|
||||
vrcOscManager?.yawAlign(referenceRotation)
|
||||
}
|
||||
}
|
||||
|
||||
if (resetType == ResetType.FULL) {
|
||||
@@ -224,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
|
||||
|
||||
@@ -323,7 +340,7 @@ class ResetsManager(
|
||||
}
|
||||
}
|
||||
|
||||
private fun executeTrackerResets(resetType: ResetType, method: MountingMethod?, bodyParts: List<BodyPart>?, config: ResetsConfig) {
|
||||
private fun executeTrackerResets(resetType: ResetType, method: MountingMethod?, bodyParts: List<BodyPart>?, config: ResetsConfig): Quaternion {
|
||||
val allTrackers = server.context.state.value.trackers.values
|
||||
|
||||
// Get the reference. The reference is used to align rotation/spaces.
|
||||
@@ -352,10 +369,13 @@ class ResetsManager(
|
||||
// Do the actual reset
|
||||
it.context.dispatch(getResetAction(referenceRotation, resetType, it.context.state.value.bodyPart, config))
|
||||
}
|
||||
|
||||
return referenceRotation
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun create(ctx: Phase1ContextProvider, skeleton: Skeleton, stepMountingManager: StepMountingManager, scope: CoroutineScope): ResetsManager {
|
||||
// TODO vrcOscManager is only nullable for tests bc I'm lazy
|
||||
fun create(ctx: Phase1ContextProvider, skeleton: Skeleton, vrcOscManager: VRCOSCManager?, stepMountingManager: StepMountingManager, scope: CoroutineScope): ResetsManager {
|
||||
val context = Context.create(
|
||||
initialState = ResetsState(
|
||||
canDoYawReset = false,
|
||||
@@ -367,7 +387,7 @@ class ResetsManager(
|
||||
behaviours = listOf(ResetsMountingTimeoutBehaviour()),
|
||||
name = "ResetsManager",
|
||||
)
|
||||
return ResetsManager(context, ctx.server, ctx.config.settings, skeleton, stepMountingManager, ctx.errorReporting)
|
||||
return ResetsManager(context, ctx.server, ctx.config.settings, skeleton, vrcOscManager, stepMountingManager, ctx.errorReporting)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,10 @@ import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import java.util.EnumMap
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.random.Random
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
@@ -67,21 +69,27 @@ class LocalizerResetBehaviour(val settings: Settings) : SkeletonBehaviour {
|
||||
}
|
||||
}
|
||||
|
||||
class YouSpinMeRightRoundBehaviour(val inputHz: Int = 1) : SkeletonBehaviour {
|
||||
/**
|
||||
* randomPacketLoss and constantPacketLoss are from 0 to 1
|
||||
* sendPosition is for the head data.
|
||||
*/
|
||||
class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f, val randomPacketLoss: Float = 0f, val constantPacketLoss: Float = 0f, val sendPosition: Boolean = false) : SkeletonBehaviour {
|
||||
override fun observe(receiver: Skeleton) {
|
||||
receiver.context.scope.launch {
|
||||
val intervalMs = (millisecondsInSecond / inputHz.toFloat()).toLong()
|
||||
val interval = (millisecondsInSecond / inputHz.toFloat()).toLong().milliseconds
|
||||
val startTime = timeSource.markNow()
|
||||
while (true) {
|
||||
delay(intervalMs)
|
||||
val elapsed = startTime.elapsedNow().inWholeMilliseconds / millisecondsInSecond
|
||||
delay(interval / abs(constantPacketLoss - 1f).toDouble())
|
||||
|
||||
// Simulate packet loss
|
||||
if (Random.nextFloat() < randomPacketLoss) continue
|
||||
|
||||
val elapsed = startTime.elapsedNow().inWholeMilliseconds / millisecondsInSecond * speed
|
||||
val state = receiver.context.state.value
|
||||
|
||||
receiver.context.dispatch(
|
||||
SkeletonActions.SetBonePose(
|
||||
BodyPart.LOWER_CHEST,
|
||||
Vector3.ZERO,
|
||||
inputHz.toUShort(),
|
||||
Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)),
|
||||
Vector3.ZERO,
|
||||
null,
|
||||
@@ -90,28 +98,26 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 1) : SkeletonBehaviour {
|
||||
receiver.context.dispatch(
|
||||
SkeletonActions.SetBonePose(
|
||||
BodyPart.LEFT_LOWER_LEG,
|
||||
Vector3.ZERO,
|
||||
inputHz.toUShort(),
|
||||
Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)),
|
||||
Vector3.ZERO,
|
||||
null,
|
||||
),
|
||||
)
|
||||
|
||||
val circleRadius = 0.5f
|
||||
val circleX = cos(elapsed * 2f) * circleRadius
|
||||
val circleZ = sin(elapsed * 2f) * circleRadius
|
||||
val jumpHeight = maxOf(0f, sin(elapsed * 3f) * 0.3f)
|
||||
receiver.context.dispatch(
|
||||
SkeletonActions.SetBonePose(
|
||||
BodyPart.HEAD,
|
||||
Vector3.ZERO,
|
||||
inputHz.toUShort(),
|
||||
Quaternion.IDENTITY,
|
||||
Vector3.ZERO,
|
||||
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
|
||||
),
|
||||
)
|
||||
if (sendPosition) {
|
||||
val circleRadius = 0.5f
|
||||
val circleX = cos(elapsed * 2f) * circleRadius
|
||||
val circleZ = sin(elapsed * 2f) * circleRadius
|
||||
val jumpHeight = maxOf(0f, sin(elapsed * 3f) * 0.3f)
|
||||
receiver.context.dispatch(
|
||||
SkeletonActions.SetBonePose(
|
||||
BodyPart.HEAD,
|
||||
Quaternion.IDENTITY,
|
||||
Vector3.ZERO,
|
||||
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -290,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, null, boneInput.position, false))
|
||||
receiver.context.dispatch(SkeletonActions.SetBonePose(BodyPart.HEAD, null, null, boneInput.position, false))
|
||||
}
|
||||
}
|
||||
// Inputs changed; re-run FK
|
||||
@@ -302,7 +308,7 @@ class ComputedSkeletonBehaviour(
|
||||
for (processor in targetProcessors) processor.process(ikTargets, mutableBoneInputs, mutableComputedSkeleton, targetState.floorLevel)
|
||||
|
||||
// Run IK
|
||||
ccdIk(
|
||||
val ikSuccess = ccdIk(
|
||||
mutableBoneInputs,
|
||||
mutableComputedSkeleton,
|
||||
ikTargets.map { (bodyPart, target) ->
|
||||
@@ -311,10 +317,15 @@ class ComputedSkeletonBehaviour(
|
||||
target,
|
||||
)
|
||||
},
|
||||
BODY_PART_OFFSET_CONSTRAINT_MAP,
|
||||
BODY_PART_CONSTRAINT_MAP,
|
||||
IK_THRESHOLD,
|
||||
IK_MAX_ITERATIONS,
|
||||
)
|
||||
// TODO Make this not spam logs on repeated failures
|
||||
// if (!ikSuccess) {
|
||||
// AppLogger.skeleton.warn("IK step did not meet all requested targets within $IK_THRESHOLD meters")
|
||||
// }
|
||||
|
||||
// Save or restore paused tracking
|
||||
if (targetState.pausedProcessedBoneInputs != null) {
|
||||
|
||||
@@ -2,199 +2,201 @@ package dev.slimevr.skeleton
|
||||
|
||||
import com.jme3.math.FastMath
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
|
||||
// For fingers and toes
|
||||
// TODO: should constrain splay separately from swing.
|
||||
private val DIGIT_CONSTRAINT = TwistSwingConstraint(
|
||||
10f * FastMath.DEG_TO_RAD,
|
||||
115f * FastMath.DEG_TO_RAD,
|
||||
private val METACARPAL_THUMB_CONSTRAINT = LooseHingeConstraint(
|
||||
-80f * FastMath.DEG_TO_RAD,
|
||||
100f * FastMath.DEG_TO_RAD,
|
||||
55f * FastMath.DEG_TO_RAD,
|
||||
Vector3.NEG_X,
|
||||
)
|
||||
private val THUMB_CONSTRAINT = LooseHingeConstraint(
|
||||
-5f * FastMath.DEG_TO_RAD,
|
||||
100f * FastMath.DEG_TO_RAD,
|
||||
3f * FastMath.DEG_TO_RAD,
|
||||
Vector3.NEG_X,
|
||||
)
|
||||
|
||||
private val LEFT_PROXIMAL_FINGER_CONSTRAINT = LooseHingeConstraint(
|
||||
-65f * FastMath.DEG_TO_RAD,
|
||||
110f * FastMath.DEG_TO_RAD,
|
||||
30f * FastMath.DEG_TO_RAD,
|
||||
Vector3.POS_Z,
|
||||
)
|
||||
private val LEFT_FINGER_CONSTRAINT = LooseHingeConstraint(
|
||||
-5f * FastMath.DEG_TO_RAD,
|
||||
110f * FastMath.DEG_TO_RAD,
|
||||
3f,
|
||||
Vector3.POS_Z,
|
||||
)
|
||||
private val RIGHT_PROXIMAL_FINGER_CONSTRAINT = LEFT_PROXIMAL_FINGER_CONSTRAINT.copy(hingeAxis = Vector3.NEG_Z)
|
||||
private val RIGHT_FINGER_CONSTRAINT = LEFT_FINGER_CONSTRAINT.copy(hingeAxis = Vector3.NEG_Z)
|
||||
|
||||
private val TOE_CONSTRAINT = LooseHingeConstraint(
|
||||
-70f * FastMath.DEG_TO_RAD,
|
||||
90f * FastMath.DEG_TO_RAD,
|
||||
30f * FastMath.DEG_TO_RAD,
|
||||
Vector3.NEG_X,
|
||||
)
|
||||
|
||||
// TODO Actually figure out good values for these constraints, maybe a source would be
|
||||
// good?
|
||||
val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
|
||||
mapOf(
|
||||
// Left arm
|
||||
BodyPart.LEFT_SHOULDER to TwistSwingConstraint(
|
||||
105f * FastMath.DEG_TO_RAD,
|
||||
45f * FastMath.DEG_TO_RAD,
|
||||
70f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.LEFT_UPPER_ARM to TwistSwingConstraint(
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
180f * FastMath.DEG_TO_RAD,
|
||||
BodyPart.LEFT_UPPER_ARM to FreeHingeConstraint(
|
||||
-40f * FastMath.DEG_TO_RAD,
|
||||
125f * FastMath.DEG_TO_RAD,
|
||||
Vector3.POS_Y,
|
||||
),
|
||||
BodyPart.LEFT_LOWER_ARM to LooseHingeConstraint(
|
||||
-180f * FastMath.DEG_TO_RAD,
|
||||
-160f * FastMath.DEG_TO_RAD,
|
||||
0f * FastMath.DEG_TO_RAD,
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
55f * FastMath.DEG_TO_RAD,
|
||||
Vector3.NEG_Z,
|
||||
),
|
||||
BodyPart.LEFT_HAND to TwistSwingConstraint(
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
70f * FastMath.DEG_TO_RAD,
|
||||
95f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
|
||||
// Right arm
|
||||
BodyPart.RIGHT_SHOULDER to TwistSwingConstraint(
|
||||
105f * FastMath.DEG_TO_RAD,
|
||||
45f * FastMath.DEG_TO_RAD,
|
||||
70f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.RIGHT_UPPER_ARM to TwistSwingConstraint(
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
180f * FastMath.DEG_TO_RAD,
|
||||
BodyPart.RIGHT_UPPER_ARM to FreeHingeConstraint(
|
||||
-40f * FastMath.DEG_TO_RAD,
|
||||
125f * FastMath.DEG_TO_RAD,
|
||||
Vector3.NEG_Y,
|
||||
),
|
||||
BodyPart.RIGHT_LOWER_ARM to LooseHingeConstraint(
|
||||
-180f * FastMath.DEG_TO_RAD,
|
||||
-160f * FastMath.DEG_TO_RAD,
|
||||
0f * FastMath.DEG_TO_RAD,
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
55f * FastMath.DEG_TO_RAD,
|
||||
Vector3.POS_Z,
|
||||
),
|
||||
BodyPart.RIGHT_HAND to TwistSwingConstraint(
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
70f * FastMath.DEG_TO_RAD,
|
||||
95f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
|
||||
// Spine
|
||||
BodyPart.UPPER_CHEST to TwistSwingConstraint(
|
||||
95f * FastMath.DEG_TO_RAD,
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
105f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.LOWER_CHEST to TwistSwingConstraint(
|
||||
30f * FastMath.DEG_TO_RAD,
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
110f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.UPPER_WAIST to TwistSwingConstraint(
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
110f * FastMath.DEG_TO_RAD,
|
||||
35f * FastMath.DEG_TO_RAD,
|
||||
60f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.LOWER_WAIST to TwistSwingConstraint(
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
110f * FastMath.DEG_TO_RAD,
|
||||
35f * FastMath.DEG_TO_RAD,
|
||||
55f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.HIP to TwistSwingConstraint(
|
||||
65f * FastMath.DEG_TO_RAD,
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
50f * FastMath.DEG_TO_RAD,
|
||||
80f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
|
||||
// Left leg
|
||||
BodyPart.LEFT_UPPER_LEG to TwistSwingConstraint(
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
170f * FastMath.DEG_TO_RAD,
|
||||
BodyPart.LEFT_UPPER_LEG to LooseHingeConstraint(
|
||||
-50f * FastMath.DEG_TO_RAD,
|
||||
165f * FastMath.DEG_TO_RAD,
|
||||
90f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.LEFT_LOWER_LEG to LooseHingeConstraint(
|
||||
-5f * FastMath.DEG_TO_RAD,
|
||||
180f * FastMath.DEG_TO_RAD,
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
-165f * FastMath.DEG_TO_RAD,
|
||||
6f * FastMath.DEG_TO_RAD,
|
||||
65f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.LEFT_FOOT to LooseHingeConstraint(
|
||||
-45f * FastMath.DEG_TO_RAD,
|
||||
20f * FastMath.DEG_TO_RAD,
|
||||
55f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
// TODO enforcing constraint looks bad
|
||||
// BodyPart.LEFT_FOOT to LooseHingeConstraint(
|
||||
// -60f * FastMath.DEG_TO_RAD,
|
||||
// 90f * FastMath.DEG_TO_RAD,
|
||||
// 80f * FastMath.DEG_TO_RAD,
|
||||
// ),
|
||||
|
||||
// Right leg
|
||||
BodyPart.RIGHT_UPPER_LEG to TwistSwingConstraint(
|
||||
120f * FastMath.DEG_TO_RAD,
|
||||
170f * FastMath.DEG_TO_RAD,
|
||||
BodyPart.RIGHT_UPPER_LEG to LooseHingeConstraint(
|
||||
-50f * FastMath.DEG_TO_RAD,
|
||||
165f * FastMath.DEG_TO_RAD,
|
||||
90f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.RIGHT_LOWER_LEG to LooseHingeConstraint(
|
||||
-5f * FastMath.DEG_TO_RAD,
|
||||
180f * FastMath.DEG_TO_RAD,
|
||||
40f * FastMath.DEG_TO_RAD,
|
||||
-165f * FastMath.DEG_TO_RAD,
|
||||
6f * FastMath.DEG_TO_RAD,
|
||||
65f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.RIGHT_FOOT to LooseHingeConstraint(
|
||||
-45f * FastMath.DEG_TO_RAD,
|
||||
20f * FastMath.DEG_TO_RAD,
|
||||
55f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
// BodyPart.RIGHT_FOOT to LooseHingeConstraint(
|
||||
// -60f * FastMath.DEG_TO_RAD,
|
||||
// 90f * FastMath.DEG_TO_RAD,
|
||||
// 80f * FastMath.DEG_TO_RAD,
|
||||
// ),
|
||||
|
||||
// Left fingers
|
||||
BodyPart.LEFT_THUMB_METACARPAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_THUMB_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_THUMB_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_THUMB_METACARPAL to METACARPAL_THUMB_CONSTRAINT,
|
||||
BodyPart.LEFT_THUMB_PROXIMAL to THUMB_CONSTRAINT,
|
||||
BodyPart.LEFT_THUMB_DISTAL to THUMB_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_DISTAL to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_DISTAL to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_DISTAL to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_DISTAL to LEFT_FINGER_CONSTRAINT,
|
||||
|
||||
// Right fingers
|
||||
BodyPart.RIGHT_THUMB_METACARPAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_THUMB_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_THUMB_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_PROXIMAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_INTERMEDIATE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_DISTAL to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_THUMB_METACARPAL to METACARPAL_THUMB_CONSTRAINT,
|
||||
BodyPart.RIGHT_THUMB_PROXIMAL to THUMB_CONSTRAINT,
|
||||
BodyPart.RIGHT_THUMB_DISTAL to THUMB_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_DISTAL to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_DISTAL to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_DISTAL to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_DISTAL to RIGHT_FINGER_CONSTRAINT,
|
||||
|
||||
// Left toes
|
||||
BodyPart.LEFT_BIG_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_TOE to DIGIT_CONSTRAINT,
|
||||
|
||||
// Right toes
|
||||
BodyPart.RIGHT_BIG_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_TOE to DIGIT_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_TOE to DIGIT_CONSTRAINT,
|
||||
// Toes
|
||||
BodyPart.LEFT_BIG_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.LEFT_INDEX_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.LEFT_MIDDLE_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.LEFT_RING_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.LEFT_LITTLE_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.RIGHT_BIG_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.RIGHT_INDEX_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.RIGHT_MIDDLE_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.RIGHT_RING_TOE to TOE_CONSTRAINT,
|
||||
BodyPart.RIGHT_LITTLE_TOE to TOE_CONSTRAINT,
|
||||
),
|
||||
)
|
||||
|
||||
fun constrainOffset(
|
||||
constraint: Constraint,
|
||||
parent: Quaternion,
|
||||
bone: Quaternion,
|
||||
offset: Quaternion,
|
||||
): Quaternion {
|
||||
// TODO: Ensure the quaternion multiplication order is correct here
|
||||
return constraint.apply(parent, offset * bone) / bone
|
||||
}
|
||||
|
||||
fun constrainOffsetWithSkeleton(
|
||||
bodyPart: BodyPart,
|
||||
offset: Quaternion,
|
||||
bones: ComputedSkeleton,
|
||||
constraints: BodyPartMap<Constraint>,
|
||||
): Quaternion {
|
||||
val constraint = constraints[bodyPart] ?: return offset
|
||||
val boneRot = bones[bodyPart]?.rotation ?: return offset
|
||||
val parentRot = parentOf(bodyPart)?.let { parent ->
|
||||
bones[parent]?.rotation
|
||||
} ?: Quaternion.IDENTITY
|
||||
|
||||
return constrainOffset(
|
||||
constraint,
|
||||
parentRot,
|
||||
boneRot,
|
||||
offset,
|
||||
)
|
||||
}
|
||||
|
||||
fun constrainSkeleton(
|
||||
bones: InputSkeleton,
|
||||
constraints: BodyPartMap<Constraint>,
|
||||
onlyActive: Boolean,
|
||||
): InputSkeleton {
|
||||
// Apply constraints top-down
|
||||
for ((parentBodyPart, bodyPart) in iterateBodyPartHierarchy()) {
|
||||
val bone = bones[bodyPart] ?: continue
|
||||
if (onlyActive && !bone.isRotationActive) continue
|
||||
val constraint = constraints[bodyPart] ?: continue
|
||||
val parentRotation = bones[parentBodyPart]?.rotation ?: Quaternion.IDENTITY
|
||||
bones[bodyPart] = bone.copy(
|
||||
@@ -206,3 +208,85 @@ fun constrainSkeleton(
|
||||
}
|
||||
return bones
|
||||
}
|
||||
|
||||
/**
|
||||
* Used for the initial rotation before doing IK to promote movement and preferred axis.
|
||||
*/
|
||||
val BODY_PART_PREFERRED_ROTATION = BodyPartMap(
|
||||
mapOf(
|
||||
BodyPart.LEFT_UPPER_ARM to Quaternion.fromRotationVector(-45f * FastMath.DEG_TO_RAD, 90f * FastMath.DEG_TO_RAD, -100f * FastMath.DEG_TO_RAD),
|
||||
BodyPart.RIGHT_UPPER_ARM to Quaternion.fromRotationVector(-45f * FastMath.DEG_TO_RAD, -90f * FastMath.DEG_TO_RAD, 100f * FastMath.DEG_TO_RAD),
|
||||
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(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),
|
||||
// BodyPart.UPPER_WAIST to Quaternion.rotationAroundXAxis(7.5f * FastMath.DEG_TO_RAD),
|
||||
// BodyPart.LOWER_WAIST to Quaternion.rotationAroundXAxis(7.5f * FastMath.DEG_TO_RAD),
|
||||
),
|
||||
)
|
||||
|
||||
// Constraints to apply to a local offset to best fit a bone's natural movement
|
||||
// Basically the max angle change per IK iteration within local axes
|
||||
// TODO May need to decay constraint over iterations
|
||||
val BODY_PART_OFFSET_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
|
||||
mapOf(
|
||||
BodyPart.LEFT_UPPER_ARM to LooseAxisConstraint(
|
||||
5f * FastMath.DEG_TO_RAD,
|
||||
Vector3.POS_X,
|
||||
),
|
||||
BodyPart.LEFT_LOWER_ARM to LooseAxisConstraint(
|
||||
5f * FastMath.DEG_TO_RAD,
|
||||
Vector3.POS_X,
|
||||
),
|
||||
|
||||
BodyPart.RIGHT_UPPER_ARM to LooseAxisConstraint(
|
||||
5f * FastMath.DEG_TO_RAD,
|
||||
Vector3.POS_X,
|
||||
),
|
||||
BodyPart.RIGHT_LOWER_ARM to LooseAxisConstraint(
|
||||
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.LEFT_UPPER_LEG to LooseAxisConstraint(
|
||||
5f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.LEFT_LOWER_LEG to LooseAxisConstraint(
|
||||
0.2f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
|
||||
BodyPart.RIGHT_UPPER_LEG to LooseAxisConstraint(
|
||||
5f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
BodyPart.RIGHT_LOWER_LEG to LooseAxisConstraint(
|
||||
0.2f * FastMath.DEG_TO_RAD,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -17,12 +17,11 @@ val BODY_PART_IK_CHAIN_MAP: BodyPartMap<IKChain> = BodyPartMap(
|
||||
BodyPart.RIGHT_UPPER_ARM,
|
||||
BodyPart.RIGHT_LOWER_ARM,
|
||||
),
|
||||
BodyPart.HIP to listOf(
|
||||
BodyPart.LOWER_WAIST to listOf(
|
||||
BodyPart.UPPER_CHEST,
|
||||
BodyPart.LOWER_CHEST,
|
||||
BodyPart.UPPER_WAIST,
|
||||
BodyPart.LOWER_WAIST,
|
||||
BodyPart.HIP,
|
||||
),
|
||||
BodyPart.LEFT_LOWER_LEG to listOf(
|
||||
BodyPart.LEFT_UPPER_LEG,
|
||||
@@ -32,15 +31,5 @@ val BODY_PART_IK_CHAIN_MAP: BodyPartMap<IKChain> = BodyPartMap(
|
||||
BodyPart.RIGHT_UPPER_LEG,
|
||||
BodyPart.RIGHT_LOWER_LEG,
|
||||
),
|
||||
BodyPart.LEFT_FOOT to listOf(
|
||||
BodyPart.LEFT_UPPER_LEG,
|
||||
BodyPart.LEFT_LOWER_LEG,
|
||||
BodyPart.LEFT_FOOT,
|
||||
),
|
||||
BodyPart.RIGHT_FOOT to listOf(
|
||||
BodyPart.RIGHT_UPPER_LEG,
|
||||
BodyPart.RIGHT_LOWER_LEG,
|
||||
BodyPart.RIGHT_FOOT,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -99,7 +99,7 @@ inline fun BodyPart.findFirstParent(predicate: (BodyPart) -> Boolean): BodyPart?
|
||||
}
|
||||
|
||||
val headPartSet = setOf(BodyPart.HEAD)
|
||||
fun highestBodyParts(bodyParts: Set<BodyPart>): Set<BodyPart> {
|
||||
fun highestBodyParts(bodyParts: Collection<BodyPart>): Set<BodyPart> {
|
||||
if (BodyPart.HEAD in bodyParts) return headPartSet
|
||||
|
||||
// Construct boolean array once
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,22 +15,26 @@ import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
|
||||
private data class VelocityData(
|
||||
private data class BoneSample(
|
||||
val rotation: Quaternion,
|
||||
val position: Vector3,
|
||||
)
|
||||
|
||||
private fun computeVelocity(currentVelocityData: VelocityData, lastVelocityData: VelocityData, deltaTime: Float): Velocity {
|
||||
val deltaPosition = currentVelocityData.position - lastVelocityData.position
|
||||
val deltaRotation = currentVelocityData.rotation / lastVelocityData.rotation
|
||||
private data class VelocitySample(
|
||||
val boneSample: BoneSample,
|
||||
val velocity: Velocity,
|
||||
)
|
||||
|
||||
private fun computeVelocity(currentBoneSample: BoneSample, lastBoneSample: BoneSample, deltaTime: Float): Velocity {
|
||||
val deltaPosition = currentBoneSample.position - lastBoneSample.position
|
||||
val deltaRotation = currentBoneSample.rotation / lastBoneSample.rotation
|
||||
return Velocity(
|
||||
linear = deltaPosition / deltaTime,
|
||||
angular = currentVelocityData.rotation.sandwich(deltaRotation.toRotationVectorQ()) / deltaTime,
|
||||
angular = currentBoneSample.rotation.sandwich(deltaRotation.toRotationVectorQ()) / deltaTime,
|
||||
)
|
||||
}
|
||||
|
||||
// Optional smoothing of velocity, to make it smoother for the output (SteamVR/Monado prediction).
|
||||
private const val SMOOTHING_MS = 25f
|
||||
private const val SMOOTHING_MS = 20f
|
||||
private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, deltaTime: Float): Velocity {
|
||||
val t = (deltaTime * (millisecondsInSecond / SMOOTHING_MS)).coerceAtMost(1f)
|
||||
return Velocity(
|
||||
@@ -42,12 +46,10 @@ private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, de
|
||||
/**
|
||||
* Computes linear (m/s) and angular (rad/s) velocity for the bones.
|
||||
*/
|
||||
class VelocityComputedProcessor(
|
||||
private val smooth: Boolean = false,
|
||||
) : SkeletonComputedProcessor,
|
||||
class VelocityComputedProcessor :
|
||||
SkeletonComputedProcessor,
|
||||
ResettableSkeletonProcessor {
|
||||
private val lastVelocities: BodyPartMap<Velocity> = bodyPartMap()
|
||||
private val lastVelocityData: BodyPartMap<VelocityData> = bodyPartMap()
|
||||
private val lastVelocities: BodyPartMap<VelocitySample> = bodyPartMap()
|
||||
private var lastProcessTime = timeSource.markNow()
|
||||
|
||||
override fun process(mutableComputedSkeleton: ComputedSkeleton, inputSkeleton: InputSkeleton) {
|
||||
@@ -57,24 +59,24 @@ class VelocityComputedProcessor(
|
||||
lastProcessTime = now
|
||||
|
||||
for ((bodyPart, bone) in mutableComputedSkeleton) {
|
||||
// Compute current velocity
|
||||
val currentVelocityData = VelocityData(bone.rotation, bone.tailPosition)
|
||||
val currentVelocity = lastVelocityData[bodyPart]?.let { computeVelocity(currentVelocityData, it, deltaTime) } ?: ZERO_VELOCITY
|
||||
val lastVelocitySample = lastVelocities[bodyPart]
|
||||
|
||||
val newVelocity = if (smooth) {
|
||||
smoothVelocity(currentVelocity, lastVelocities[bodyPart] ?: ZERO_VELOCITY, deltaTime)
|
||||
// Compute velocity
|
||||
val currentBoneSample = BoneSample(bone.rotation, bone.tailPosition)
|
||||
val smoothedVelocity = if (lastVelocitySample != null) {
|
||||
val currentVelocity = computeVelocity(currentBoneSample, lastVelocitySample.boneSample, deltaTime)
|
||||
smoothVelocity(currentVelocity, lastVelocitySample.velocity, deltaTime)
|
||||
} else {
|
||||
currentVelocity
|
||||
ZERO_VELOCITY
|
||||
}
|
||||
mutableComputedSkeleton[bodyPart] = bone.copy(velocity = newVelocity)
|
||||
|
||||
lastVelocityData[bodyPart] = currentVelocityData
|
||||
lastVelocities[bodyPart] = newVelocity
|
||||
mutableComputedSkeleton[bodyPart] = bone.copy(velocity = smoothedVelocity)
|
||||
lastVelocities[bodyPart] = VelocitySample(currentBoneSample, smoothedVelocity)
|
||||
}
|
||||
}
|
||||
|
||||
override fun reset(resetType: ResetType) {
|
||||
lastVelocities.clear()
|
||||
lastVelocityData.clear()
|
||||
lastProcessTime = timeSource.markNow()
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package dev.slimevr.skeleton
|
||||
|
||||
import com.jme3.math.FastMath
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.min
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
import kotlin.math.withSign
|
||||
@@ -12,9 +14,9 @@ fun applyLocalOperation(
|
||||
parentRotation: Quaternion,
|
||||
childRotation: Quaternion,
|
||||
operation: (localRotation: Quaternion) -> Quaternion,
|
||||
): Quaternion = parentRotation * operation(parentRotation.inv() * childRotation)
|
||||
): Quaternion = operation(childRotation.localAbout(parentRotation)).globalAbout(parentRotation)
|
||||
|
||||
// TODO Actually rewrite, currently still using original server code
|
||||
// TODO Create unit tests to validate behaviour
|
||||
interface Constraint {
|
||||
/**
|
||||
* Applies the constraint to a local rotation.
|
||||
@@ -40,16 +42,31 @@ data class TwistSwingConstraint(
|
||||
/**
|
||||
* Swing range in radians.
|
||||
*/
|
||||
val swing: Float = 0f,
|
||||
val swing: Float,
|
||||
val twistAxis: Vector3 = Vector3.POS_Y,
|
||||
) : Constraint {
|
||||
override fun apply(localRotation: Quaternion): Quaternion {
|
||||
var (swingQ, twistQ) = decomposeToSwingTwist(localRotation, Vector3.NEG_Y)
|
||||
var (swingQ, twistQ) = decomposeToSwingTwist(localRotation, twistAxis)
|
||||
swingQ = constrainAngle(swingQ, swing)
|
||||
twistQ = constrainAngle(twistQ, twist)
|
||||
return swingQ * twistQ
|
||||
}
|
||||
}
|
||||
|
||||
data class TwistConstraint(
|
||||
/**
|
||||
* Twist range in radians.
|
||||
*/
|
||||
val twist: Float = 0f,
|
||||
val twistAxis: Vector3 = Vector3.POS_Y,
|
||||
) : Constraint {
|
||||
override fun apply(localRotation: Quaternion): Quaternion {
|
||||
var (swingQ, twistQ) = decomposeToSwingTwist(localRotation, twistAxis)
|
||||
twistQ = constrainAngle(twistQ, twist)
|
||||
return swingQ * twistQ
|
||||
}
|
||||
}
|
||||
|
||||
data class HingeConstraint(
|
||||
/**
|
||||
* Minimum rotation in radians.
|
||||
@@ -58,9 +75,8 @@ data class HingeConstraint(
|
||||
/**
|
||||
* Maximum rotation in radians.
|
||||
*/
|
||||
val max: Float = 0f,
|
||||
val maxDeviationFromTracker: Float = 15f,
|
||||
val hingeAxis: Vector3 = Vector3.NEG_X,
|
||||
val max: Float,
|
||||
val hingeAxis: Vector3 = Vector3.POS_X,
|
||||
) : Constraint {
|
||||
override fun apply(localRotation: Quaternion): Quaternion {
|
||||
val (_, hingeAxisRot) = decomposeToSwingTwist(localRotation, hingeAxis)
|
||||
@@ -76,10 +92,12 @@ data class LooseHingeConstraint(
|
||||
/**
|
||||
* Maximum rotation in radians.
|
||||
*/
|
||||
val max: Float = 0f,
|
||||
val allowedDeviation: Float = 0f,
|
||||
val maxDeviationFromTracker: Float = 15f,
|
||||
val hingeAxis: Vector3 = Vector3.NEG_X,
|
||||
val max: Float,
|
||||
/**
|
||||
* Maximum non-hinge axis rotation in radians.
|
||||
*/
|
||||
val allowedDeviation: Float,
|
||||
val hingeAxis: Vector3 = Vector3.POS_X,
|
||||
) : Constraint {
|
||||
override fun apply(localRotation: Quaternion): Quaternion {
|
||||
val (nonHingeRot, hingeAxisRot) = decomposeToSwingTwist(localRotation, hingeAxis)
|
||||
@@ -88,13 +106,56 @@ data class LooseHingeConstraint(
|
||||
}
|
||||
}
|
||||
|
||||
data class FreeHingeConstraint(
|
||||
/**
|
||||
* Minimum rotation in radians.
|
||||
*/
|
||||
val min: Float = 0f,
|
||||
/**
|
||||
* Maximum rotation in radians.
|
||||
*/
|
||||
val max: Float,
|
||||
val hingeAxis: Vector3 = Vector3.POS_X,
|
||||
) : Constraint {
|
||||
override fun apply(localRotation: Quaternion): Quaternion {
|
||||
val (nonHingeRot, hingeAxisRot) = decomposeToSwingTwist(localRotation, hingeAxis)
|
||||
return nonHingeRot * constrainOnAxis(hingeAxisRot, min, max, hingeAxis)
|
||||
}
|
||||
}
|
||||
|
||||
data class AxisConstraint(
|
||||
val axis: Vector3 = Vector3.POS_X,
|
||||
) : Constraint {
|
||||
override fun apply(
|
||||
localRotation: Quaternion,
|
||||
): Quaternion = localRotation.project(axis).unit()
|
||||
}
|
||||
|
||||
data class LooseAxisConstraint(
|
||||
/**
|
||||
* Maximum non-axis rotation in radians.
|
||||
*/
|
||||
val allowedDeviation: Float,
|
||||
val axis: Vector3 = Vector3.POS_X,
|
||||
) : Constraint {
|
||||
override fun apply(localRotation: Quaternion): Quaternion {
|
||||
val (nonAxisRot, axisRot) = decomposeToSwingTwist(localRotation, axis)
|
||||
return constrainAngle(nonAxisRot, allowedDeviation) * axisRot
|
||||
}
|
||||
}
|
||||
|
||||
data class SwingTwist(
|
||||
val swing: Quaternion,
|
||||
val twist: Quaternion,
|
||||
)
|
||||
|
||||
fun decomposeToSwingTwist(
|
||||
rotation: Quaternion,
|
||||
twistAxis: Vector3,
|
||||
): Pair<Quaternion, Quaternion> {
|
||||
): SwingTwist {
|
||||
val twist = rotation.project(twistAxis).unit()
|
||||
val swing = rotation / twist
|
||||
return Pair(swing, twist)
|
||||
return SwingTwist(swing, twist)
|
||||
}
|
||||
|
||||
fun constrainAngle(rotation: Quaternion, angle: Float): Quaternion {
|
||||
@@ -116,36 +177,27 @@ fun constrainAngle(rotation: Quaternion, angle: Float): Quaternion {
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps an angle to -pi to pi
|
||||
private fun wrapAngle(angle: Float) = angle - FastMath.TWO_PI * floor((angle + FastMath.PI) / FastMath.TWO_PI)
|
||||
|
||||
fun constrainOnAxis(
|
||||
rotation: Quaternion,
|
||||
minAngle: Float,
|
||||
maxAngle: Float,
|
||||
axis: Vector3,
|
||||
): Quaternion {
|
||||
val magnitudeMin = sin(minAngle * 0.5f)
|
||||
val magnitudeMax = sin(maxAngle * 0.5f)
|
||||
val magnitudeSqrMin = (magnitudeMin * magnitudeMin).withSign(minAngle)
|
||||
val magnitudeSqrMax = (magnitudeMax * magnitudeMax).withSign(maxAngle)
|
||||
val vector = rotation.xyz
|
||||
|
||||
val rotMagnitudeSqr = vector.lenSq().withSign(vector.dot(axis) * rotation.w)
|
||||
return if (rotMagnitudeSqr !in magnitudeSqrMin..magnitudeSqrMax) {
|
||||
val distToMin = min(
|
||||
abs(rotMagnitudeSqr - magnitudeSqrMin),
|
||||
abs(rotMagnitudeSqr + magnitudeSqrMin),
|
||||
)
|
||||
val distToMax = min(
|
||||
abs(rotMagnitudeSqr - magnitudeSqrMax),
|
||||
abs(rotMagnitudeSqr + magnitudeSqrMax),
|
||||
)
|
||||
|
||||
val magnitude = if (distToMin < distToMax) magnitudeMin else magnitudeMax
|
||||
val magnitudeSqr =
|
||||
abs(if (distToMin < distToMax) magnitudeSqrMin else magnitudeSqrMax)
|
||||
val angle = rotation.angleAboutR(axis)
|
||||
return if (angle !in minAngle..maxAngle) {
|
||||
val distToMin = abs(wrapAngle(angle - minAngle))
|
||||
val distToMax = abs(wrapAngle(angle - maxAngle))
|
||||
val magnitude = if (distToMin < distToMax) minAngle else maxAngle
|
||||
|
||||
// Could do Quaternion.fromRotationVector(axis * magnitude) but this is more optimized
|
||||
// and constraints run several times per frame because of IK.
|
||||
val halfMagnitude = magnitude * 0.5f
|
||||
Quaternion(
|
||||
sqrt(1f - magnitudeSqr),
|
||||
vector.unit() * -magnitude,
|
||||
cos(halfMagnitude),
|
||||
axis * sin(halfMagnitude),
|
||||
)
|
||||
} else {
|
||||
rotation
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package dev.slimevr.skeleton
|
||||
|
||||
import com.jme3.math.FastMath
|
||||
import dev.slimevr.util.subListOfLast
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import java.util.EnumMap
|
||||
import kotlin.math.log
|
||||
|
||||
fun requireBone(bones: ComputedSkeleton, bodyPart: BodyPart) = requireNotNull(bones[bodyPart]) {
|
||||
"The computed skeleton is missing \"${bodyPart}\" from the IK chain."
|
||||
@@ -19,37 +20,115 @@ fun chainDistanceFromTarget(
|
||||
return (target - chainTail).len()
|
||||
}
|
||||
|
||||
private val oppositeRotation = Quaternion.rotationAroundZAxis(FastMath.PI)
|
||||
fun chainOffsetsLength(
|
||||
bones: ComputedSkeleton,
|
||||
chain: IKChain,
|
||||
): Double = chain.sumOf { requireBone(bones, it).offset.len().toDouble() }
|
||||
|
||||
fun parentRot(
|
||||
bones: ComputedSkeleton,
|
||||
bodyPart: BodyPart,
|
||||
) = parentOf(bodyPart)?.let { parent ->
|
||||
bones[parent]?.rotation
|
||||
} ?: Quaternion.IDENTITY
|
||||
|
||||
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 chainEndToTarget = chainDistanceFromTarget(mutableComputedSkeleton, goal.chain, goal.target).toDouble()
|
||||
val maxChainLength = chainOffsetsLength(mutableComputedSkeleton, goal.chain)
|
||||
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
|
||||
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)
|
||||
}
|
||||
}
|
||||
if (changedBodyParts.isNotEmpty()) buildBones(mutableComputedSkeleton, mutableBoneInputs, changedBodyParts)
|
||||
}
|
||||
|
||||
// Bones are most likely opposite along the X axis
|
||||
private val oppositeRotation = Quaternion.rotationAroundXAxis(FastMath.PI)
|
||||
fun fromChainToTarget(
|
||||
bodyPart: BodyPart,
|
||||
bones: ComputedSkeleton,
|
||||
chain: IKChain,
|
||||
target: Vector3,
|
||||
): Quaternion? {
|
||||
val boneHead = requireBone(bones, bodyPart).headPosition
|
||||
val bone = requireBone(bones, bodyPart)
|
||||
val chainTail = requireBone(bones, chain.last()).tailPosition
|
||||
|
||||
val localChainTail = (chainTail - boneHead).unit()
|
||||
if (FastMath.isApproxEqual(localChainTail.lenSq(), 0f)) {
|
||||
val localChainTail = chainTail - bone.headPosition
|
||||
val localChainTailLenSq = localChainTail.lenSq()
|
||||
if (FastMath.isApproxZero(localChainTailLenSq)) {
|
||||
// Chain tail is at the origin
|
||||
return null
|
||||
}
|
||||
|
||||
val localTarget = (target - boneHead).unit()
|
||||
if (FastMath.isApproxEqual(localTarget.lenSq(), 0f)) {
|
||||
val localTarget = target - bone.headPosition
|
||||
val localTargetLenSq = localTarget.lenSq()
|
||||
if (FastMath.isApproxZero(localTargetLenSq)) {
|
||||
// Target is at the origin
|
||||
return null
|
||||
}
|
||||
|
||||
val offset = Quaternion.fromTo(localChainTail, localTarget)
|
||||
val offset = Quaternion.fromTo(localChainTail.unit(), localTarget.unit())
|
||||
return if (FastMath.isApproxEqual(offset.lenSq(), 1f)) {
|
||||
offset
|
||||
} else {
|
||||
// When the vectors are exactly opposite, arbitrarily choose an axis
|
||||
oppositeRotation
|
||||
alignOffset(bone.rotation.inv(), oppositeRotation)
|
||||
}
|
||||
}
|
||||
|
||||
// Apply offset in global space to rotation
|
||||
fun applyOffset(
|
||||
rotation: Quaternion,
|
||||
offset: Quaternion,
|
||||
) = offset * rotation
|
||||
|
||||
fun computeOffset(
|
||||
rotation: Quaternion,
|
||||
rotationWithOffset: Quaternion,
|
||||
) = rotationWithOffset / rotation
|
||||
|
||||
fun alignOffset(
|
||||
rotation: Quaternion,
|
||||
offset: Quaternion,
|
||||
) = rotation.inv() * offset * rotation
|
||||
|
||||
fun constrainOffsetWithSkeleton(
|
||||
bodyPart: BodyPart,
|
||||
offset: Quaternion,
|
||||
bones: ComputedSkeleton,
|
||||
constraint: Constraint,
|
||||
): Quaternion {
|
||||
val boneRot = bones[bodyPart]?.rotation ?: return offset
|
||||
|
||||
return computeOffset(
|
||||
boneRot,
|
||||
constraint.apply(
|
||||
parentRot(bones, bodyPart),
|
||||
applyOffset(boneRot, offset),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun rotateChain(
|
||||
boneInputs: InputSkeleton,
|
||||
chain: IKChain,
|
||||
@@ -60,7 +139,7 @@ fun rotateChain(
|
||||
requireNotNull(boneInput) {
|
||||
"The provided bone inputs are missing \"${bodyPart}\" from the IK chain."
|
||||
}.copy(
|
||||
rotation = rotation * boneInput.rotation,
|
||||
rotation = applyOffset(boneInput.rotation, rotation),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -71,28 +150,39 @@ fun ccdIkIteration(
|
||||
mutableComputedSkeleton: ComputedSkeleton,
|
||||
chain: IKChain,
|
||||
target: Vector3,
|
||||
constraints: BodyPartMap<Constraint>?,
|
||||
offsetConstraint: Constraint?,
|
||||
constraint: Constraint?,
|
||||
) {
|
||||
// TODO: Do we need annealing and/or dampening?
|
||||
// The first bone in the chain is the one we are adjusting in this iteration
|
||||
val bodyPart = chain.first()
|
||||
val offset = fromChainToTarget(bodyPart, mutableComputedSkeleton, chain, target) ?: return
|
||||
|
||||
// Constrain the local offset
|
||||
val localConstrainedOffset = offsetConstraint?.let {
|
||||
val rotation = mutableComputedSkeleton[bodyPart]?.rotation ?: return@let null
|
||||
alignOffset(
|
||||
rotation.inv(),
|
||||
it.apply(alignOffset(rotation, offset)),
|
||||
)
|
||||
} ?: offset
|
||||
|
||||
// We only need to constrain the bone that we are adjusting
|
||||
val constrainedOffset = constraints?.let {
|
||||
val constrainedOffset = constraint?.let {
|
||||
constrainOffsetWithSkeleton(
|
||||
bodyPart,
|
||||
offset,
|
||||
localConstrainedOffset,
|
||||
mutableComputedSkeleton,
|
||||
it,
|
||||
)
|
||||
} ?: offset
|
||||
} ?: localConstrainedOffset
|
||||
|
||||
// Mutate the input skeleton
|
||||
rotateChain(mutableBoneInputs, chain, constrainedOffset)
|
||||
|
||||
// Only build bones for inputs that were changed
|
||||
buildBones(mutableComputedSkeleton, mutableBoneInputs, chain.toSet())
|
||||
// If performance is bad, we can combine buildBones calls for non-overlapping IK chains
|
||||
buildBones(mutableComputedSkeleton, mutableBoneInputs, chain)
|
||||
}
|
||||
|
||||
typealias IKChain = List<BodyPart>
|
||||
@@ -101,31 +191,49 @@ data class IKChainGoal(
|
||||
val target: Vector3,
|
||||
)
|
||||
|
||||
/**
|
||||
* @return True if all goals were met, false if any goal was not met.
|
||||
*/
|
||||
fun ccdIk(
|
||||
mutableBoneInputs: InputSkeleton,
|
||||
mutableComputedSkeleton: ComputedSkeleton,
|
||||
goals: List<IKChainGoal>,
|
||||
offsetConstraints: BodyPartMap<Constraint>?,
|
||||
constraints: BodyPartMap<Constraint>?,
|
||||
threshold: Float,
|
||||
maxIterations: Int,
|
||||
) {
|
||||
): Boolean {
|
||||
// No goal leaves every bone as the FK pass built it, so nothing below needs to run
|
||||
if (goals.isEmpty()) return
|
||||
if (goals.isEmpty()) return true
|
||||
|
||||
for (i in 0..maxIterations) {
|
||||
for (goal in goals) {
|
||||
// Set each bone we're gonna do IK on to its preferred rotation
|
||||
adjustToPreferredRotations(mutableBoneInputs, mutableComputedSkeleton, goals, constraints)
|
||||
|
||||
// IK iterations
|
||||
var allGoalsMet = true
|
||||
for (i in 0 until maxIterations) {
|
||||
allGoalsMet = true
|
||||
for ((chain, target) in goals) {
|
||||
// Only iterate chains not meeting the threshold
|
||||
if (chainDistanceFromTarget(mutableComputedSkeleton, goal.chain, goal.target) <= threshold) break
|
||||
if (chainDistanceFromTarget(mutableComputedSkeleton, chain, target) <= threshold) continue
|
||||
allGoalsMet = false
|
||||
|
||||
// The chain from the current bone to the end, iterating backwards
|
||||
val iterationChain = goal.chain.takeLast((i % goal.chain.size) + 1)
|
||||
// TODO We can avoid making any objects or just cache this if it's slow,
|
||||
// check performance to see if needed
|
||||
val iterationChain = chain.subListOfLast((i % chain.size) + 1)
|
||||
val bodyPart = iterationChain.first()
|
||||
ccdIkIteration(
|
||||
mutableBoneInputs,
|
||||
mutableComputedSkeleton,
|
||||
iterationChain,
|
||||
goal.target,
|
||||
constraints,
|
||||
target,
|
||||
offsetConstraints?.get(bodyPart),
|
||||
constraints?.get(bodyPart),
|
||||
)
|
||||
}
|
||||
if (allGoalsMet) break
|
||||
}
|
||||
|
||||
return allGoalsMet
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package dev.slimevr.skeleton.inputprocessors
|
||||
|
||||
import dev.slimevr.skeleton.BodyPartMap
|
||||
import dev.slimevr.skeleton.InputSkeleton
|
||||
import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
|
||||
data class ArmSource(
|
||||
val bodyPart: BodyPart,
|
||||
val needsActive: Boolean = true,
|
||||
// null means it uses all remaining.
|
||||
val ratio: Float? = null,
|
||||
// For body-part-prerequisites.kt
|
||||
val reliable: Boolean = false,
|
||||
)
|
||||
|
||||
val ARM_TO_SOURCE = arrayOf(
|
||||
BodyPart.LEFT_SHOULDER to arrayOf(
|
||||
ArmSource(BodyPart.LEFT_UPPER_ARM, true, 0.04f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false, null, true),
|
||||
),
|
||||
BodyPart.RIGHT_SHOULDER to arrayOf(
|
||||
ArmSource(BodyPart.RIGHT_UPPER_ARM, true, 0.04f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false, null, true),
|
||||
),
|
||||
|
||||
BodyPart.LEFT_UPPER_ARM to arrayOf(
|
||||
ArmSource(BodyPart.LEFT_LOWER_ARM, true),
|
||||
ArmSource(BodyPart.LEFT_HAND, true),
|
||||
ArmSource(BodyPart.LEFT_SHOULDER, true, 0.4f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false),
|
||||
),
|
||||
BodyPart.RIGHT_UPPER_ARM to arrayOf(
|
||||
ArmSource(BodyPart.RIGHT_LOWER_ARM, true),
|
||||
ArmSource(BodyPart.RIGHT_HAND, true),
|
||||
ArmSource(BodyPart.RIGHT_SHOULDER, true, 0.4f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false),
|
||||
),
|
||||
|
||||
BodyPart.LEFT_LOWER_ARM to arrayOf(
|
||||
ArmSource(BodyPart.LEFT_HAND, true),
|
||||
ArmSource(BodyPart.LEFT_UPPER_ARM, true),
|
||||
ArmSource(BodyPart.LEFT_SHOULDER, true, 0.2f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false),
|
||||
),
|
||||
BodyPart.RIGHT_LOWER_ARM to arrayOf(
|
||||
ArmSource(BodyPart.RIGHT_HAND, true),
|
||||
ArmSource(BodyPart.RIGHT_UPPER_ARM, true),
|
||||
ArmSource(BodyPart.RIGHT_SHOULDER, true, 0.2f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false),
|
||||
),
|
||||
|
||||
BodyPart.LEFT_HAND to arrayOf(
|
||||
ArmSource(BodyPart.LEFT_LOWER_ARM),
|
||||
ArmSource(BodyPart.LEFT_UPPER_ARM),
|
||||
ArmSource(BodyPart.LEFT_SHOULDER, true, 0.25f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false),
|
||||
),
|
||||
BodyPart.RIGHT_HAND to arrayOf(
|
||||
ArmSource(BodyPart.RIGHT_LOWER_ARM),
|
||||
ArmSource(BodyPart.RIGHT_UPPER_ARM),
|
||||
ArmSource(BodyPart.RIGHT_SHOULDER, true, 0.25f),
|
||||
ArmSource(BodyPart.UPPER_CHEST, false),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Handles imputing missing arm bones from other arm bones and the upper chest.
|
||||
*
|
||||
* It's useful to set a good starting rotation for arms before IK.
|
||||
*
|
||||
* This processor must run after the spine processor.
|
||||
*/
|
||||
class ArmsInputProcessor : SkeletonInputProcessor {
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
val boneInputs = BodyPartMap(mutableInputSkeleton)
|
||||
for ((bodyPart, sources) in ARM_TO_SOURCE) {
|
||||
val bone = boneInputs[bodyPart] ?: continue
|
||||
if (bone.isRotationActive && bone.isAccelerationActive) continue
|
||||
|
||||
var ratioSum = 0f
|
||||
var rotation: Quaternion? = null
|
||||
var acceleration: Vector3? = null
|
||||
for ((index, source) in sources.withIndex()) {
|
||||
val sourceBone = boneInputs[source.bodyPart] ?: continue
|
||||
if (source.needsActive && !sourceBone.isRotationActive) continue
|
||||
|
||||
val isLastSource = index == sources.count() - 1
|
||||
val remainingRatio = 1f - ratioSum
|
||||
val ratio = (if (!isLastSource) source.ratio?.coerceAtMost(remainingRatio) else null) ?: remainingRatio
|
||||
if (!bone.isRotationActive) {
|
||||
rotation = (rotation ?: Quaternion.ZERO) + (sourceBone.rotation * ratio)
|
||||
}
|
||||
if (!bone.isAccelerationActive) {
|
||||
acceleration = (acceleration ?: Vector3.ZERO) + (sourceBone.acceleration * ratio)
|
||||
}
|
||||
|
||||
ratioSum += ratio
|
||||
if (ratioSum >= 1f) break
|
||||
}
|
||||
|
||||
if ((rotation == null || rotation == bone.rotation) && (acceleration == null || acceleration == bone.acceleration)) continue
|
||||
|
||||
mutableInputSkeleton[bodyPart] = bone.copy(rotation = rotation?.unit() ?: bone.rotation, acceleration = acceleration ?: bone.acceleration)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,6 @@ class ConstraintInputProcessor(
|
||||
val skeletonConfig = settings.context.state.value.data.skeletonConfig
|
||||
if (!skeletonConfig.toggles.enforceConstraints) return
|
||||
|
||||
constrainSkeleton(mutableInputSkeleton, constraints)
|
||||
constrainSkeleton(mutableInputSkeleton, constraints, true)
|
||||
}
|
||||
}
|
||||
@@ -5,27 +5,12 @@ import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
|
||||
/**
|
||||
* Linked BodyPart to the BodyPart it takes its rotation from.
|
||||
*
|
||||
* Order matters: an untracked arm cascades down from the upper chest in one pass.
|
||||
* Linked BodyPart to the BodyPart it takes its rotation from. Order matters.
|
||||
*/
|
||||
val BONE_DIRECT_LINK_SOURCES = arrayOf(
|
||||
BodyPart.HEAD to BodyPart.NECK,
|
||||
|
||||
BodyPart.LEFT_FOOT to BodyPart.LEFT_LOWER_LEG,
|
||||
BodyPart.RIGHT_FOOT to BodyPart.RIGHT_LOWER_LEG,
|
||||
|
||||
BodyPart.LEFT_SHOULDER to BodyPart.UPPER_CHEST,
|
||||
BodyPart.RIGHT_SHOULDER to BodyPart.UPPER_CHEST,
|
||||
|
||||
BodyPart.LEFT_UPPER_ARM to BodyPart.LEFT_SHOULDER,
|
||||
BodyPart.RIGHT_UPPER_ARM to BodyPart.RIGHT_SHOULDER,
|
||||
|
||||
BodyPart.LEFT_LOWER_ARM to BodyPart.LEFT_UPPER_ARM,
|
||||
BodyPart.RIGHT_LOWER_ARM to BodyPart.RIGHT_UPPER_ARM,
|
||||
|
||||
BodyPart.LEFT_HAND to BodyPart.LEFT_LOWER_ARM,
|
||||
BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -37,8 +22,9 @@ class DirectLinkInputProcessor : SkeletonInputProcessor {
|
||||
val bone = mutableInputSkeleton[bodyPart] ?: continue
|
||||
if (bone.isRotationActive && bone.isAccelerationActive) continue
|
||||
|
||||
val rotation = if (!bone.isRotationActive) mutableInputSkeleton[source]?.rotation ?: bone.rotation else bone.rotation
|
||||
val acceleration = if (!bone.isAccelerationActive) mutableInputSkeleton[source]?.acceleration ?: bone.acceleration else bone.acceleration
|
||||
val source = mutableInputSkeleton[source]
|
||||
val rotation = if (!bone.isRotationActive) source?.rotation ?: bone.rotation else bone.rotation
|
||||
val acceleration = if (!bone.isAccelerationActive) source?.acceleration ?: bone.acceleration else bone.acceleration
|
||||
|
||||
if (rotation == bone.rotation && acceleration == bone.acceleration) continue
|
||||
|
||||
|
||||
@@ -2,9 +2,14 @@ package dev.slimevr.skeleton.inputprocessors
|
||||
|
||||
import dev.slimevr.skeleton.InputSkeleton
|
||||
import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import dev.slimevr.skeleton.bodyPartMap
|
||||
import dev.slimevr.skeleton.findFirstParent
|
||||
import dev.slimevr.util.timeSource
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.collections.set
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
private val FALLBACK_REFRESH = 1.seconds
|
||||
|
||||
// Only allow child fallbacks in certain cases
|
||||
val CHILD_FALLBACKS = mapOf(
|
||||
@@ -59,23 +64,38 @@ val CHILD_FALLBACKS = mapOf(
|
||||
* This does not produce reliable data. For that, see the direct link processor.
|
||||
*/
|
||||
class FallbackInputProcessor : SkeletonInputProcessor {
|
||||
// First is rotation, second is acceleration
|
||||
val cachedFallbacks = bodyPartMap<Pair<BodyPart?, BodyPart?>>()
|
||||
var timeSinceRefresh = timeSource.markNow()
|
||||
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
// Only lookup fallbacks every so often for optimization's sake
|
||||
if (timeSinceRefresh.elapsedNow() > FALLBACK_REFRESH) {
|
||||
for ((bodyPart, bone) in mutableInputSkeleton) {
|
||||
if (bone.isRotationActive && bone.isAccelerationActive) continue
|
||||
val rotationFallback = if (!bone.isRotationActive) {
|
||||
bodyPart.findFirstParent { mutableInputSkeleton[it]?.isRotationActive == true }
|
||||
?: CHILD_FALLBACKS[bodyPart]?.firstOrNull { mutableInputSkeleton[it]?.isRotationActive == true }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val accelFallback = if (!bone.isAccelerationActive) {
|
||||
bodyPart.findFirstParent { mutableInputSkeleton[it]?.isAccelerationActive == true }
|
||||
?: CHILD_FALLBACKS[bodyPart]?.firstOrNull { mutableInputSkeleton[it]?.isAccelerationActive == true }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
cachedFallbacks[bodyPart] = rotationFallback to accelFallback
|
||||
}
|
||||
timeSinceRefresh = timeSource.markNow()
|
||||
}
|
||||
|
||||
for ((bodyPart, bone) in mutableInputSkeleton) {
|
||||
if (bone.isRotationActive && bone.isAccelerationActive) continue
|
||||
val newRotation = if (!bone.isRotationActive) {
|
||||
val fallbackPart = bodyPart.findFirstParent { mutableInputSkeleton[it]?.isRotationActive == true }
|
||||
?: CHILD_FALLBACKS[bodyPart]?.firstOrNull { mutableInputSkeleton[it]?.isRotationActive == true }
|
||||
mutableInputSkeleton[fallbackPart]?.rotation?.eulerHeading() ?: bone.rotation
|
||||
} else {
|
||||
bone.rotation
|
||||
}
|
||||
val newAcceleration = if (!bone.isAccelerationActive) {
|
||||
val fallbackPart = bodyPart.findFirstParent { mutableInputSkeleton[it]?.isAccelerationActive == true }
|
||||
?: CHILD_FALLBACKS[bodyPart]?.firstOrNull { mutableInputSkeleton[it]?.isAccelerationActive == true }
|
||||
mutableInputSkeleton[fallbackPart]?.acceleration ?: bone.acceleration
|
||||
} else {
|
||||
bone.acceleration
|
||||
}
|
||||
val cachedFallback = cachedFallbacks[bodyPart]
|
||||
val newRotation = mutableInputSkeleton[cachedFallback?.first]?.rotation?.eulerHeading() ?: bone.rotation
|
||||
val newAcceleration = mutableInputSkeleton[cachedFallback?.second]?.acceleration ?: bone.acceleration
|
||||
|
||||
mutableInputSkeleton[bodyPart] = bone.copy(rotation = newRotation, acceleration = newAcceleration)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package dev.slimevr.skeleton.inputprocessors
|
||||
|
||||
import com.jme3.math.FastMath
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.skeleton.BodyPartMap
|
||||
import dev.slimevr.skeleton.BoneInput
|
||||
import dev.slimevr.skeleton.InputSkeleton
|
||||
import dev.slimevr.skeleton.ResettableSkeletonProcessor
|
||||
import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import dev.slimevr.skeleton.bodyPartMap
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import kotlin.math.log
|
||||
import kotlin.time.ComparableTimeMark
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
// Upsampling
|
||||
private val UPSAMPLING_EXTRAPOLATION_MAX_DURATION = 0.8.seconds
|
||||
|
||||
// Upsampling (technically Prediction but always active)
|
||||
private const val UPSAMPLING_EXTRAPOLATION_LOG_BASE_MIN = 7f
|
||||
private const val UPSAMPLING_EXTRAPOLATION_LOG_BASE_MAX = 3f
|
||||
|
||||
// Upsampling (technically Smoothing but always active)
|
||||
private const val UPSAMPLING_TIME_CARRYOVER_MIN = 0.6f
|
||||
private const val UPSAMPLING_TIME_CARRYOVER_MAX = 0.92f
|
||||
private val UPSAMPLING_TIME_CARRYOVER_LIMIT = 900.milliseconds
|
||||
|
||||
// Smoothing
|
||||
private const val SMOOTHING_MS_MAX = 50.0
|
||||
|
||||
// Prediction
|
||||
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(
|
||||
mapOf(
|
||||
BodyPart.LEFT_SHOULDER to 1.4,
|
||||
BodyPart.RIGHT_SHOULDER to 1.4,
|
||||
BodyPart.LEFT_UPPER_ARM to 1.4,
|
||||
BodyPart.RIGHT_UPPER_ARM to 1.4,
|
||||
BodyPart.LEFT_LOWER_ARM to 1.4,
|
||||
BodyPart.RIGHT_LOWER_ARM to 1.4,
|
||||
),
|
||||
)
|
||||
|
||||
private data class BoneSample(
|
||||
val rotation: Quaternion,
|
||||
val acceleration: Vector3,
|
||||
val position: Vector3?,
|
||||
) {
|
||||
companion object {
|
||||
fun fromBone(bone: BoneInput) = BoneSample(bone.rotation, bone.acceleration, bone.position)
|
||||
}
|
||||
}
|
||||
|
||||
private data class BoneSamples(
|
||||
// These get assigned everytime we get a new pose for a bone
|
||||
val fromSample: BoneSample?,
|
||||
val targetSample: BoneSample,
|
||||
val poseTime: ComparableTimeMark,
|
||||
val sampleTime: ComparableTimeMark,
|
||||
val timeBetweenPoses: Duration,
|
||||
val predictedRotation: Quaternion,
|
||||
// Mutable since these get changed every skeleton frame even if no new pose is received
|
||||
var runningSample: BoneSample?,
|
||||
var timeLeftForLastPose: Duration, // can be negative
|
||||
)
|
||||
|
||||
private fun computePoseTimeDelta(
|
||||
previousPoseTime: ComparableTimeMark?,
|
||||
currentPoseTime: ComparableTimeMark,
|
||||
) = previousPoseTime?.let {
|
||||
currentPoseTime - previousPoseTime
|
||||
} ?: Duration.ZERO
|
||||
|
||||
private fun computeTimeBetweenPoses(
|
||||
poseTimeDelta: Duration,
|
||||
timeLeftForLastPose: Duration?,
|
||||
timeCarryover: Double,
|
||||
): Duration {
|
||||
// Use some of last pose's remaining time
|
||||
val lastPoseCarryoverTime = timeLeftForLastPose?.let { it.coerceAtMost(UPSAMPLING_TIME_CARRYOVER_LIMIT) * timeCarryover } ?: Duration.ZERO
|
||||
return (lastPoseCarryoverTime + poseTimeDelta).coerceAtLeast(Duration.ZERO)
|
||||
}
|
||||
|
||||
private fun computePredictedRotation(
|
||||
previousRotation: Quaternion?,
|
||||
previousPredictedRotation: Quaternion?,
|
||||
targetRotation: Quaternion,
|
||||
predictionTime: Duration,
|
||||
poseTimeDelta: Duration,
|
||||
): Quaternion {
|
||||
if (previousRotation == null) return targetRotation
|
||||
|
||||
// Use some of the previous prediction
|
||||
val previousPredictionDelta = previousPredictedRotation?.localAbout(previousRotation)?.pow(PREVIOUS_PREDICTION_CARRYOVER)
|
||||
?: Quaternion.IDENTITY
|
||||
|
||||
val currentDelta = if (poseTimeDelta > Duration.ZERO) {
|
||||
val t = (predictionTime / poseTimeDelta).toFloat()
|
||||
targetRotation.localAbout(previousRotation).pow(t)
|
||||
} else {
|
||||
Quaternion.IDENTITY
|
||||
}
|
||||
|
||||
return targetRotation * previousPredictionDelta * currentDelta
|
||||
}
|
||||
|
||||
private fun computeInterpolationRatio(
|
||||
timeSinceLastPose: Duration,
|
||||
timeBetweenPoses: Duration,
|
||||
extrapolationLogBase: Double,
|
||||
): Float {
|
||||
// Time between now and tracker data.
|
||||
val timeSinceLastPoseClamped = timeSinceLastPose.coerceAtMost(timeBetweenPoses + UPSAMPLING_EXTRAPOLATION_MAX_DURATION)
|
||||
// Ratio of how close we should be to the next pose.
|
||||
// 0 = we just got started, 1 = we should have the next one, >1 = we didn't get it yet; packet lost or late
|
||||
val rawRatio = if (timeBetweenPoses > Duration.ZERO) timeSinceLastPoseClamped / timeBetweenPoses else 1.0
|
||||
// In case the rawRatio is >1, we extrapolate using log to keep some smooth perceived movement.
|
||||
val extrapolationAmount = log((rawRatio).coerceAtLeast(1.0), extrapolationLogBase)
|
||||
// Resulting ratio to use for interpolation, including extrapolation if any.
|
||||
return (rawRatio.coerceAtMost(1.0) + extrapolationAmount).toFloat()
|
||||
}
|
||||
|
||||
/**
|
||||
* This processor handles upsampling, smoothing and prediction, all in one processor for optimization's sake.
|
||||
*
|
||||
* ----- Upsampling -----
|
||||
* Since the skeleton runs at a different rate than trackers (e.g: 500hz vs 100hz),
|
||||
* this processor handles interpolating data received from trackers across skeleton frames up
|
||||
* until the next tracker data (e.g: interpolating the 100hz data across 5 frames to reach 500hz).
|
||||
*
|
||||
* Its goal is to make the data more reliable and easier to work with by avoiding spikes over frames as the skeleton
|
||||
* receives new data from trackers. We trade off a little bit of latency (1 tracker tick, or ~10 ms) for this.
|
||||
*
|
||||
* It will also extrapolate a little if we haven't received new tracker data in the time we were supposed to,
|
||||
* to mitigate packet loss and late packets.
|
||||
*
|
||||
* With this, processors don't have to care that trackers only send at 100hz and can know that the data from one skeleton
|
||||
* frame to another will have reliably changed according to the IRL movements.
|
||||
*
|
||||
* ----- Smoothing -----
|
||||
* Smoothing decides how fast to get to the target rotation by just scaling down the interpolation ratio.
|
||||
*
|
||||
* ----- Prediction -----
|
||||
* Prediction decides how far away the target rotation is using an average of past rotation deltas.
|
||||
*/
|
||||
class FilteringInputProcessor(val settings: Settings) :
|
||||
SkeletonInputProcessor,
|
||||
ResettableSkeletonProcessor {
|
||||
private val boneSamples: BodyPartMap<BoneSamples> = bodyPartMap()
|
||||
private var lastProcessEndTime = timeSource.markNow()
|
||||
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
val now = timeSource.markNow()
|
||||
|
||||
val skeletonRatios = settings.context.state.value.data.skeletonConfig.ratios
|
||||
val timeCarryover = FastMath.remapClamped(skeletonRatios.smoothingStrength, 0f, 1f, UPSAMPLING_TIME_CARRYOVER_MIN, UPSAMPLING_TIME_CARRYOVER_MAX).toDouble()
|
||||
val extrapolationLogBase = FastMath.remapClamped(skeletonRatios.predictionStrength, 0f, 1f, UPSAMPLING_EXTRAPOLATION_LOG_BASE_MIN, UPSAMPLING_EXTRAPOLATION_LOG_BASE_MAX).toDouble()
|
||||
val smoothingTime = (skeletonRatios.smoothingStrength * SMOOTHING_MS_MAX).milliseconds
|
||||
val predictionTime = (skeletonRatios.predictionStrength * PREDICTION_MS_MAX).milliseconds
|
||||
|
||||
for ((bodyPart, bone) in mutableInputSkeleton) {
|
||||
val partPredictionTime = predictionTime * (PART_MULTIPLIER[bodyPart] ?: 1.0)
|
||||
|
||||
if (bone.poseTime == null) {
|
||||
boneSamples.remove(bodyPart)
|
||||
continue
|
||||
}
|
||||
|
||||
val previousSamples = boneSamples[bodyPart]
|
||||
|
||||
// New pose data updates the samples
|
||||
val samples = if (bone.poseTime != previousSamples?.poseTime) {
|
||||
// Use the runningSample as starting point if any to resume where we were at last frame
|
||||
val fromSample = previousSamples?.runningSample ?: previousSamples?.targetSample
|
||||
// Need to store this data in time because we mutate the skeleton bones
|
||||
val targetSample = BoneSample.fromBone(bone)
|
||||
|
||||
// How much time has passed between the last 2 bone poses
|
||||
val poseTimeDelta = computePoseTimeDelta(previousSamples?.poseTime, bone.poseTime)
|
||||
|
||||
// The time we'll take to interpolate to the new pose
|
||||
val timeBetweenPoses = computeTimeBetweenPoses(poseTimeDelta, previousSamples?.timeLeftForLastPose, timeCarryover)
|
||||
|
||||
// The predicted target rotation
|
||||
val predictedRotation = if (partPredictionTime > Duration.ZERO) {
|
||||
// Prediction enabled
|
||||
computePredictedRotation(
|
||||
previousSamples?.targetSample?.rotation,
|
||||
previousSamples?.predictedRotation,
|
||||
targetSample.rotation,
|
||||
partPredictionTime,
|
||||
poseTimeDelta,
|
||||
)
|
||||
} else {
|
||||
targetSample.rotation
|
||||
}
|
||||
|
||||
// New samples
|
||||
BoneSamples(fromSample, targetSample, bone.poseTime, lastProcessEndTime, timeBetweenPoses, predictedRotation, null, Duration.ZERO)
|
||||
} else {
|
||||
previousSamples
|
||||
}
|
||||
|
||||
// Filtering
|
||||
if (samples.fromSample != null) {
|
||||
val timeSinceLastPose = now - samples.sampleTime
|
||||
val upsamplingRatio = computeInterpolationRatio(timeSinceLastPose, samples.timeBetweenPoses, extrapolationLogBase)
|
||||
|
||||
// Rotation
|
||||
val rotation = if (bone.isRotationActive) {
|
||||
val smoothingRatio = if (smoothingTime > Duration.ZERO) {
|
||||
// Smoothing enabled
|
||||
computeInterpolationRatio(timeSinceLastPose, samples.timeBetweenPoses + smoothingTime, extrapolationLogBase)
|
||||
} else {
|
||||
upsamplingRatio
|
||||
}
|
||||
// Use the predicted rotation as target
|
||||
samples.fromSample.rotation.interpQ(samples.predictedRotation, smoothingRatio)
|
||||
} else {
|
||||
samples.targetSample.rotation
|
||||
}
|
||||
|
||||
// Acceleration
|
||||
val acceleration = if (bone.isAccelerationActive) {
|
||||
samples.fromSample.acceleration.lerp(samples.targetSample.acceleration, upsamplingRatio)
|
||||
} else {
|
||||
samples.targetSample.acceleration
|
||||
}
|
||||
|
||||
// Position
|
||||
val position = if (bone.isPositionActive && samples.fromSample.position != null && samples.targetSample.position != null) {
|
||||
samples.fromSample.position.lerp(samples.targetSample.position, upsamplingRatio)
|
||||
} else {
|
||||
samples.targetSample.position
|
||||
}
|
||||
|
||||
// Update bone data in skeleton
|
||||
val newBone = bone.copy(rotation = rotation, acceleration = acceleration, position = position)
|
||||
mutableInputSkeleton[bodyPart] = newBone
|
||||
|
||||
// Update running sample so that we resume from where we left off if we get a new pose next frame
|
||||
samples.runningSample = BoneSample.fromBone(newBone)
|
||||
// Time left for this pose, using the ratio to account for non-linear extrapolation
|
||||
samples.timeLeftForLastPose = samples.timeBetweenPoses - (samples.timeBetweenPoses * upsamplingRatio.toDouble())
|
||||
}
|
||||
|
||||
// Save updated samples
|
||||
boneSamples[bodyPart] = samples
|
||||
}
|
||||
|
||||
lastProcessEndTime = now
|
||||
}
|
||||
|
||||
override fun reset(resetType: ResetType) {
|
||||
boneSamples.clear()
|
||||
}
|
||||
}
|
||||
@@ -6,35 +6,52 @@ import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
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
|
||||
|
||||
private const val INTERMEDIATE_FROM_PROXIMAL = 2.12f
|
||||
private const val DISTAL_FROM_PROXIMAL = 3.03f
|
||||
private const val INTERMEDIATE_FROM_PROXIMAL_CURL = 2.12f
|
||||
private const val DISTAL_FROM_PROXIMAL_CURL = 3.03f
|
||||
|
||||
private val PROXIMAL_REST_ROTATION = Quaternion.rotationAroundZAxis(0.15f)
|
||||
private val PROXIMAL_THUMB_REST_ROTATION = Quaternion.rotationAroundXAxis(-0.15f)
|
||||
private val THUMB_PARTS = arrayOf(
|
||||
BodyPart.LEFT_THUMB_METACARPAL,
|
||||
BodyPart.LEFT_THUMB_PROXIMAL,
|
||||
BodyPart.LEFT_THUMB_DISTAL,
|
||||
BodyPart.RIGHT_THUMB_METACARPAL,
|
||||
BodyPart.RIGHT_THUMB_PROXIMAL,
|
||||
BodyPart.RIGHT_THUMB_DISTAL,
|
||||
)
|
||||
private const val INTERMEDIATE_FROM_PROXIMAL = 1.04f
|
||||
private const val DISTAL_FROM_PROXIMAL = 1.10f
|
||||
|
||||
private fun getRestRotation(hand: BoneInput, finger: BoneInput, multiplier: Float): Quaternion {
|
||||
val isThumb = finger.bodyPart in THUMB_PARTS
|
||||
val restRotation = if (isThumb) {
|
||||
PROXIMAL_THUMB_REST_ROTATION
|
||||
private const val REST_ANGLE = 0.15f
|
||||
|
||||
private fun getRestRotation(handRotation: Quaternion, axis: Vector3, multiplier: Float): Quaternion {
|
||||
val restRotation = Quaternion.fromRotationVector(axis * REST_ANGLE)
|
||||
return handRotation * restRotation.pow(multiplier)
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpolate the forward, back and side rotation with different ratios: one ratio for forward and one ratio for back and side.
|
||||
*/
|
||||
private fun interpolateForwardBackSide(hand: Quaternion, finger: Quaternion, forwardRatio: Float, backSideRatio: Float, axis: Vector3): Quaternion {
|
||||
// Work with the local rotation to avoid axes being ambiguous
|
||||
val local = finger.localAbout(hand)
|
||||
|
||||
// If forward is going back, actually use the backSideRatio.
|
||||
val actualForwardRatio = if (local.angleAboutR(axis) < 0f) {
|
||||
backSideRatio
|
||||
} else {
|
||||
val side = hand.bodyPart.side
|
||||
if (side == Side.RIGHT) {
|
||||
PROXIMAL_REST_ROTATION.inv()
|
||||
} else {
|
||||
PROXIMAL_REST_ROTATION
|
||||
}
|
||||
forwardRatio
|
||||
}
|
||||
return hand.rotation * restRotation.pow(multiplier)
|
||||
|
||||
// Early return for optimization
|
||||
if (actualForwardRatio == backSideRatio) return hand.interpQ(finger, backSideRatio)
|
||||
|
||||
// Decompose the local rotation into its twist (forward) and its swing (side) along the axis
|
||||
val forward = local.project(axis).unit()
|
||||
val side = local / forward
|
||||
|
||||
// Scale each axis of the local rotation with our ratios
|
||||
val scaledForward = forward.pow(actualForwardRatio)
|
||||
val scaledSide = side.pow(backSideRatio)
|
||||
|
||||
// Recompose the local rotation. We removed forward from local rotation to get side, so we must add forward to side back.
|
||||
val scaledLocal = scaledSide * scaledForward
|
||||
|
||||
// Return scaled local rotation applied to From rotation
|
||||
return scaledLocal.globalAbout(hand)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,59 +63,102 @@ class FingersInputProcessor : SkeletonInputProcessor {
|
||||
val proximal: BodyPart,
|
||||
val intermediate: BodyPart,
|
||||
val distal: BodyPart,
|
||||
val axis: Vector3,
|
||||
val isThumb: Boolean = false,
|
||||
)
|
||||
|
||||
private val fingers = arrayOf(
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_INDEX_PROXIMAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_DISTAL),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_MIDDLE_PROXIMAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_DISTAL),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_RING_PROXIMAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_DISTAL),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_LITTLE_PROXIMAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_DISTAL),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL, Vector3.NEG_X, true),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_INDEX_PROXIMAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_DISTAL, Vector3.POS_Z),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_MIDDLE_PROXIMAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_DISTAL, Vector3.POS_Z),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_RING_PROXIMAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_DISTAL, Vector3.POS_Z),
|
||||
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_LITTLE_PROXIMAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_DISTAL, Vector3.POS_Z),
|
||||
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL, Vector3.NEG_X, true),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL, Vector3.NEG_Z),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL, Vector3.NEG_Z),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL, Vector3.NEG_Z),
|
||||
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL, Vector3.NEG_Z),
|
||||
)
|
||||
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
for (finger in fingers) {
|
||||
val hand = mutableInputSkeleton[finger.hand] ?: continue
|
||||
val handRotation = mutableInputSkeleton[finger.hand]?.rotation ?: continue
|
||||
val proximal = mutableInputSkeleton[finger.proximal] ?: continue
|
||||
val intermediate = mutableInputSkeleton[finger.intermediate] ?: continue
|
||||
val distal = mutableInputSkeleton[finger.distal] ?: continue
|
||||
|
||||
// Proximal
|
||||
if (!proximal.isRotationActive) {
|
||||
// Missing proximal bone. Impute it from intermediate > distal > hand
|
||||
val newRotation = if (intermediate.isRotationActive) {
|
||||
hand.rotation.interpQ(intermediate.rotation, 1f / INTERMEDIATE_FROM_PROXIMAL)
|
||||
interpolateForwardBackSide(
|
||||
handRotation,
|
||||
intermediate.rotation,
|
||||
1f / INTERMEDIATE_FROM_PROXIMAL_CURL,
|
||||
1f / INTERMEDIATE_FROM_PROXIMAL,
|
||||
finger.axis,
|
||||
)
|
||||
} else if (distal.isRotationActive) {
|
||||
hand.rotation.interpQ(distal.rotation, 1f / DISTAL_FROM_PROXIMAL)
|
||||
interpolateForwardBackSide(
|
||||
handRotation,
|
||||
distal.rotation,
|
||||
1f / DISTAL_FROM_PROXIMAL_CURL,
|
||||
1f / DISTAL_FROM_PROXIMAL,
|
||||
finger.axis,
|
||||
)
|
||||
} else {
|
||||
getRestRotation(hand, proximal, 1f)
|
||||
getRestRotation(handRotation, finger.axis, 1f)
|
||||
}
|
||||
mutableInputSkeleton[finger.proximal] = proximal.copy(rotation = newRotation)
|
||||
}
|
||||
|
||||
// Intermediate
|
||||
if (!intermediate.isRotationActive) {
|
||||
// Missing intermediate bone. Impute it from distal > proximal > hand
|
||||
val newRotation = if (distal.isRotationActive) {
|
||||
hand.rotation.interpQ(distal.rotation, INTERMEDIATE_FROM_PROXIMAL / DISTAL_FROM_PROXIMAL)
|
||||
interpolateForwardBackSide(
|
||||
handRotation,
|
||||
distal.rotation,
|
||||
INTERMEDIATE_FROM_PROXIMAL_CURL / DISTAL_FROM_PROXIMAL_CURL,
|
||||
INTERMEDIATE_FROM_PROXIMAL / DISTAL_FROM_PROXIMAL,
|
||||
finger.axis,
|
||||
)
|
||||
} else if (proximal.isRotationActive) {
|
||||
hand.rotation.interpQ(proximal.rotation, INTERMEDIATE_FROM_PROXIMAL)
|
||||
interpolateForwardBackSide(
|
||||
handRotation,
|
||||
proximal.rotation,
|
||||
INTERMEDIATE_FROM_PROXIMAL_CURL,
|
||||
INTERMEDIATE_FROM_PROXIMAL,
|
||||
finger.axis,
|
||||
)
|
||||
} else {
|
||||
getRestRotation(hand, proximal, INTERMEDIATE_FROM_PROXIMAL)
|
||||
getRestRotation(handRotation, finger.axis, INTERMEDIATE_FROM_PROXIMAL_CURL)
|
||||
}
|
||||
mutableInputSkeleton[finger.intermediate] = intermediate.copy(rotation = newRotation)
|
||||
}
|
||||
|
||||
// Distal
|
||||
if (!distal.isRotationActive) {
|
||||
// Missing distal bone. Impute it from intermediate > proximal > hand
|
||||
val newRotation = if (intermediate.isRotationActive) {
|
||||
hand.rotation.interpQ(intermediate.rotation, DISTAL_FROM_PROXIMAL / INTERMEDIATE_FROM_PROXIMAL)
|
||||
interpolateForwardBackSide(
|
||||
handRotation,
|
||||
intermediate.rotation,
|
||||
DISTAL_FROM_PROXIMAL_CURL / INTERMEDIATE_FROM_PROXIMAL_CURL,
|
||||
DISTAL_FROM_PROXIMAL / INTERMEDIATE_FROM_PROXIMAL,
|
||||
finger.axis,
|
||||
)
|
||||
} else if (proximal.isRotationActive) {
|
||||
hand.rotation.interpQ(proximal.rotation, DISTAL_FROM_PROXIMAL)
|
||||
interpolateForwardBackSide(
|
||||
handRotation,
|
||||
proximal.rotation,
|
||||
DISTAL_FROM_PROXIMAL_CURL,
|
||||
DISTAL_FROM_PROXIMAL,
|
||||
finger.axis,
|
||||
)
|
||||
} else {
|
||||
getRestRotation(hand, proximal, DISTAL_FROM_PROXIMAL)
|
||||
getRestRotation(handRotation, finger.axis, DISTAL_FROM_PROXIMAL_CURL)
|
||||
}
|
||||
mutableInputSkeleton[finger.distal] = distal.copy(rotation = newRotation)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package dev.slimevr.skeleton.inputprocessors
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.skeleton.BodyPartMap
|
||||
import dev.slimevr.skeleton.InputSkeleton
|
||||
import dev.slimevr.skeleton.ResettableSkeletonProcessor
|
||||
import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import dev.slimevr.skeleton.bodyPartMap
|
||||
import dev.slimevr.util.MonotonicValueTimeMark
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.FilteringType
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
/** How long the running average of rotation deltas used for predictions is */
|
||||
val RUNNING_AVERAGE_WINDOW = 10.milliseconds
|
||||
|
||||
/** How far ahead the prediction reaches at amount 1, scaled down by the configured amount */
|
||||
val PREDICTION_LEAD = 12.milliseconds
|
||||
|
||||
/**
|
||||
* Tries to predict future rotations of bones.
|
||||
*/
|
||||
class RotationPredictionInputProcessor(val settings: Settings) :
|
||||
SkeletonInputProcessor,
|
||||
ResettableSkeletonProcessor {
|
||||
private data class BoneDelta(
|
||||
val lastRotation: Quaternion,
|
||||
val rotationDelta: Quaternion,
|
||||
val lastChange: MonotonicValueTimeMark,
|
||||
)
|
||||
|
||||
// Used to minimize latency even more for arm tracking where it is more noticeable in VR.
|
||||
private val PART_MULTIPLIER = BodyPartMap(
|
||||
mapOf(
|
||||
BodyPart.LEFT_SHOULDER to 1.4f,
|
||||
BodyPart.RIGHT_SHOULDER to 1.4f,
|
||||
BodyPart.LEFT_UPPER_ARM to 1.4f,
|
||||
BodyPart.RIGHT_UPPER_ARM to 1.4f,
|
||||
BodyPart.LEFT_LOWER_ARM to 1.4f,
|
||||
BodyPart.RIGHT_LOWER_ARM to 1.4f,
|
||||
)
|
||||
)
|
||||
|
||||
private val deltas: BodyPartMap<BoneDelta> = bodyPartMap()
|
||||
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
val config = settings.context.state.value.data.skeletonConfig.filtering
|
||||
val filteringAmount = config.amount
|
||||
if (config.type != FilteringType.PREDICTION || filteringAmount <= 0f) {
|
||||
// Drop stale velocities so re-enabling doesn't diff against a long outdated pose
|
||||
if (deltas.isNotEmpty()) deltas.clear()
|
||||
return
|
||||
}
|
||||
val now = timeSource.markNow()
|
||||
|
||||
for ((bodyPart, bone) in mutableInputSkeleton) {
|
||||
if (!bone.isRotationActive) continue
|
||||
|
||||
val prev = deltas[bodyPart]
|
||||
if (prev == null) {
|
||||
deltas[bodyPart] = BoneDelta(bone.rotation, Quaternion.IDENTITY, now)
|
||||
continue
|
||||
}
|
||||
|
||||
val leadScale = (PREDICTION_LEAD / (now - prev.lastChange)).toFloat()
|
||||
val rotationDelta = (bone.rotation / prev.lastRotation).pow(leadScale)
|
||||
deltas[bodyPart] = BoneDelta(bone.rotation, rotationDelta, now)
|
||||
|
||||
val bonePredictionAmount = filteringAmount * (PART_MULTIPLIER[bodyPart] ?: 1f)
|
||||
val scaledDelta = rotationDelta.pow(bonePredictionAmount)
|
||||
val predicted = scaledDelta * bone.rotation
|
||||
if (predicted != bone.rotation) mutableInputSkeleton[bodyPart] = bone.copy(rotation = predicted)
|
||||
}
|
||||
}
|
||||
|
||||
override fun reset(resetType: ResetType) {
|
||||
deltas.clear()
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package dev.slimevr.skeleton.inputprocessors
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.skeleton.BodyPartMap
|
||||
import dev.slimevr.skeleton.InputSkeleton
|
||||
import dev.slimevr.skeleton.ResettableSkeletonProcessor
|
||||
import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import dev.slimevr.skeleton.bodyPartMap
|
||||
import dev.slimevr.util.inFloatingSeconds
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import solarxr_protocol.rpc.FilteringType
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
|
||||
private const val SMOOTHING_MULTIPLIER = 100f
|
||||
private const val SMOOTH_MIN = 0.46f
|
||||
private const val SMOOTH_MAX = 0.92f
|
||||
|
||||
/**
|
||||
* Running average of bone rotations to smooth them out.
|
||||
*/
|
||||
class RotationSmoothingInputProcessor(val settings: Settings) :
|
||||
SkeletonInputProcessor,
|
||||
ResettableSkeletonProcessor {
|
||||
private val smoothed: BodyPartMap<Quaternion> = bodyPartMap()
|
||||
private var lastProcessTime = timeSource.markNow()
|
||||
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
val config = settings.context.state.value.data.skeletonConfig.filtering
|
||||
val filteringAmount = config.amount
|
||||
if (config.type != FilteringType.SMOOTHING || filteringAmount <= 0f) {
|
||||
// Drop stale poses so re-enabling doesn't blend out of an outdated frame
|
||||
if (smoothed.isNotEmpty()) smoothed.clear()
|
||||
lastProcessTime = timeSource.markNow()
|
||||
return
|
||||
}
|
||||
|
||||
// Normalize with frame time
|
||||
val lastFrameTimeSeconds = lastProcessTime.elapsedNow().inFloatingSeconds
|
||||
lastProcessTime = timeSource.markNow()
|
||||
|
||||
val smoothingAmount = SMOOTH_MIN + filteringAmount * (SMOOTH_MAX - SMOOTH_MIN)
|
||||
val alpha = ((1 - smoothingAmount) * lastFrameTimeSeconds * SMOOTHING_MULTIPLIER).coerceIn(0f, 1f)
|
||||
|
||||
for ((bodyPart, bone) in mutableInputSkeleton) {
|
||||
if (!bone.isRotationActive) continue
|
||||
|
||||
val prev = smoothed[bodyPart] ?: bone.rotation
|
||||
val rotation = prev.lerpQ(bone.rotation, alpha).unit()
|
||||
smoothed[bodyPart] = rotation
|
||||
if (rotation != bone.rotation) mutableInputSkeleton[bodyPart] = bone.copy(rotation = rotation)
|
||||
}
|
||||
}
|
||||
|
||||
override fun reset(resetType: ResetType) {
|
||||
lastProcessTime = timeSource.markNow()
|
||||
smoothed.clear()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.enums.enumEntries
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.pow
|
||||
|
||||
// At this default value, the user's spine should behave as we meant it to.
|
||||
const val DEFAULT_SPINE_UPPER_LOWER = 0.5f
|
||||
@@ -42,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.3f),
|
||||
SpineSource.HIP to Reliability(4f, 6.25f, 0.4f),
|
||||
SpineSource.UPPER_LEGS to Reliability(4f, 5f),
|
||||
),
|
||||
SpineSource.LOWER_CHEST to arrayOf(
|
||||
@@ -52,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.3f),
|
||||
SpineSource.HIP to Reliability(4f, 7.25f, 0.4f),
|
||||
SpineSource.UPPER_LEGS to Reliability(4f, 6f),
|
||||
),
|
||||
SpineSource.UPPER_WAIST to arrayOf(
|
||||
@@ -64,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.85f),
|
||||
SpineSource.HIP to Reliability(4.5f, 13.5f, 0.88f),
|
||||
SpineSource.UPPER_LEGS to Reliability(0.25f, 12f),
|
||||
),
|
||||
SpineSource.LOWER_WAIST to arrayOf(
|
||||
@@ -74,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.85f),
|
||||
SpineSource.HIP to Reliability(5.25f, 13f, 0.88f),
|
||||
SpineSource.UPPER_LEGS to Reliability(1.75f, 11f),
|
||||
),
|
||||
SpineSource.HIP to arrayOf(
|
||||
@@ -83,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.9f), // Itself
|
||||
SpineSource.HIP to Reliability(38f, 60f), // Itself
|
||||
// To
|
||||
SpineSource.UPPER_LEGS to Reliability(7f, 17f),
|
||||
),
|
||||
@@ -133,37 +134,49 @@ private fun buildFromTo(sourceActive: Map<SpineSource, Boolean>) = SPINE_SOURCE_
|
||||
spineSource to (from to to)
|
||||
}
|
||||
|
||||
// Higher value makes it so attitude is less prioritized
|
||||
const val ATTITUDE_MIN = 0.3f
|
||||
/**
|
||||
* Prioritize the rotation with the lowest attitude to prevent one thigh driving the whole spine by itself.
|
||||
* TODO to improve this even more for cases like crossing legs while sitting down, we need to use the rotation delta
|
||||
* from the From. E.g: when using Upper Chest + Upper Legs, need to use delta from each Upper Leg to Upper Chest.
|
||||
* This would allow us to apply different weights to forward (x-axis) rotation and side (z-axis rotation).
|
||||
*/
|
||||
private fun attitudeWeightedAverageRotation(inputSkeleton: InputSkeleton, bodyParts: Array<BodyPart> = arrayOf()): Quaternion? {
|
||||
val rotationsToAverage = inputSkeleton.values.filter { it.bodyPart in bodyParts }.map { it.rotation }
|
||||
if (rotationsToAverage.count() <= 1) return rotationsToAverage.firstOrNull()
|
||||
// TODO should SpineSource's parameter be a Pair with a nullable second argument?
|
||||
if (rotationsToAverage.count() > 2) error("attitudeWeightedAverageRotation only works with 2 rotations max")
|
||||
// Too high or too low will make roll priority too snappy or not strong enough
|
||||
const val ROLL_MULTIPLIER = 16f
|
||||
const val REST_MULTIPLIER = 10f
|
||||
|
||||
val attitudeLengthSum = rotationsToAverage.sumOf { ATTITUDE_MIN + (it.eulerHeading().inv() * it).angleQ().toDouble() }.toFloat()
|
||||
// Higher value makes it so local rotation is less prioritized
|
||||
const val ANGLE_MIN = 3f
|
||||
|
||||
// How much to not prioritize a tracker with roll rotation
|
||||
const val ROLL_POW = 1.8f
|
||||
|
||||
/**
|
||||
* Prioritize the rotation with the smallest local rotation to prevent one thigh driving the whole spine by itself.
|
||||
*/
|
||||
private fun localWeightedAverageRotation(inputSkeleton: InputSkeleton, bodyParts: Array<BodyPart>, parentRotation: Quaternion): Quaternion? {
|
||||
val rotationsToAverage = inputSkeleton.values.filter { it.bodyPart in bodyParts }.map { it.rotation }
|
||||
val numRotations = rotationsToAverage.count()
|
||||
if (numRotations <= 1) return rotationsToAverage.firstOrNull()
|
||||
|
||||
// Precompute local angles "lengths" of rotations, weighted so that roll counts more
|
||||
val localLengths = rotationsToAverage.map {
|
||||
val local = it.localAbout(parentRotation)
|
||||
val roll = local.project(Vector3.POS_Z).unit()
|
||||
val rest = local / roll
|
||||
ANGLE_MIN + (roll.angleQ() * ROLL_MULTIPLIER).pow(ROLL_POW) + (rest.angleQ() * REST_MULTIPLIER)
|
||||
}
|
||||
val localLengthsSum = localLengths.sum()
|
||||
val nbDivider = (numRotations - 1f)
|
||||
return rotationsToAverage
|
||||
.fold(Quaternion.ZERO) { acc, rotation ->
|
||||
// This only works for 2 rotations, but we don't have any case with >2 anyways
|
||||
val ratio = abs(1 - ((ATTITUDE_MIN + (rotation.eulerHeading().inv() * rotation).angleQ()) / attitudeLengthSum))
|
||||
.foldIndexed(Quaternion.ZERO) { i, acc, rotation ->
|
||||
// Use the inverse ratio of the angle, accounting for the number of rotations
|
||||
val ratio = abs(1f - (localLengths[i] / localLengthsSum)) / nbDivider
|
||||
acc + (rotation * ratio)
|
||||
}.unit()
|
||||
}
|
||||
|
||||
private fun weightedAverageRotation(sources: List<SpineSource>, reliabilities: Map<SpineSource, Reliability>, boneInputs: InputSkeleton): Quaternion {
|
||||
private fun weightedAverageRotation(sources: List<SpineSource>, reliabilities: Map<SpineSource, Reliability>, boneInputs: InputSkeleton, fromRotation: Quaternion?): Quaternion {
|
||||
var accProportion = 0f
|
||||
return sources.foldIndexed(Quaternion.ZERO) { i, acc, fromSource ->
|
||||
val rotation = attitudeWeightedAverageRotation(boneInputs, fromSource.parts)
|
||||
val rotation = localWeightedAverageRotation(boneInputs, fromSource.parts, fromRotation ?: Quaternion.IDENTITY)
|
||||
if (rotation != null) {
|
||||
val proportion = if (i + 1 == sources.count()) {
|
||||
// Use all the remaining
|
||||
1 - accProportion
|
||||
1f - accProportion
|
||||
} else {
|
||||
reliabilities[fromSource]?.proportion ?: error("No proportion found for $fromSource")
|
||||
}
|
||||
@@ -185,7 +198,7 @@ private fun weightedAverageReliability(sources: List<SpineSource>, reliabilities
|
||||
|
||||
val proportion = if (i + 1 == sources.count()) {
|
||||
// Use all the remaining
|
||||
1 - accProportion
|
||||
1f - accProportion
|
||||
} else {
|
||||
reliabilities[source]?.proportion ?: error("No proportion found for $source")
|
||||
}
|
||||
@@ -226,22 +239,22 @@ private fun interpolateRatio(fromUpperToLower: Float, curvature: Float, fromReli
|
||||
private fun interpolateForwardSide(fromRotation: Quaternion, toRotation: Quaternion, forwardRatio: Float, sideRatio: Float?): Quaternion {
|
||||
if (sideRatio == null) return fromRotation.interpQ(toRotation, forwardRatio)
|
||||
|
||||
// Work with the rotation delta to avoid axes being ambiguous
|
||||
val delta = fromRotation.inv() * toRotation
|
||||
// Work with the local rotation to avoid axes being ambiguous
|
||||
val local = toRotation.localAbout(fromRotation)
|
||||
|
||||
// Decompose the delta into its twist (forward) and swing (remaining/sides) along the x-axis
|
||||
val forward = delta.project(Vector3.POS_X).unit()
|
||||
val side = delta / forward
|
||||
// Decompose the local rotation into its twist (forward) and swing (remaining/sides) along the x-axis
|
||||
val forward = local.project(Vector3.POS_X).unit()
|
||||
val side = local / forward
|
||||
|
||||
// Scale each axis of the delta with our ratios
|
||||
// Scale each axis of the local rotation with our ratios
|
||||
val scaledForward = forward.pow(forwardRatio)
|
||||
val scaledSide = side.pow(sideRatio)
|
||||
|
||||
// Recompose the delta. We removed formward from delta to get side, so we must add forward to side back.
|
||||
val scaledDelta = scaledSide * scaledForward
|
||||
// Recompose the local rotation. We removed forward from local rotation to get side, so we must add forward to side back.
|
||||
val scaledLocal = scaledSide * scaledForward
|
||||
|
||||
// Return scaled delta applied to From rotation
|
||||
return fromRotation * scaledDelta
|
||||
// Return scaled local rotation applied to From rotation
|
||||
return scaledLocal.globalAbout(fromRotation)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -270,17 +283,18 @@ class SpineInputProcessor(val settings: Settings) : SkeletonInputProcessor {
|
||||
if (to.isEmpty()) continue // Nothing to interpolate with
|
||||
|
||||
// Determine the sources used for getting rotation
|
||||
val fromRotationSources = from.ifEmpty { to }
|
||||
val fromRotationSources = from.ifEmpty { listOf(to.first()) }
|
||||
val fromReliabilitySources = from.ifEmpty { listOf(spineSource) }
|
||||
val toSources = if (from.isNotEmpty()) to else to.flatMap { fromTo[it]?.second ?: continue@loop }
|
||||
val toSources = if (from.isNotEmpty()) to else fromTo[to.first()]?.second ?: continue@loop
|
||||
if (toSources.isEmpty()) continue
|
||||
|
||||
// Get From and To's weighted average reliabilities
|
||||
val (fromForwardReliability, fromSideReliability) = weightedAverageReliability(fromReliabilitySources, reliabilities)
|
||||
val (toForwardReliability, toSideReliability) = weightedAverageReliability(toSources, reliabilities)
|
||||
|
||||
// Get From and To's weighted average rotations
|
||||
val fromRotation = weightedAverageRotation(fromRotationSources, reliabilities, boneInputs)
|
||||
val toRotation = weightedAverageRotation(toSources, reliabilities, boneInputs)
|
||||
val fromRotation = weightedAverageRotation(fromRotationSources, reliabilities, boneInputs, null)
|
||||
val toRotation = weightedAverageRotation(toSources, reliabilities, boneInputs, fromRotation)
|
||||
|
||||
// We are interpolating as-if we were the To if From is empty
|
||||
val sourceActive = bone.isRotationActive || from.isEmpty()
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
-51
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package dev.slimevr.skeleton.inputprocessors
|
||||
|
||||
import dev.slimevr.skeleton.BodyPartMap
|
||||
import dev.slimevr.skeleton.InputSkeleton
|
||||
import dev.slimevr.skeleton.ResettableSkeletonProcessor
|
||||
import dev.slimevr.skeleton.SkeletonInputProcessor
|
||||
import dev.slimevr.skeleton.bodyPartMap
|
||||
import dev.slimevr.util.inFloatingSeconds
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
|
||||
private data class BoneInterpolation(
|
||||
val rotation: Quaternion,
|
||||
val acceleration: Vector3,
|
||||
val position: Vector3?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Since the skeleton runs at a different rate than trackers (e.g: 500hz vs 100hz),
|
||||
* this processor handles interpolating data received from trackers across skeleton frames up
|
||||
* until the next tracker data (e.g: interpolating the 100hz data across 5 frames to reach 500hz).
|
||||
*
|
||||
* This has the side effect of smoothing data a bit but that is **not** its primary goal as it will run whether
|
||||
* smoothing filtering is enabled or not.
|
||||
* Its main goal is to make the data more reliable and easier to work with by avoiding spikes over frames as the skeleton
|
||||
* receives new data from trackers. We trade off a little bit of latency (~4 ms) for this.
|
||||
*
|
||||
* With this, processors don't have to care that trackers only send at 100hz and can know that the data from one skeleton
|
||||
* frame to another is reliable.
|
||||
* For example, since rotation is interpolated here, the velocity processor doesn't have to do its own interpolation.
|
||||
*/
|
||||
class UpsamplingInputProcessor :
|
||||
SkeletonInputProcessor,
|
||||
ResettableSkeletonProcessor {
|
||||
private var interpolationData: BodyPartMap<BoneInterpolation> = bodyPartMap()
|
||||
private var lastProcessTime = timeSource.markNow()
|
||||
|
||||
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
|
||||
val deltaTime = lastProcessTime.elapsedNow().inFloatingSeconds
|
||||
lastProcessTime = timeSource.markNow()
|
||||
|
||||
for ((bodyPart, bone) in mutableInputSkeleton) {
|
||||
if (bone.tps == null) continue
|
||||
|
||||
// For a 100hz tracker on 500hz skeleton, this will be 0.2f (interpolating 1/5 every frame)
|
||||
val interpolationRatio = (deltaTime * bone.tps.toFloat()).coerceAtMost(1f)
|
||||
val newBone = interpolationData[bodyPart]?.let { interpolation ->
|
||||
// Interpolate rotation, acceleration and position.
|
||||
val rotation = if (bone.isRotationActive) {
|
||||
interpolation.rotation.interpQ(bone.rotation, interpolationRatio)
|
||||
} else {
|
||||
bone.rotation
|
||||
}
|
||||
val acceleration = if (bone.isAccelerationActive) {
|
||||
interpolation.acceleration.lerp(bone.acceleration, interpolationRatio)
|
||||
} else {
|
||||
bone.acceleration
|
||||
}
|
||||
val position = if (bone.isPositionActive && bone.position != null && interpolation.position != null) {
|
||||
interpolation.position.lerp(bone.position, interpolationRatio)
|
||||
} else {
|
||||
bone.position
|
||||
}
|
||||
|
||||
// Return modified bone with interpolated data
|
||||
bone.copy(
|
||||
rotation = rotation,
|
||||
acceleration = acceleration,
|
||||
position = position,
|
||||
)
|
||||
} ?: bone
|
||||
|
||||
// Set new interpolated bone data
|
||||
if (bone != newBone) mutableInputSkeleton[bodyPart] = newBone
|
||||
|
||||
// Set running interpolation data
|
||||
interpolationData[bodyPart] = BoneInterpolation(
|
||||
newBone.rotation,
|
||||
newBone.acceleration,
|
||||
newBone.position,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun reset(resetType: ResetType) {
|
||||
interpolationData.clear()
|
||||
lastProcessTime = timeSource.markNow()
|
||||
}
|
||||
}
|
||||
@@ -4,23 +4,21 @@ 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.ConstraintInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.DirectLinkInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.FallbackInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.FilteringInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.FingersInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.HeadPositionFallbackInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.NeckInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.RotationPredictionInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.RotationSmoothingInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.SpineInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.ToesInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.BoneOffsetInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor
|
||||
import dev.slimevr.skeleton.inputprocessors.UpsamplingInputProcessor
|
||||
import dev.slimevr.skeleton.targetprocessors.FloorClipTargetProcessor
|
||||
import dev.slimevr.skeleton.targetprocessors.PositionalTargetProcessor
|
||||
import dev.slimevr.skeleton.targetprocessors.SkatingCorrectionTargetProcessor
|
||||
@@ -33,6 +31,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import solarxr_protocol.rpc.SkeletonBone
|
||||
import kotlin.time.ComparableTimeMark
|
||||
|
||||
data class Velocity(
|
||||
/** In meters/s */
|
||||
@@ -48,8 +47,7 @@ data class BoneInput(
|
||||
val bodyPart: BodyPart,
|
||||
val headOffset: Vector3,
|
||||
val offset: Vector3,
|
||||
val boneOffset: Vector3,
|
||||
val tps: UShort?,
|
||||
val poseTime: ComparableTimeMark?,
|
||||
val rotation: Quaternion,
|
||||
val acceleration: Vector3,
|
||||
val position: 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,
|
||||
@@ -83,7 +80,7 @@ data class BoneState(
|
||||
get() = rotation * orientationOffset
|
||||
|
||||
val localRotation: Quaternion
|
||||
get() = parentBone?.let { it.rotation.inv() * rotation } ?: rotation
|
||||
get() = parentBone?.let { rotation.localAbout(it.rotation) } ?: rotation
|
||||
val localHeadPosition: Vector3
|
||||
get() = parentBone?.let { headPosition - it.tailPosition } ?: headPosition
|
||||
val localTailPosition: Vector3
|
||||
@@ -114,8 +111,7 @@ val DEFAULT_BONE_INPUT = BoneInput(
|
||||
bodyPart = BodyPart.NONE,
|
||||
headOffset = Vector3.ZERO,
|
||||
offset = Vector3.ZERO,
|
||||
boneOffset = Vector3.ZERO,
|
||||
tps = null,
|
||||
poseTime = null,
|
||||
rotation = Quaternion.IDENTITY,
|
||||
acceleration = Vector3.ZERO,
|
||||
position = null,
|
||||
@@ -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,
|
||||
@@ -168,7 +163,7 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO
|
||||
/**
|
||||
* Runs FK from boneInputs, mutating the passed bones.
|
||||
*/
|
||||
fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton, changedParts: Set<BodyPart> = headPartSet) {
|
||||
fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton, changedParts: Collection<BodyPart> = headPartSet) {
|
||||
for (bodyPart in highestBodyParts(changedParts)) {
|
||||
for ((parentPart, childPart) in iterateBodyPartHierarchy(bodyPart, false)) {
|
||||
val rawBone = boneInputs[childPart] ?: continue
|
||||
@@ -181,8 +176,6 @@ fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton,
|
||||
sealed interface SkeletonActions {
|
||||
data class SetBonePose(
|
||||
val bodyPart: BodyPart,
|
||||
val boneOffset: Vector3?,
|
||||
val tps: UShort?,
|
||||
val rotation: Quaternion?,
|
||||
val acceleration: Vector3?,
|
||||
val position: Vector3?,
|
||||
@@ -193,6 +186,7 @@ sealed interface SkeletonActions {
|
||||
data class PauseTracking(val pause: Boolean) : SkeletonActions
|
||||
data class SetPausedBoneInputs(val pausedBoneInputs: InputSkeleton) : SkeletonActions
|
||||
data object ResetHeadPosition : SkeletonActions
|
||||
data object RecenterHeadPosition : SkeletonActions
|
||||
data object ResetFloorLevel : SkeletonActions
|
||||
data class RequestProcessorReset(val resetType: ResetType) : SkeletonActions
|
||||
data class ProcessorResetsApplied(val count: Int) : SkeletonActions
|
||||
@@ -268,29 +262,26 @@ class Skeleton(
|
||||
ProportionsBehaviour(ctx.config.userConfig),
|
||||
HeightLogBehaviour(),
|
||||
LocalizerResetBehaviour(settings),
|
||||
// YouSpinMeRightRoundBehaviour(inputHz = 50),
|
||||
// YouSpinMeRightRoundBehaviour(inputHz = 100, speed = 1f, randomPacketLoss = 0f, constantPacketLoss = 0f, sendPosition = true),
|
||||
ComputedSkeletonBehaviour(
|
||||
hz = hz,
|
||||
waiter = waiter,
|
||||
// Run before FK on the inputs
|
||||
inputProcessors = listOf(
|
||||
UpsamplingInputProcessor(),
|
||||
RotationPredictionInputProcessor(settings),
|
||||
RotationSmoothingInputProcessor(settings),
|
||||
BoneOffsetInputProcessor(),
|
||||
FilteringInputProcessor(settings),
|
||||
HeadPositionFallbackInputProcessor(),
|
||||
FallbackInputProcessor(),
|
||||
UpperLegsRollAlignInputProcessor(settings),
|
||||
SpineInputProcessor(settings),
|
||||
NeckInputProcessor(),
|
||||
DirectLinkInputProcessor(),
|
||||
ArmsInputProcessor(),
|
||||
FingersInputProcessor(),
|
||||
ToesInputProcessor(),
|
||||
ConstraintInputProcessor(settings),
|
||||
),
|
||||
// Run on the result of FK and persist
|
||||
fkComputedProcessors = listOf(
|
||||
VelocityComputedProcessor(false),
|
||||
VelocityComputedProcessor(),
|
||||
),
|
||||
// Run on the inputs with the result of FK and run FK
|
||||
fkProcessors = listOf(
|
||||
@@ -306,7 +297,8 @@ class Skeleton(
|
||||
),
|
||||
// Run on the result of IK and persist.
|
||||
ikComputedProcessors = listOf(
|
||||
VelocityComputedProcessor(true),
|
||||
UpperLegsTwistComputedProcessor(settings),
|
||||
VelocityComputedProcessor(),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user