Compare commits

...
Author SHA1 Message Date
loucass003 05dc3cf31e Better compile time calculation 2026-09-15 18:07:44 +02:00
loucass003 68d678bcf4 Clean up tests. remove redundant ones, regroup stuff 2026-09-15 16:54:09 +02:00
loucass003 cc0f7dd3e8 More cleanup. Handle more edge cases 2026-09-15 16:33:34 +02:00
loucass003 d49877668d More cleanup. move ressouces in the right folder. Simplified override 2026-09-15 15:46:50 +02:00
loucass003 3ee7f00e8d Mimic mc override system / move files around 2026-09-15 14:55:05 +02:00
loucass003 e957ebc977 Migration logic 2026-09-15 14:05:45 +02:00
loucass003 065d2bf71b Re organise and split parser in a way we can add stuff without too much overlap 2026-09-15 13:54:35 +02:00
loucass003 c54ea7f1b9 Splitted and more organised ressource pack parser / compiler 2026-09-15 06:34:01 +02:00
loucass003 309cff3406 Check for duplicates in vchat output addresses 2026-09-15 03:36:47 +02:00
loucass003 3b4df34049 Verify pipline operation order and give errors 2026-09-15 03:36:47 +02:00
loucass003 8e2fb1609b More checks on VMC outputs when compiling the packs 2026-09-15 03:36:47 +02:00
loucass003 49ac85b129 Make sure order of fallacks is correct 2026-09-15 03:36:47 +02:00
loucass003 d962d52631 Better overrides 2026-09-15 03:36:47 +02:00
loucass003 0bb2772cf0 removes in overides 2026-09-15 03:35:59 +02:00
loucass003 b6acf4a98e overrides 2026-09-15 03:35:59 +02:00
loucass003 9526be4841 VRCOSC output from pack 2026-09-15 03:35:59 +02:00
loucass003 55e631b7f0 Battery Source to pack 2026-09-15 03:28:03 +02:00
loucass003 9c29e8880f VRM mappings from pack 2026-09-15 03:23:12 +02:00
loucass003 dcabe69bc8 Bone Routing from pack 2026-09-15 03:21:07 +02:00
loucass003 efeada35fa Constrains and RotationFallback processors 2026-09-15 03:19:30 +02:00
loucass003 4b4aa89f37 Proportions from resource packs 2026-09-15 03:18:11 +02:00
loucass003 5b5a20ff4c Ressource pack base parser 2026-09-15 03:13:08 +02:00
loucass003 4ab1e6c127 Formated jsons + outputs 2026-09-15 03:13:08 +02:00
loucass003 8a149e861f Ressource pack structure example 2026-09-15 03:13:08 +02:00
Butterscotch! b92b91778a Add source for body part masses 2026-09-14 21:04:40 -04:00
Erimel 82e48cbad4 WIP fixing centaur and run spotless 2026-09-14 20:31:42 -04:00
loucass003 be2c16d827 Fix conneciton looping 2026-09-15 01:08:21 +02:00
loucass003 65cdc83e3c Remove BodyPart fully from solarxr, implement new connection sequence 2026-09-15 00:12:06 +02:00
Erimel ee38e9f6ba No more TestFactory
So much more optimized and no more inflating numbers
2026-09-14 17:33:58 -04:00
Erimel 2681ae7621 toRotationVectorR and Q 2026-09-14 16:48:50 -04:00
Erimel 747931404f Make spine processor easier to port over for Futura 2026-09-14 15:01:55 -04:00
Erimel 67140a7703 Rename RelaxedSpine to just Spine 2026-09-14 14:40:00 -04:00
Sapphire 8ef05d49cc Parse sensor temperature for legacy HID protocol 2026-09-14 01:57:44 -05:00
Erimel 9995a81caf Not just osc trackers 2026-09-13 14:37:56 -04:00
loucass003 07626b9623 move freeze up 2026-09-13 14:14:43 +02:00
loucass003 a371af75fa Move registry into a module, preparing for extensions 2026-09-13 14:14:12 +02:00
loucass003 69acb068c7 Solarxr Connection Handshake and bone registry + untested but compile change for binding provider 2026-09-13 12:50:39 +02:00
Erimel 15775a1247 Fix centaur 2026-09-12 15:47:00 -04:00
Erimel 6dfad04ebb Add comment about prediction multiplier 2026-09-12 14:10:01 -04:00
Butterscotch! 6ebae1bedf Don't perform toe snap with a 0 length foot 2026-09-12 02:57:57 -04:00
Erimel bc11c874e2 Remove OutboundProbe to fix CI 2026-09-11 20:18:35 -04:00
Erimel 889c54720c Absolute twist for spine 2026-09-11 19:48:07 -04:00
Erimel 8c7ec3a453 revert polarityReference causing centaur 2026-09-11 19:02:36 -04:00
Erimel ebe5c6b010 Rewrite relaxed spine processor 2026-09-11 18:52:38 -04:00
loucass003 2de0569326 Remove serial detection modal 2026-09-11 20:40:49 +02:00
loucass003 2a28c0766a Fix x scroll on home 2026-09-11 20:24:09 +02:00
loucass003 ec59f373ae Make height text on preview send to height calibration page 2026-09-11 20:14:58 +02:00
loucass003 64d1aa6209 Properly remember flightlist closed state across pages 2026-09-11 20:11:40 +02:00
loucass003 183f986eee Tracker table sorting + column selection. Remove moreInfo and sortByName dev toggles 2026-09-11 20:04:13 +02:00
loucass003 83e99e2708 Home screen, no trackers view 2026-09-11 19:16:18 +02:00
loucass003 1608c3ea91 Better keybinds 2026-09-11 19:03:04 +02:00
loucass003 a9f252f59f Sligtly better spacing in assignment 2026-09-11 16:23:38 +02:00
loucass003 e8196425da more metrics on dispatcher 2026-09-11 15:57:15 +02:00
Sapphire bd2c4da2f2 Fix devices potentially showing in wrong group 2026-09-10 20:56:58 -05:00
Erimel bc1f5a2652 Fix CI 2026-09-10 20:41:18 -04:00
Erimel 6b1ccd3f6f Improve relaxed spine even more!!! ^v^ 2026-09-10 20:38:01 -04:00
Erimel 2acf7804d8 Don't mark occluded tracker bone as inactive 2026-09-10 19:42:16 -04:00
Erimel 1d2b6295c9 Fix toes not following ankle 2026-09-10 19:09:51 -04:00
Erimel 28efcda839 Potential fix for smoothing causing centaur 2026-09-10 19:03:28 -04:00
Erimel 28eb411ecb Rename processors 2026-09-10 19:01:20 -04:00
Erimel 1b40f12791 Split waist, default upper chest, and use lower chest to relax spine 2026-09-10 18:17:32 -04:00
loucass003 59fc10da6e Better preview camera 2026-09-10 22:56:35 +02:00
loucass003 fb6fda82e1 More keyboard / controller motion controls 2026-09-10 22:28:24 +02:00
342 changed files with 11419 additions and 4106 deletions

No files matched your search

+85 -8
View File
@@ -29,6 +29,77 @@ using namespace solarxr_protocol;
static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); }
// Must match SOLARXR_PROTOCOL_VERSION in server/core/.../solarxr/protocol.kt
constexpr uint32_t SOLARXR_PROTOCOL_VERSION = 2;
// Exchanges ClientHello/ServerHello, then waits for the server's BoneRegistry and
// FinishConfiguration before acknowledging. All later sends must use
// FinishMessageBundleBuffer so the server does not gate them as pre-init messages.
static bool performSolarXRHandshake(SolarXRConnection &conn) {
using namespace solarxr_protocol::connection;
{
flatbuffers::FlatBufferBuilder fbb;
auto hello = CreateClientHello(fbb, SOLARXR_PROTOCOL_VERSION);
fbb.Finish(hello, "SXCH");
conn.sendMsg(fbb);
}
auto helloReply = conn.recvMsg();
if (!helloReply || helloReply->size() < 8
|| !flatbuffers::BufferHasIdentifier(helloReply->data(), "SXSH")) {
Logger::get().error("Did not receive a valid SolarXR ServerHello");
return false;
}
auto serverHello = flatbuffers::GetRoot<ServerHello>(helloReply->data());
if (serverHello->status() != HelloStatus::ACCEPTED) {
Logger::get().error("SolarXR server rejected our protocol version (status {})",
static_cast<int>(serverHello->status()));
return false;
}
// Connection messages arrive in their own bundles; process each fully
// (the server sends BoneRegistry before FinishConfiguration).
bool finished = false;
while (!finished) {
auto frame = conn.recvMsg();
if (!frame || frame->size() < 8
|| !flatbuffers::BufferHasIdentifier(frame->data(), "SXMB")) {
Logger::get().error("Did not receive a valid SolarXR MessageBundle during initialization");
return false;
}
auto bundle = flatbuffers::GetRoot<MessageBundle>(frame->data());
auto msgs = bundle->connection_msgs();
if (!msgs) continue;
for (auto header : *msgs) {
switch (header->message_type()) {
case ConnectionMessage::FinishConfiguration:
finished = true;
break;
case ConnectionMessage::ConnectionError: {
auto error = header->message_as_ConnectionError();
Logger::get().warning("SolarXR connection error during initialization: {}",
error->message() ? error->message()->str() : "");
break;
}
default:
break;
}
}
}
flatbuffers::FlatBufferBuilder fbb;
std::vector<flatbuffers::Offset<ConnectionMessageHeader>> connectionMsgs{
CreateConnectionMessageHeader(fbb, ConnectionMessage::ConfigurationAcknowledged,
CreateConfigurationAcknowledged(fbb).Union()),
};
auto bundle = CreateMessageBundleDirect(fbb, nullptr, nullptr, nullptr, &connectionMsgs);
FinishMessageBundleBuffer(fbb, bundle);
conn.sendMsg(fbb);
return true;
}
static void onYawReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
@@ -38,7 +109,7 @@ static void onYawReset(SolarXRConnection &conn) {
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
FinishMessageBundleBuffer(fbb, bundle);
conn.sendMsg(fbb);
}
static void onFullReset(SolarXRConnection &conn) {
@@ -50,7 +121,7 @@ static void onFullReset(SolarXRConnection &conn) {
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
FinishMessageBundleBuffer(fbb, bundle);
conn.sendMsg(fbb);
}
static void onMountingCalibration(SolarXRConnection &conn) {
@@ -62,21 +133,22 @@ static void onMountingCalibration(SolarXRConnection &conn) {
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
FinishMessageBundleBuffer(fbb, bundle);
conn.sendMsg(fbb);
}
static void onFeetMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto bodyParts = fbb.CreateVector(
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::POSE_MOUNTING, bodyParts, 0.f);
auto boneIds = fbb.CreateVector<uint16_t>(
{ static_cast<uint16_t>(datatypes::BodyPart::LEFT_FOOT),
static_cast<uint16_t>(datatypes::BodyPart::RIGHT_FOOT) });
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::POSE_MOUNTING, boneIds, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
FinishMessageBundleBuffer(fbb, bundle);
conn.sendMsg(fbb);
}
static void onToggleTracking(SolarXRConnection &conn) {
@@ -91,7 +163,7 @@ static void onToggleTracking(SolarXRConnection &conn) {
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
FinishMessageBundleBuffer(fbb, bundle);
conn.sendMsg(fbb);
}
@@ -136,6 +208,11 @@ int main() {
try {
SolarXRConnection conn;
if (!performSolarXRHandshake(conn)) {
logger.error("Failed to complete SolarXR connection initialization");
return 1;
}
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{ nullptr,
shutdown_vr };
+28
View File
@@ -129,3 +129,31 @@ void SolarXRConnection::sendMsg(flatbuffers::FlatBufferBuilder &fbb) {
return;
}
}
bool SolarXRConnection::recvExact(char *buf, size_t len) {
size_t done = 0;
while (done < len) {
auto n = recv(fd, buf + done, static_cast<int>(len - done), 0);
if (n == SocketError || n == 0) return false;
done += static_cast<size_t>(n);
}
return true;
}
std::optional<std::vector<uint8_t>> SolarXRConnection::recvMsg() {
uint32_t size = 0;
if (!recvExact(reinterpret_cast<char *>(&size), sizeof(size))) return std::nullopt;
if constexpr (std::endian::native != std::endian::little)
size = std::byteswap(size);
if (size < sizeof(size)) {
Logger::get().warning("Received an invalid SolarXR frame size {}", size);
return std::nullopt;
}
std::vector<uint8_t> buffer(size - sizeof(size));
if (!buffer.empty() && !recvExact(reinterpret_cast<char *>(buffer.data()), buffer.size())) {
return std::nullopt;
}
return buffer;
}
+9
View File
@@ -1,6 +1,8 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#ifdef _WIN32
#define WIN32_MEAN_AND_LEAN
@@ -46,6 +48,9 @@ private:
static std::filesystem::path getSocketPath();
// Reads exactly len bytes, looping over partial reads. false on EOF/error.
bool recvExact(char *buf, size_t len);
public:
SolarXRConnection() noexcept(false);
@@ -53,4 +58,8 @@ public:
bool connected();
void sendMsg(flatbuffers::FlatBufferBuilder &fbb);
// Reads one length-prefixed SolarXR frame (the same framing sendMsg writes).
// Returns nullopt on disconnect or a socket error.
std::optional<std::vector<uint8_t>> recvMsg();
};
+35 -30
View File
@@ -71,8 +71,9 @@ body_part-RIGHT_UPPER_LEG = Right thigh
body_part-RIGHT_LOWER_LEG = Right ankle
body_part-RIGHT_FOOT = Right foot
body_part-UPPER_CHEST = Upper chest
body_part-CHEST = Chest
body_part-WAIST = Waist
body_part-LOWER_CHEST = Lower chest
body_part-UPPER_WAIST = Upper waist
body_part-LOWER_WAIST = Lower waist
body_part-HIP = Hip
body_part-LEFT_SHOULDER = Left shoulder
body_part-LEFT_UPPER_ARM = Left upper arm
@@ -173,19 +174,24 @@ skeleton_bone-UPPER_CHEST-desc =
This is the distance from the base of your neck to the middle of your chest.
To adjust it, adjust your Torso Length properly and modify it in various positions
(sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.
skeleton_bone-CHEST = Chest Length
skeleton_bone-CHEST-desc =
skeleton_bone-LOWER_CHEST = Lower Chest Length
skeleton_bone-LOWER_CHEST-desc =
This is the distance from the middle of your chest to the middle of your spine.
To adjust it, adjust your Torso Length properly and modify it in various positions
(sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.
skeleton_bone-WAIST = Waist Length
skeleton_bone-WAIST-desc =
This is the distance from the middle of your spine to your belly button.
skeleton_bone-UPPER_WAIST = Upper Waist Length
skeleton_bone-UPPER_WAIST-desc =
This is the distance from the middle of your spine to a bit above your belly button.
To adjust it, adjust your Torso Length properly and modify it in various positions
(sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.
skeleton_bone-LOWER_WAIST = Lower Waist Length
skeleton_bone-LOWER_WAIST-desc =
This is the distance from a bit above your belly button to a bit below it.
To adjust it, adjust your Torso Length properly and modify it in various positions
(sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.
skeleton_bone-HIP = Hip Length
skeleton_bone-HIP-desc =
This is the distance from your belly button to your hips.
This is the distance from a bit bellow your belly button to your hips.
To adjust it, set your Torso Length properly and modify it in various positions
(sitting down, bending over, lying down, etc.) until your virtual spine matches your real one.
skeleton_bone-HIPS_WIDTH = Hips Width
@@ -271,15 +277,6 @@ reset-error-mounting-need_full_reset = Need a full reset before mounting
reset-error-yaw-need_full_reset = Need a full reset before yaw reset
reset-error-no_feet_tracker = No feet tracker assigned / available
## Serial detection stuff
serial_detection-new_device-p0 = New serial device detected!
serial_detection-new_device-p1 = Enter your Wi-Fi credentials!
serial_detection-new_device-p2 = Please select what you want to do with it
serial_detection-open_wifi = Connect to Wi-Fi
serial_detection-open_serial = Open USB Serial Console
serial_detection-submit = Submit!
serial_detection-close = Close
## Navigation bar
navbar-home = Home
navbar-body_proportions = Body Proportions
@@ -304,9 +301,7 @@ widget-developer_mode = Developer Mode
widget-developer_mode-high_contrast = High contrast
widget-developer_mode-precise_rotation = Precise rotation
widget-developer_mode-fast_data_feed = Fast data feed
widget-developer_mode-sort_by_name = Sort by name
widget-developer_mode-raw_slime_rotation = Raw rotation
widget-developer_mode-more_info = More info
## Widget: IMU Visualizer
widget-imu_visualizer = Tracking data
@@ -477,7 +472,7 @@ settings-sidebar-stay_aligned = Stay Aligned
settings-sidebar-tracking = Tracking
settings-sidebar-trackers = Trackers
settings-sidebar-interface = Interface
settings-sidebar-osc_trackers = VRChat OSC Trackers
settings-sidebar-vrchat_osc = VRChat OSC
settings-sidebar-osc_vmc = VMC
settings-sidebar-utils = Utilities
settings-sidebar-serial = USB Serial Console
@@ -630,6 +625,7 @@ settings-keybinds_pause-tracking = Pause Tracking
settings-keybinds_reset-all-button = Reset all
settings-keybinds-system-managed-description = Your desktop manages global shortcuts itself, so they have to be changed from your system settings.
settings-keybinds-open-system-settings-button = Open system settings
settings-keybinds-system-managed-hint = Set in system settings
settings-keybinds-unsupported-description = Global keybinds are not supported on this platform.
settings-sidebar-keybinds = Keybinds
settings-keybinds-recorder-modal-title = Assign keybind for
@@ -643,9 +639,9 @@ settings-keybinds-already-assigned = Already used by { $name }
settings-keybinds-click-to-record = Click to record shortcut
settings-keybinds-change-shortcut = Click to change shortcut
settings-keybinds-reset-single = Reset keybind to default
settings-keybinds-recorder-hint-recording = Hold Ctrl, Alt, or Super, then press a letter or number
settings-keybinds-error-letters-numbers-only = That key can't be used, pick a letter or number
settings-keybinds-error-add-modifier = You can only start a combination with Ctrl, Alt, or Super
settings-keybinds-recorder-hint-recording = Hold the keys you want, then release them
settings-keybinds-error-unsupported-key = That key can't be used in a shortcut
settings-keybinds-error-add-modifier = Hold Ctrl, Alt, or Super with that key
## FK/Tracking settings
@@ -692,7 +688,7 @@ settings-general-fk_settings-arm_fk-forward-description = Expects your arms to b
settings-general-fk_settings-skeleton_settings-ratios = Skeleton ratios
settings-general-fk_settings-skeleton_settings-ratios-description = Change the values of skeleton settings. You may need to adjust your proportions after changing these.
settings-general-fk_settings-skeleton_settings-impute_spine_from_upper_to_lower = Estimate missing spine trackers from upper to lower
settings-general-fk_settings-skeleton_settings-impute_spine_curvature = Spine curvature of adjacent missing spine trackers
settings-general-fk_settings-skeleton_settings-impute_spine_curvature = Spine curvature
settings-general-fk_settings-skeleton_settings-interpolate_hip_with_upper_legs = Interpolate the hip with the upper legs
settings-general-fk_settings-skeleton_settings-interpolate_upper_legs_twist_with_lower_legs = Interpolate the upper legs' twists with the lower legs'
settings-general-fk_settings-self_localization-title = Mocap mode
@@ -749,9 +745,6 @@ settings-interface-appearance-font_size-description = This affects the font size
## Notification settings
settings-interface-notifications = Notifications
settings-general-interface-serial_detection = Serial device detection
settings-general-interface-serial_detection-description = This option will show a pop-up every time you plug in a new serial device that could be a tracker. It helps to improve the setup process of a tracker.
settings-general-interface-serial_detection-label = Serial device detection
settings-general-interface-feedback_sound = Feedback sound
settings-general-interface-feedback_sound-description = This option plays a sound when a reset is triggered.
settings-general-interface-feedback_sound-label = Feedback sound
@@ -792,7 +785,7 @@ settings-interface-behavior-skeleton_mesh = Skeleton preview style
settings-interface-behavior-skeleton_mesh-description = Draw the body preview with solid 3D shapes instead of simple lines. Turn this off on low-end machines.
settings-interface-behavior-skeleton_mesh-label = Use 3D shapes
settings-interface-behavior-controller_nav = Game controller navigation
settings-interface-behavior-controller_nav-description = Move focus around the interface with a game controller. The D-pad or left stick move between controls, A activates, B goes back. Only active while a controller is connected.
settings-interface-behavior-controller_nav-description = Move focus around the interface with a game controller: the D-pad or left stick move between controls, A activates, B goes back, only while a controller is connected. Holding Ctrl or Alt with the arrow keys always moves focus the same way.
settings-interface-behavior-controller_nav-label = Navigate with a controller
## Serial settings
@@ -829,10 +822,10 @@ settings-serial-send_command-warning-ok = I know what I'm doing
settings-serial-send_command-warning-cancel = Cancel
## OSC VRChat settings
settings-osc-vrchat = VRChat OSC Trackers
settings-osc-vrchat = VRChat OSC
# This cares about multilines
settings-osc-vrchat-description-v1 =
Change settings specific to the OSC Trackers standard used for sending
Change settings specific to VRChat OSC and the OSC Trackers standard used to send
tracking data to applications without SteamVR (ex. Quest standalone).
Make sure to enable OSC in VRChat via the Action Menu under OSC > Enabled.
settings-osc-vrchat-enable = Enable
@@ -975,6 +968,14 @@ settings-home-list-layout-desc = Select one of the possible layouts of the home
settings-home-list-layout-grid = Grid
settings-home-list-layout-table = Table
settings-home-table_columns = Table columns
settings-home-table_columns-desc = Choose which columns are shown in the trackers table
settings-home-tracker_display = Tracker info
settings-home-tracker_display-desc = Choose which extra details are shown on trackers
settings-home-tracker_display-battery_voltage = Battery voltage
settings-home-tracker_display-numeric_signal = Numeric signal strength
## Tracking Checklist
settings-tracking_checklist-active_steps = Active Steps
settings-tracking_checklist-active_steps-desc = List of all the steps in the tracking checklist. You can choose to disable specific steps.
@@ -1415,6 +1416,10 @@ home-settings = Home Page Settings
home-settings-close = Close
home-connection_group-wifi = Wi-Fi Trackers
home-connection_group-driver = VR Devices
home-no_trackers-title = No trackers connected
home-no_trackers-description = Connect a tracker or turn on your existing trackers to get started
home-no_trackers-connect = Connect trackers
home-no_trackers-guide = View setup guide
# Accessible names and tooltips for the icon-only buttons in a connection group's toolbox
tracker-connection-metrics = Live telemetry
tracker-connection-dongle_settings = Dongle settings
+2 -18
View File
@@ -24,7 +24,6 @@ import { ManualMountingPage } from './components/onboarding/pages/mounting/Manua
import { TrackersAssignPage } from './components/onboarding/pages/trackers-assign/TrackerAssignment';
import { DonglePage } from './components/onboarding/pages/Dongle';
import { ConfigContextProvider } from './components/providers/ConfigContext';
import { SerialDetectionModal } from './components/SerialDetectionModal';
import { VRCOSCSettings } from './components/settings/pages/VRCOSCSettings';
import { BoneRoutingSettings } from './components/settings/pages/BoneRoutingSettings';
import { DriverSettings } from './components/settings/pages/DriverSettings';
@@ -45,6 +44,7 @@ import { Preload } from './components/Preload';
import { UnknownDeviceModal } from './components/UnknownDeviceModal';
import { useDiscordPresence } from './hooks/discord-presence';
import { useControllerNav } from './hooks/controller-nav';
import { useInternalLinkGuard } from './hooks/internal-links';
import { withSentryReactRouterV6Routing } from '@sentry/react';
import { ScaledProportionsPage } from './components/onboarding/pages/body-proportions/ScaledProportions';
import { AdvancedSettings } from './components/settings/pages/AdvancedSettings';
@@ -76,10 +76,10 @@ function Layout() {
const { isMobile } = useBreakpoint('mobile');
useDiscordPresence();
useControllerNav();
useInternalLinkGuard();
return (
<>
<SerialDetectionModal />
<VersionUpdateModal />
<UnknownDeviceModal />
<UdevRulesModal />
@@ -237,22 +237,6 @@ export default function App() {
}
};
useEffect(() => {
const onKeydown: (arg0: KeyboardEvent) => void = function (event) {
// prevent search bar keybind
if (
event.key === 'F3' ||
(event.ctrlKey && event.key === 'f') ||
(event.metaKey && event.key === 'f')
) {
event.preventDefault();
}
};
window.addEventListener('keydown', onKeydown);
return () => window.removeEventListener('keydown', onKeydown);
}, []);
useEffect(() => {
fetchReleases().catch((e) => error(e, 'failed to fetch releases'));
}, []);
@@ -1,168 +0,0 @@
import { Localized, useLocalization } from '@fluent/react';
import { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
NewSerialDeviceResponseT,
RpcMessage,
SerialDeviceT,
SerialDeviceType,
} from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useWifiCredsForm, WifiFormData } from '@/hooks/wifi-form';
import { BaseModal } from './commons/BaseModal';
import { Button } from './commons/Button';
import { BulbIcon } from './commons/icon/BulbIcon';
import { USBIcon } from './commons/icon/UsbIcon';
import { Input } from './commons/Input';
import { Typography } from './commons/Typography';
export function SerialDetectionModal() {
const { l10n } = useLocalization();
const { config } = useConfig();
const nav = useNavigate();
const { pathname } = useLocation();
const { useRPCPacket } = useWebsocketAPI();
const [isOpen, setOpen] = useState<SerialDeviceT | null>(null);
const [showWifiForm, setShowWifiForm] = useState(false);
const { handleSubmit, submitWifiCreds, formState, control } =
useWifiCredsForm();
const closeModal = () => {
setOpen(null);
setShowWifiForm(false);
};
const openSerial = () => {
nav('/settings/serial', { state: { serialPort: isOpen?.port } });
closeModal();
};
const openWifi = () => {
setShowWifiForm(true);
};
const modalWifiSubmit = (form: WifiFormData) => {
submitWifiCreds(form);
closeModal();
nav('/onboarding/connect-trackers', { state: { alonePage: true } });
};
useRPCPacket(
RpcMessage.NewSerialDeviceResponse,
({ device }: NewSerialDeviceResponseT) => {
if (
config?.watchNewDevices &&
![
'/settings/serial',
'/onboarding/add-trackers',
'/onboarding/connect-trackers',
'/settings/firmware-tool',
].includes(pathname) &&
device?.type !== SerialDeviceType.HID_RECEIVER
) {
setOpen(device);
}
}
);
return (
<BaseModal isOpen={!!isOpen} onRequestClose={closeModal}>
<div className="flex flex-col gap-3">
{!showWifiForm && (
<>
<div className="flex flex-col items-center gap-3 fill-accent-background-20">
<USBIcon />
<div className="flex flex-col items-center gap-2">
<Typography variant="main-title">
{l10n.getString('serial_detection-new_device-p0')}
</Typography>
<Typography variant="section-title">
{isOpen?.name || 'unknown'}
</Typography>
<Typography variant="standard">
{l10n.getString('serial_detection-new_device-p2')}
</Typography>
</div>
</div>
<Button variant="primary" onClick={openWifi}>
{l10n.getString('serial_detection-open_wifi')}
</Button>
<Button variant="tertiary" onClick={openSerial}>
{l10n.getString('serial_detection-open_serial')}
</Button>
<Button variant="tertiary" onClick={closeModal}>
{l10n.getString('serial_detection-close')}
</Button>
</>
)}
{showWifiForm && (
<form
onSubmit={handleSubmit(modalWifiSubmit)}
className="flex flex-col gap-3"
>
<div className="flex flex-col items-center gap-3">
<div className="fill-background-10">
<BulbIcon />
</div>
<Typography variant="main-title">
{l10n.getString('serial_detection-new_device-p0')}
</Typography>
<Typography variant="standard">
{l10n.getString('serial_detection-new_device-p1')}
</Typography>
</div>
<div className="flex flex-col gap-3 rounded-xl max-w-sm sentry-mask">
<Localized
id="onboarding-wifi_creds-ssid"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{ required: true }}
name="ssid"
type="text"
label="SSID"
placeholder="ssid"
variant="secondary"
/>
</Localized>
<Localized
id="onboarding-wifi_creds-password"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{
validate: {
validPassword: (v: string | undefined) =>
!v || new TextEncoder().encode(v).length >= 8, // WPA2 min password is 8 bytes
},
}}
name="password"
type="password"
label="Password"
placeholder="password"
variant="secondary"
/>
</Localized>
</div>
<Button
type="submit"
variant="primary"
disabled={!formState.isValid}
>
{l10n.getString('serial_detection-submit')}
</Button>
<Button variant="tertiary" onClick={closeModal}>
{l10n.getString('serial_detection-close')}
</Button>
</form>
)}
</div>
</BaseModal>
);
}
+8 -26
View File
@@ -1,4 +1,5 @@
import { useTrackingChecklist } from '@/hooks/tracking-checklist';
import { NavLink } from 'react-router-dom';
import { Clickable } from './commons/Clickable';
import { TrackingChecklist } from './tracking-checklist/TrackingChecklist';
import { SkeletonVisualizerWidget } from './widgets/SkeletonVisualizerWidget';
@@ -68,17 +69,19 @@ export function PreviewControls({ open }: { open: boolean }) {
<Typography id="onboarding-manual_proportions-estimated_height" />
}
>
<div
<NavLink
to="/onboarding/body-proportions/scaled"
state={{ alonePage: true }}
className={classNames(
'h-10 bg-background-60 p-4 flex items-center rounded-lg justify-center cursor-help w-fit top-2 left-2 absolute',
'h-10 bg-background-60 p-4 flex items-center rounded-lg justify-center cursor-pointer hover:bg-background-50 w-fit top-2 left-2 absolute',
{
'opacity-0': !open,
'opacity-0 pointer-events-none': !open,
'opacity-100': open,
}
)}
>
<Typography variant="section-title">{userHeight}</Typography>
</div>
</NavLink>
</Tooltip>
<div className="absolute bottom-0 pb-4 flex justify-center w-full">
<div className="flex bg-background-80 bg-opacity-70 rounded-lg gap-2 px-4 py-2 items-center fill-background-10">
@@ -232,33 +235,12 @@ function PreviewSection({ open }: { open: boolean }) {
}
export function Sidebar() {
const { completion } = useTrackingChecklist();
const [closed, setClosed] = useState(true);
const [closing, setClosing] = useState(false);
const { closed, closing, toggleClosed } = useTrackingChecklist();
const closedHight = '90px';
const checklistSize = closed ? closedHight : 'calc(100% - 16px)';
const previewSize = closed ? `calc(100% - ${closedHight} - 24px)` : '0%';
const toggleClosed = () => setClosed((closed) => !closed);
useLayoutEffect(() => {
setClosing(true);
const ref = setTimeout(() => setClosing(false), 1000);
return () => {
clearTimeout(ref);
setClosing(false);
};
}, [closed]);
useEffect(() => {
if (completion === 'complete') {
setClosed(true);
} else if (completion === 'incomplete') {
setClosed(false);
}
}, [completion]);
return (
<>
<div
+11 -7
View File
@@ -10,7 +10,11 @@ import {
} from '@/hooks/reset';
import { Tooltip } from './commons/Tooltip';
import { useAtomValue } from 'jotai';
import { assignedTrackersAtom } from '@/store/app-store';
import {
assignedTrackersAtom,
bodyPartOfBone,
boneRegistryAtom,
} from '@/store/app-store';
import { useBreakpoint } from '@/hooks/breakpoint';
import { useMemo } from 'react';
import { ResetButtonIcon } from './home/ResetButton';
@@ -147,6 +151,7 @@ function BasicResetButton({
export function Toolbar() {
const assignedTrackers = useAtomValue(assignedTrackersAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const { visibleGroups, groupVisibility } = useMemo(() => {
const groupVisibility = Object.keys(BODY_PARTS_GROUPS)
@@ -154,11 +159,10 @@ export function Toolbar() {
.reduce(
(curr, key) => {
const group = key as MountingResetGroup;
curr[group] = assignedTrackers.some(
({ tracker }) =>
tracker.info?.bodyPart &&
BODY_PARTS_GROUPS[group].includes(tracker.info?.bodyPart)
);
curr[group] = assignedTrackers.some(({ tracker }) => {
const bodyPart = bodyPartOfBone(boneRegistry, tracker.info?.boneId);
return bodyPart && BODY_PARTS_GROUPS[group].includes(bodyPart);
});
return curr;
},
@@ -169,7 +173,7 @@ export function Toolbar() {
groupVisibility,
visibleGroups: Object.values(groupVisibility).filter((v) => v).length,
};
}, [assignedTrackers]);
}, [assignedTrackers, boneRegistry]);
return (
<>
+8 -2
View File
@@ -1,12 +1,13 @@
import classNames from 'classnames';
import { ReactNode } from 'react';
import ReactModal from 'react-modal';
import { collectFocusables } from '@/utils/focus-nav';
import { collectFocusables, isFocusable } from '@/utils/focus-nav';
/**
* `react-modal` parks focus on its own `tabindex="-1"` content node, which is
* not something a user can act on. Runs a frame late to land after react-modal's
* own focus call, and leaves an explicit `autoFocus` in the content alone.
* A `[data-nav-entry]` takes the priority
*
* FIXME: replace react-modal; its focus handling keeps forcing workarounds.
*/
@@ -14,7 +15,12 @@ function focusFirstControl(contentEl: HTMLDivElement) {
requestAnimationFrame(() => {
const active = document.activeElement;
if (active && active !== contentEl && contentEl.contains(active)) return;
collectFocusables(contentEl)[0]?.focus();
const entry = contentEl.querySelector<HTMLElement>('[data-nav-entry]');
const target =
(entry && (isFocusable(entry) ? entry : collectFocusables(entry)[0])) ||
collectFocusables(contentEl)[0];
target?.focus();
});
}
+10 -4
View File
@@ -1,8 +1,13 @@
import classNames from 'classnames';
import { useEffect, useMemo, useRef, useState } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { PersonFrontIcon } from './PersonFrontIcon';
import { FlatDeviceTracker, groupTrackerByBodyPart } from '@/store/app-store';
import {
boneRegistryAtom,
FlatDeviceTracker,
groupTrackerByBodyPart,
} from '@/store/app-store';
import { useAtomValue } from 'jotai';
interface SlotDot {
id: string;
@@ -121,9 +126,10 @@ export function BodyDisplay({
};
}, []);
const boneRegistry = useAtomValue(boneRegistryAtom);
const trackerByPart = useMemo(
() => groupTrackerByBodyPart(trackers),
[trackers]
() => groupTrackerByBodyPart(trackers, boneRegistry),
[trackers, boneRegistry]
);
return (
@@ -1,5 +1,6 @@
import classNames from 'classnames';
import {
FocusEvent,
HTMLAttributes,
PointerEvent,
ReactNode,
@@ -8,7 +9,7 @@ import {
useRef,
useState,
} from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { useBreakpoint } from '@/hooks/breakpoint';
const DOT_HIT_PADDING = 12;
@@ -19,10 +20,10 @@ export interface BodySideNames {
}
const bodyPartFromName = (name: string): BodyPart | null => {
const part = (BodyPart as unknown as Record<string, number | undefined>)[
const part = (BodyPart as unknown as Record<string, string | undefined>)[
name
];
return typeof part === 'number' ? part : null;
return typeof part === 'string' ? (part as BodyPart) : null;
};
const boxOf = (el: HTMLElement, offset: { left: number; top: number }) => {
@@ -282,13 +283,24 @@ export function BodyInteractions({
setSlotsButtonPos(slots);
};
const onControlPointerOver = (event: PointerEvent<HTMLDivElement>) => {
const control = (event.target as HTMLElement).closest<HTMLElement>(
const highlightFrom = (target: EventTarget | null) => {
const control = (target as HTMLElement | null)?.closest<HTMLElement>(
'.control'
);
setHoveredControl(control?.id || null);
};
const onControlPointerOver = (event: PointerEvent<HTMLDivElement>) =>
highlightFrom(event.target);
const controlFocusProps = {
onPointerOver: onControlPointerOver,
onPointerLeave: () => setHoveredControl(null),
onFocusCapture: (event: FocusEvent<HTMLDivElement>) =>
highlightFrom(event.target),
onBlurCapture: () => setHoveredControl(null),
};
updateSlotsRef.current = updateSlots;
const assignedKey = useMemo(
() => [...assignedRoles].sort((a, b) => a - b).join(','),
@@ -357,21 +369,11 @@ export function BodyInteractions({
height="100%"
/>
<div className="flex flex-col w-full h-full">
<div
ref={topContainerRef}
className="z-10"
onPointerOver={onControlPointerOver}
onPointerLeave={() => setHoveredControl(null)}
>
<div ref={topContainerRef} className="z-10" {...controlFocusProps}>
{topControls}
</div>
<div className="flex flex-grow min-h-0 gap-5">
<div
ref={leftContainerRef}
className="z-10"
onPointerOver={onControlPointerOver}
onPointerLeave={() => setHoveredControl(null)}
>
<div ref={leftContainerRef} className="z-10" {...controlFocusProps}>
{leftControls}
</div>
<div
@@ -396,7 +398,11 @@ export function BodyInteractions({
<div
key={id}
{...(part != null ? dotProps?.(part) : undefined)}
className={classNames('absolute z-10')}
aria-hidden="true"
className={classNames(
'absolute z-10',
hidden && 'pointer-events-none'
)}
onClick={() =>
!hidden && part != null && onSelectRole(part)
}
@@ -455,21 +461,11 @@ export function BodyInteractions({
}
)}
</div>
<div
ref={rightContainerRef}
className="z-10"
onPointerOver={onControlPointerOver}
onPointerLeave={() => setHoveredControl(null)}
>
<div ref={rightContainerRef} className="z-10" {...controlFocusProps}>
{rightControls}
</div>
</div>
<div
ref={bottomContainerRef}
className="z-10"
onPointerOver={onControlPointerOver}
onPointerLeave={() => setHoveredControl(null)}
>
<div ref={bottomContainerRef} className="z-10" {...controlFocusProps}>
{bottomControls}
</div>
</div>
@@ -1,4 +1,5 @@
import { BoardType, BodyPart, DeviceDataT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BoardType, DeviceDataT } from 'solarxr-protocol';
import { useLocaleConfig } from '@/i18n/config';
import { AnkleIcon } from './icon/AnkleIcon';
import { ButterflyIcon } from './icon/ButterflyIcon';
@@ -72,7 +73,7 @@ export const mapPart: Record<
}) => JSX.Element
> = {
[BodyPart.UPPER_CHEST]: ({ width }) => <UpperChestIcon width={width} />,
[BodyPart.CHEST]: ({ width }) => <ChestIcon width={width} />,
[BodyPart.LOWER_CHEST]: ({ width }) => <ChestIcon width={width} />,
[BodyPart.HEAD]: ({ width }) => <HeadsetIcon width={width} />,
[BodyPart.HIP]: ({ width }) => <HipIcon width={width} />,
[BodyPart.LEFT_FOOT]: ({ width, currentLocales }) =>
@@ -111,7 +112,8 @@ export const mapPart: Record<
[BodyPart.RIGHT_UPPER_LEG]: ({ width }) => (
<UpperLegIcon width={width} flipped />
),
[BodyPart.WAIST]: ({ width }) => <WaistIcon width={width} />,
[BodyPart.UPPER_WAIST]: ({ width }) => <WaistIcon width={width} />,
[BodyPart.LOWER_WAIST]: ({ width }) => <WaistIcon width={width} />,
[BodyPart.LEFT_THUMB_METACARPAL]: ({ width }) => (
<FingersIcon width={width} />
),
+2 -1
View File
@@ -99,7 +99,8 @@ export const CheckboxInternal = forwardRef<
'bg-accent-background-50': checked && disabled,
'bg-accent-background-30 animate-pulse': loading && !disabled,
'bg-background-50':
((!checked && color == 'primary') || color == 'secondary') &&
!checked &&
(color == 'primary' || color == 'secondary') &&
!loading,
'bg-background-40': !checked && color == 'tertiary' && !loading,
})}
+54 -19
View File
@@ -169,6 +169,8 @@ function DropdownItem({
);
}
export type DropdownAction = 'all' | 'none';
type DropdownListProps = {
isOpen: boolean;
onSelect: (item: DropdownItem) => void;
@@ -177,6 +179,7 @@ type DropdownListProps = {
onSelectAll?: () => void;
onDeselectAll?: () => void;
innerFocusValue: string | null;
focusedAction: DropdownAction | null;
anchorName: string;
} & Pick<
Required<DropdownProps>,
@@ -198,6 +201,7 @@ const DropdownList = forwardRef<HTMLDivElement, DropdownListProps>(function (
onSelectAll,
onDeselectAll,
innerFocusValue,
focusedAction,
display,
alignment,
direction,
@@ -261,20 +265,28 @@ const DropdownList = forwardRef<HTMLDivElement, DropdownListProps>(function (
{multiple && (onSelectAll || onDeselectAll) && (
<div className="flex items-center justify-between px-3 py-2 border-b border-background-10/10 text-xs font-bold bg-background-80/60 select-none">
<Clickable
id={`__dropdownList-${name}-action-all`}
onClick={(e) => {
e.stopPropagation();
onSelectAll?.();
}}
className="text-background-10 hover:text-background-20 transition-colors"
className={classNames(
'text-background-10 hover:text-background-20 transition-colors rounded',
focusedAction === 'all' && 'ring-2 ring-accent-background-10'
)}
>
<Typography id="dropdown_select-all" />
</Clickable>
<Clickable
id={`__dropdownList-${name}-action-none`}
onClick={(e) => {
e.stopPropagation();
onDeselectAll?.();
}}
className="text-background-30 hover:text-background-10 transition-colors"
className={classNames(
'text-background-30 hover:text-background-10 transition-colors rounded',
focusedAction === 'none' && 'ring-2 ring-accent-background-10'
)}
>
<Typography id="dropdown_unselect-all" />
</Clickable>
@@ -368,29 +380,47 @@ export function DropdownInside(
}
};
const selectAll = () =>
props.multiple && props.onChange(items.map((i) => i.value));
const deselectAll = () => props.multiple && props.onChange([]);
/**
* The header select-all / unselect-all buttons sit before the items in the
* roving order, so arrows reach them like any option.
*/
const actionKeys: DropdownAction[] = props.multiple ? ['all', 'none'] : [];
const navCount = actionKeys.length + items.length;
const resolveNav = (
index: number | null
): { action: DropdownAction | null; item: DropdownItem | null } => {
if (index === null || index < 0) return { action: null, item: null };
if (index < actionKeys.length)
return { action: actionKeys[index] ?? null, item: null };
return { action: null, item: items[index - actionKeys.length] ?? null };
};
const ref = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const anchorName = `--dropdown-anchor-${useId().replace(/:/g, '')}`;
const [innerFocusIndex, setInnerFocusIndex] = useState<number | null>(null);
// Index may point past the array (items changed, empty list) - resolve safely.
const focusedItem =
innerFocusIndex === null ? null : (items[innerFocusIndex] ?? null);
// Index may point past the range (items changed, empty list) - resolve safely.
const { action: focusedAction, item: focusedItem } =
resolveNav(innerFocusIndex);
const getCurrentActiveIndex = () => {
return props.multiple
const i = props.multiple
? items.findIndex((item) => props.value.includes(item.value))
: items.findIndex((item) => item.value === props.value);
return i >= 0 ? i + actionKeys.length : actionKeys.length;
};
const innerFocusPrev = () => {
const current = innerFocusIndex ?? getCurrentActiveIndex();
setInnerFocusIndex(current > 0 ? current - 1 : current);
setInnerFocusIndex(Math.max(0, current - 1));
};
const innerFocusNext = () => {
const current = innerFocusIndex ?? getCurrentActiveIndex();
setInnerFocusIndex(current < items.length - 1 ? current + 1 : current);
setInnerFocusIndex(Math.min(navCount - 1, current + 1));
};
useEffect(() => {
@@ -442,7 +472,9 @@ export function DropdownInside(
items.length > 0 &&
(e.key === 'ArrowDown' || e.key === 'ArrowUp')
) {
setInnerFocusIndex(e.key === 'ArrowDown' ? 0 : items.length - 1);
setInnerFocusIndex(
e.key === 'ArrowDown' ? actionKeys.length : navCount - 1
);
setIsOpen(true);
e.preventDefault();
}
@@ -450,6 +482,8 @@ export function DropdownInside(
} else {
if (a11yClick(e)) {
e.preventDefault();
if (focusedAction === 'all') return selectAll();
if (focusedAction === 'none') return deselectAll();
if (!focusedItem) {
setIsOpen(false);
return;
@@ -476,7 +510,7 @@ export function DropdownInside(
setInnerFocusIndex(0);
return;
case 'End':
setInnerFocusIndex(items.length - 1);
setInnerFocusIndex(navCount - 1);
return;
}
}
@@ -507,9 +541,11 @@ export function DropdownInside(
aria-controls={`__dropdownList-${name}`}
aria-expanded={isOpen}
aria-activedescendant={
focusedItem
? `__dropdownList-${name}-item-${focusedItem.value}`
: ''
focusedAction
? `__dropdownList-${name}-action-${focusedAction}`
: focusedItem
? `__dropdownList-${name}-item-${focusedItem.value}`
: ''
}
role="combobox"
>
@@ -545,10 +581,8 @@ export function DropdownInside(
isOpen={isOpen}
items={items}
multiple={props.multiple}
onSelectAll={() =>
props.multiple && props.onChange(items.map((i) => i.value))
}
onDeselectAll={() => props.multiple && props.onChange([])}
onSelectAll={selectAll}
onDeselectAll={deselectAll}
onSelect={(item: DropdownItem) => {
ref.current?.focus();
selectItem(item);
@@ -559,6 +593,7 @@ export function DropdownInside(
ref={listRef}
anchorName={anchorName}
innerFocusValue={focusedItem?.value ?? null}
focusedAction={focusedAction}
name={name}
/>
</div>
@@ -1,4 +1,4 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import {
ExtremityFigureSpec,
ExtremityParts,
@@ -11,58 +11,26 @@ import { Kbd } from './Kbd';
import classNames from 'classnames';
import { useLocalization } from '@fluent/react';
import './KeybindRow.scss';
const MODIFIER_ORDER = ['CTRL', 'ALT', 'SHIFT', 'SUPER'];
const NON_SHIFT_MODIFIERS = ['CTRL', 'ALT', 'SUPER'];
const MODIFIER_KEY_NAMES: Record<string, string> = {
CONTROL: 'CTRL',
ALT: 'ALT',
SHIFT: 'SHIFT',
META: 'SUPER',
OS: 'SUPER',
};
import {
MODIFIER_ORDER,
keybindLabel,
modifierNameForKey,
modifiersFromHeld,
resolveKey,
} from './keybind-keys';
const maxKeybindLength = 5;
function orderModifiers(mods: string[]): string[] {
return MODIFIER_ORDER.filter((m) => mods.includes(m));
}
export function isValidKeybind(keys: string[]): boolean {
const main = keys.filter((k) => !MODIFIER_ORDER.includes(k));
if (main.length !== 1 || !/^[A-Z0-9]$/.test(main[0])) return false;
return keys.some((k) => NON_SHIFT_MODIFIERS.includes(k));
}
export function keybindKey(keys: string[]): string {
return [...keys].sort().join('+');
}
function resolveMainKey(code: string): string | null {
if (code.startsWith('Key')) return code.slice(3);
if (code.startsWith('Digit')) return code.slice(5);
if (code.startsWith('Numpad') && code.length === 7 && /^\d$/.test(code[6]))
return code[6];
return null;
}
function modifiersFromEvent(e: React.KeyboardEvent): string[] {
const mods: string[] = [];
if (e.ctrlKey) mods.push('CTRL');
if (e.altKey) mods.push('ALT');
if (e.shiftKey) mods.push('SHIFT');
if (e.metaKey) mods.push('SUPER');
return orderModifiers(mods);
}
type RecorderState = {
preview: string[] | null;
held: Set<string>;
best: string[] | null;
flash: { slot: number; msgId: string } | null;
};
type RecorderAction =
| { type: 'preview'; keys: string[] }
| { type: 'clearPreview' }
| { type: 'keydown'; code: string; keys: string[] }
| { type: 'keyup'; code: string }
| { type: 'clear' }
| { type: 'flash'; slot: number; msgId: string }
| { type: 'clearFlash' };
@@ -71,10 +39,24 @@ function recorderReducer(
action: RecorderAction
): RecorderState {
switch (action.type) {
case 'preview':
return { preview: action.keys, flash: null };
case 'clearPreview':
return { ...state, preview: null };
case 'keydown': {
const held = new Set(state.held);
held.add(action.code);
const hasMain = action.keys.some((k) => !MODIFIER_ORDER.includes(k));
const bestHasMain = (state.best ?? []).some(
(k) => !MODIFIER_ORDER.includes(k)
);
const best =
hasMain || !bestHasMain ? action.keys : (state.best ?? action.keys);
return { held, best, flash: null };
}
case 'keyup': {
const held = new Set(state.held);
held.delete(action.code);
return { ...state, held };
}
case 'clear':
return { held: new Set(), best: null, flash: null };
case 'flash':
return { ...state, flash: { slot: action.slot, msgId: action.msgId } };
case 'clearFlash':
@@ -98,16 +80,18 @@ export const KeybindRecorder = forwardRef<
) {
const { l10n } = useLocalization();
const [state, dispatch] = useReducer(recorderReducer, {
preview: null,
held: new Set<string>(),
best: null,
flash: null,
});
const [focused, setFocused] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => inputRef.current!, []);
const showing = state.preview ?? keys;
const recording = state.held.size > 0;
const showing = recording ? (state.best ?? []) : keys;
const activeIndex = showing.length;
const slotCount = state.preview
const slotCount = recording
? Math.min(showing.length + 1, maxKeybindLength)
: Math.max(showing.length, 1);
const displayError = state.flash ? l10n.getString(state.flash.msgId) : error;
@@ -124,58 +108,68 @@ export const KeybindRecorder = forwardRef<
}, [state.flash]);
const handleKeyDown = (e: React.KeyboardEvent) => {
e.preventDefault();
e.stopPropagation();
const hasModifier = state.held.size > 0;
if (e.key === 'Escape') {
if (!hasModifier && e.key === 'Escape') {
onCloseModal?.();
return;
}
if (e.key === 'Backspace' || e.key === 'Delete') {
if (!hasModifier && (e.key === 'Backspace' || e.key === 'Delete')) {
onUnbindModal?.();
return;
}
if (e.key === 'Enter') {
if (!hasModifier && e.key === 'Enter') {
onSubmitModal?.();
return;
}
const modifiers = modifiersFromEvent(e);
e.preventDefault();
e.stopPropagation();
if (e.repeat) return;
if (MODIFIER_KEY_NAMES[e.key.toUpperCase()]) {
dispatch({ type: 'preview', keys: modifiers });
return;
}
const mainKey = resolveMainKey(e.code);
if (!mainKey) {
const modifierName = modifierNameForKey(e.key);
if (modifierName) {
dispatch({
type: 'flash',
slot: activeIndex,
msgId: 'settings-keybinds-error-letters-numbers-only',
type: 'keydown',
code: e.code,
keys: modifiersFromHeld(new Set(state.held).add(e.code)),
});
return;
}
dispatch({ type: 'clearPreview' });
onKeysChange([...modifiers, mainKey]);
const key = resolveKey(e);
if (!key) {
dispatch({
type: 'flash',
slot: activeIndex,
msgId: 'settings-keybinds-error-unsupported-key',
});
return;
}
dispatch({
type: 'keydown',
code: e.code,
keys: [...modifiersFromHeld(state.held), key],
});
};
const handleKeyUp = (e: React.KeyboardEvent) => {
if (state.preview === null) return;
if (
e.key === 'Escape' ||
e.key === 'Enter' ||
e.key === 'Backspace' ||
e.key === 'Delete'
)
return;
const modifiers = modifiersFromEvent(e);
dispatch(
modifiers.length > 0
? { type: 'preview', keys: modifiers }
: { type: 'clearPreview' }
);
const wasRecording = state.held.size > 0;
dispatch({ type: 'keyup', code: e.code });
if (!wasRecording) return;
const stillHeld = new Set(state.held);
stillHeld.delete(e.code);
if (stillHeld.size === 0 && state.best) {
onKeysChange(state.best);
dispatch({ type: 'clear' });
}
};
const handleBlur = () => {
setFocused(false);
if (state.held.size > 0) dispatch({ type: 'clear' });
};
return (
@@ -194,8 +188,9 @@ export const KeybindRecorder = forwardRef<
<input
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
ref={inputRef}
data-nav-raw
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
/>
@@ -217,7 +212,7 @@ export const KeybindRecorder = forwardRef<
variant={variant}
className="px-4 py-2 min-w-[54px] h-[48px]"
>
{key ?? (isActive ? '...' : '')}
{key != null ? keybindLabel(key) : isActive ? '...' : ''}
</Kbd>
{i < slotCount - 1 && (
<Typography variant="standard" bold textAlign="text-center">
@@ -6,7 +6,8 @@ import {
FieldValues,
FieldPath,
} from 'react-hook-form';
import { KeybindRecorder, isValidKeybind, keybindKey } from './KeybindRecorder';
import { KeybindRecorder } from './KeybindRecorder';
import { isValidKeybind, keybindKey } from './keybind-keys';
import { Kbd } from './Kbd';
import { Typography } from './Typography';
import { KeyboardIcon } from './icon/KeyboardIcon';
@@ -30,6 +31,7 @@ export function KeybindRecorderModal<T extends FieldValues = FieldValues>({
onUnbind,
onSubmit,
takenBindings,
activatedError,
}: {
id?: string;
control: Control<T>;
@@ -40,6 +42,7 @@ export function KeybindRecorderModal<T extends FieldValues = FieldValues>({
onSubmit: () => void;
onReset?: () => void;
takenBindings?: { name: string; binding: string[] }[];
activatedError?: string | null;
}) {
const keybindlocalization = 'settings-keybinds_' + id;
const { l10n } = useLocalization();
@@ -92,7 +95,7 @@ export function KeybindRecorderModal<T extends FieldValues = FieldValues>({
keys={field.value ?? []}
onKeysChange={field.onChange}
ref={field.ref}
error={fieldState.error?.message}
error={activatedError ?? fieldState.error?.message}
onSubmitModal={handleModalSubmit}
onUnbindModal={onUnbind}
onCloseModal={onClose}
+25 -12
View File
@@ -5,6 +5,7 @@ import { KeybindForm } from '@/components/settings/pages/KeybindSettings';
import { NumberSelector } from './NumberSelector';
import { useLocaleConfig } from '@/i18n/config';
import { Kbd } from './Kbd';
import { keybindLabel } from './keybind-keys';
import { RecordIcon } from './icon/RecordIcon';
import { ResetIcon } from './icon/ResetIcon';
import { Tooltip } from './Tooltip';
@@ -25,7 +26,7 @@ function KeyBindKeyList({ keybind }: { keybind: string[] }) {
{keybind.map((key, i) => (
<div key={i} className="flex items-center gap-1.5">
<Kbd className="px-2 md:px-4 py-2 min-w-[34px] md:min-w-[40px] group-hover:border-accent-background-40">
{key}
{keybindLabel(key)}
</Kbd>
{i < keybind.length - 1 && (
<Typography variant="standard" bold textAlign="text-center">
@@ -75,13 +76,15 @@ export function KeybindsRow({
openKeybindRecorderModal,
onResetSingle,
isModified,
bindingEditable = true,
}: {
id?: string;
control: Control<KeybindForm>;
index: number;
openKeybindRecorderModal: (index: number) => void;
openKeybindRecorderModal?: (index: number) => void;
onResetSingle: (index: number) => void;
isModified?: boolean;
bindingEditable?: boolean;
}) {
const binding =
useWatch({
@@ -129,17 +132,27 @@ export function KeybindsRow({
<td className="py-2 md:py-4 px-0 md:px-4 block md:table-cell align-middle">
<div className="flex justify-start md:justify-center items-center">
<Tooltip
content={<Typography id="settings-keybinds-change-shortcut" />}
preferedDirection="top"
>
<Clickable
className="cursor-pointer rounded-xl transition-all hover:scale-105 active:scale-95"
onClick={() => openKeybindRecorderModal(index)}
{bindingEditable && openKeybindRecorderModal ? (
<Tooltip
content={<Typography id="settings-keybinds-change-shortcut" />}
preferedDirection="top"
>
<KeyBindKeyList keybind={binding} />
</Clickable>
</Tooltip>
<Clickable
className="cursor-pointer rounded-xl transition-all hover:scale-105 active:scale-95"
onClick={() => openKeybindRecorderModal(index)}
>
<KeyBindKeyList keybind={binding} />
</Clickable>
</Tooltip>
) : (
<Typography
variant="standard"
textAlign="text-center"
italic
color="secondary"
id="settings-keybinds-system-managed-hint"
/>
)}
</div>
</td>
@@ -1,4 +1,4 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
export const SIDES = [
{
@@ -53,16 +53,16 @@ export function PersonFrontIcon({
<circle
className="body-part-circle"
cx="82"
cy="90"
cy="105"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.UPPER_CHEST]}
/>
<circle
className="body-part-circle"
cx="82"
cy="105"
cy="120"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.CHEST]}
id={BodyPart[BodyPart.LOWER_CHEST]}
/>
<circle
className="body-part-circle"
@@ -71,12 +71,19 @@ export function PersonFrontIcon({
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.HIP]}
/>
<circle
className="body-part-circle"
cx="82"
cy="140"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.UPPER_WAIST]}
/>
<circle
className="body-part-circle"
cx="82"
cy="155"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.WAIST]}
id={BodyPart[BodyPart.LOWER_WAIST]}
/>
<circle
className="body-part-circle"
@@ -44,6 +44,12 @@ export function VerticalStep({
setShouldAnimate(true);
}, [active]);
// A collapsed step is only clipped, not unmounted, so keep its controls out
// of the tab order and out of spatial focus nav until the step is open.
useEffect(() => {
if (ref.current) ref.current.inert = !isSelected;
}, [isSelected]);
// Make it so it wont try to animate the size
// if we are not changing active step
useDebouncedEffect(
@@ -0,0 +1,191 @@
export const MODIFIER_ORDER = ['CTRL', 'ALT', 'SHIFT', 'SUPER'];
const NON_SHIFT_MODIFIERS = ['CTRL', 'ALT', 'SUPER'];
const MODIFIER_KEY_NAMES: Record<string, string> = {
CONTROL: 'CTRL',
ALT: 'ALT',
SHIFT: 'SHIFT',
META: 'SUPER',
OS: 'SUPER',
};
// `KeyboardEvent.code` -> canonical modifier name. The held-key set stores codes (so left/right
// variants of the same modifier don't collide), so lookups against it need this, not
// MODIFIER_KEY_NAMES (which is keyed by the location-less `e.key`).
const MODIFIER_CODE_NAMES: Record<string, string> = {
ControlLeft: 'CTRL',
ControlRight: 'CTRL',
AltLeft: 'ALT',
AltRight: 'ALT',
ShiftLeft: 'SHIFT',
ShiftRight: 'SHIFT',
MetaLeft: 'SUPER',
MetaRight: 'SUPER',
OSLeft: 'SUPER',
OSRight: 'SUPER',
};
// Keys bindable without a modifier: function, media/volume, and standalone system keys.
const MODIFIER_OPTIONAL_KEYS = new Set([
...Array.from({ length: 24 }, (_, i) => `F${i + 1}`),
'MEDIA_PLAY_PAUSE',
'MEDIA_STOP',
'MEDIA_NEXT',
'MEDIA_PREVIOUS',
'VOLUME_UP',
'VOLUME_DOWN',
'VOLUME_MUTE',
'PRINT_SCREEN',
'PAUSE',
'SCROLL_LOCK',
]);
// `KeyboardEvent.code` -> our canonical key name, kept in sync with
// server/core/.../keybind/keys.kt. Falls back to null (unbindable) for anything else.
const CODE_TO_KEY: Record<string, string> = {
ArrowUp: 'UP',
ArrowDown: 'DOWN',
ArrowLeft: 'LEFT',
ArrowRight: 'RIGHT',
Home: 'HOME',
End: 'END',
PageUp: 'PAGE_UP',
PageDown: 'PAGE_DOWN',
Insert: 'INSERT',
Delete: 'DELETE',
Space: 'SPACE',
Enter: 'ENTER',
Tab: 'TAB',
Backspace: 'BACKSPACE',
Escape: 'ESCAPE',
NumpadAdd: 'NUMPAD_ADD',
NumpadSubtract: 'NUMPAD_SUBTRACT',
NumpadMultiply: 'NUMPAD_MULTIPLY',
NumpadDivide: 'NUMPAD_DIVIDE',
NumpadDecimal: 'NUMPAD_DECIMAL',
NumpadEnter: 'NUMPAD_ENTER',
Minus: 'MINUS',
Equal: 'EQUAL',
BracketLeft: 'BRACKET_LEFT',
BracketRight: 'BRACKET_RIGHT',
Backslash: 'BACKSLASH',
Semicolon: 'SEMICOLON',
Quote: 'QUOTE',
Backquote: 'BACKQUOTE',
Comma: 'COMMA',
Period: 'PERIOD',
Slash: 'SLASH',
PrintScreen: 'PRINT_SCREEN',
Pause: 'PAUSE',
ScrollLock: 'SCROLL_LOCK',
NumLock: 'NUM_LOCK',
CapsLock: 'CAPS_LOCK',
MediaPlayPause: 'MEDIA_PLAY_PAUSE',
MediaStop: 'MEDIA_STOP',
MediaTrackNext: 'MEDIA_NEXT',
MediaTrackPrevious: 'MEDIA_PREVIOUS',
AudioVolumeUp: 'VOLUME_UP',
AudioVolumeDown: 'VOLUME_DOWN',
AudioVolumeMute: 'VOLUME_MUTE',
};
// Canonical key name -> what to render in the Kbd slot.
const KEY_LABELS: Record<string, string> = {
UP: '↑',
DOWN: '↓',
LEFT: '←',
RIGHT: '→',
PAGE_UP: 'Pg Up',
PAGE_DOWN: 'Pg Dn',
PRINT_SCREEN: 'Prt Scn',
SCROLL_LOCK: 'Scroll Lk',
NUM_LOCK: 'Num Lk',
CAPS_LOCK: 'Caps Lk',
NUMPAD_ADD: 'Num +',
NUMPAD_SUBTRACT: 'Num -',
NUMPAD_MULTIPLY: 'Num *',
NUMPAD_DIVIDE: 'Num /',
NUMPAD_DECIMAL: 'Num .',
NUMPAD_ENTER: 'Num ↵',
MEDIA_PLAY_PAUSE: '⏯',
MEDIA_STOP: '⏹',
MEDIA_NEXT: '⏭',
MEDIA_PREVIOUS: '⏮',
VOLUME_UP: 'Vol +',
VOLUME_DOWN: 'Vol -',
VOLUME_MUTE: 'Vol Mute',
MINUS: '-',
EQUAL: '=',
BRACKET_LEFT: '[',
BRACKET_RIGHT: ']',
BACKSLASH: '\\',
SEMICOLON: ';',
QUOTE: "'",
BACKQUOTE: '`',
COMMA: ',',
PERIOD: '.',
SLASH: '/',
SPACE: 'Space',
ENTER: 'Enter',
TAB: 'Tab',
BACKSPACE: 'Backspace',
ESCAPE: 'Esc',
HOME: 'Home',
END: 'End',
INSERT: 'Ins',
DELETE: 'Del',
};
Array.from({ length: 10 }, (_, i) => i).forEach((i) => {
KEY_LABELS[`NUMPAD_${i}`] = `Num ${i}`;
});
export function keybindLabel(key: string): string {
return KEY_LABELS[key] ?? key;
}
function orderModifiers(mods: string[]): string[] {
return MODIFIER_ORDER.filter((m) => mods.includes(m));
}
export function isValidKeybind(keys: string[]): boolean {
const main = keys.filter((k) => !MODIFIER_ORDER.includes(k));
if (main.length !== 1) return false;
if (MODIFIER_OPTIONAL_KEYS.has(main[0])) return true;
return keys.some((k) => NON_SHIFT_MODIFIERS.includes(k));
}
// Ordered the same way as the server's canonicalKeybind, so the two stay in sync.
export function keybindKey(keys: string[]): string {
const modifiers = orderModifiers(keys.filter((k) => MODIFIER_ORDER.includes(k)));
const main = keys.filter((k) => !MODIFIER_ORDER.includes(k));
return [...modifiers, ...main].join('+');
}
const F_KEY = /^F([1-9]|1\d|2[0-4])$/;
export function resolveKey(e: React.KeyboardEvent): string | null {
if (MODIFIER_KEY_NAMES[e.key.toUpperCase()]) return null;
if (e.code.startsWith('Key')) return e.code.slice(3);
if (e.code.startsWith('Digit')) return e.code.slice(5);
if (e.code.startsWith('Numpad') && e.code.length === 7 && /^\d$/.test(e.code[6]))
return `NUMPAD_${e.code[6]}`;
// KeyboardEvent.code for function keys is already "F1".."F24", matching our canonical name.
if (F_KEY.test(e.code)) return e.code;
return CODE_TO_KEY[e.code] ?? null;
}
export function modifierNameForCode(code: string): string | undefined {
return MODIFIER_CODE_NAMES[code];
}
export function modifierNameForKey(key: string): string | undefined {
return MODIFIER_KEY_NAMES[key.toUpperCase()];
}
export function modifiersFromHeld(held: Set<string>): string[] {
const mods: string[] = [];
for (const code of held) {
const name = MODIFIER_CODE_NAMES[code];
if (name && !mods.includes(name)) mods.push(name);
}
return orderModifiers(mods);
}
@@ -25,7 +25,7 @@ import { useOnboarding } from '@/hooks/onboarding';
import { getLocalizedTrackerName } from '@/hooks/tracker';
import { ObjectSchema, object, string } from 'yup';
import { useAtomValue } from 'jotai';
import { devicesAtom } from '@/store/app-store';
import { boneRegistryAtom, devicesAtom } from '@/store/app-store';
import { DeviceCardControl } from '@/components/firmware-tool/DeviceCard';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { TipBox } from '@/components/commons/TipBox';
@@ -230,6 +230,7 @@ function OTADevicesList({
const { l10n } = useLocalization();
const { selectDevices } = useFirmwareTool();
const allDevices = useAtomValue(devicesAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const devices =
allDevices.filter(({ hardwareInfo, trackers }) => {
@@ -248,7 +249,7 @@ function OTADevicesList({
const deviceNames = ({ trackers }: DeviceDataT) =>
trackers
.map(({ info }) => getLocalizedTrackerName(l10n, info))
.map(({ info }) => getLocalizedTrackerName(l10n, info, boneRegistry))
.filter((i): i is string => !!i);
const selectedDevices = watch('ota.selectedDevices');
@@ -2,6 +2,7 @@ import { Localized, ReactLocalization, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { getLocalizedTrackerName } from '@/hooks/tracker';
import { ComponentProps, useEffect, useMemo, useRef, useState } from 'react';
import { BodyPart } from '@/utils/body-part';
import {
BoardType,
DeviceDataT,
@@ -33,7 +34,7 @@ import { object } from 'yup';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { A } from '@/components/commons/A';
import { useAtomValue } from 'jotai';
import { devicesAtom } from '@/store/app-store';
import { boneRegistryAtom, devicesAtom } from '@/store/app-store';
import { checkForUpdate } from '@/hooks/firmware-update';
interface FirmwareUpdateForm {
@@ -49,9 +50,13 @@ interface UpdateStatus {
deviceNames: string[];
}
const deviceNames = ({ trackers }: DeviceDataT, l10n: ReactLocalization) =>
const deviceNames = (
{ trackers }: DeviceDataT,
l10n: ReactLocalization,
boneRegistry: Map<number, BodyPart>
) =>
trackers
.map(({ info }) => getLocalizedTrackerName(l10n, info))
.map(({ info }) => getLocalizedTrackerName(l10n, info, boneRegistry))
.filter((i): i is string => !!i);
const DeviceList = ({
@@ -62,13 +67,14 @@ const DeviceList = ({
devices: DeviceDataT[];
}) => {
const { l10n } = useLocalization();
const boneRegistry = useAtomValue(boneRegistryAtom);
return devices.map((device, index) => (
<DeviceCardControl
key={index}
control={control}
name={`selectedDevices.${device.id}`}
deviceNames={deviceNames(device, l10n)}
deviceNames={deviceNames(device, l10n, boneRegistry)}
/>
));
};
@@ -111,6 +117,7 @@ export function FirmwareUpdate() {
const [status, setStatus] = useState<Record<string, UpdateStatus>>({});
const allDevices = useAtomValue(devicesAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const devices =
allDevices.filter(
@@ -306,7 +313,7 @@ export function FirmwareUpdate() {
type: FirmwareUpdateMethod.OTAFirmwareUpdate,
deviceIdPort: id,
board: device.hardwareInfo?.officialBoardType ?? BoardType.UNKNOWN,
deviceNames: deviceNames(device, l10n),
deviceNames: deviceNames(device, l10n, boneRegistry),
},
];
},
+117 -61
View File
@@ -13,6 +13,7 @@ import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useAtomValue } from 'jotai';
import {
assignedTrackersAtom,
boneRegistryAtom,
donglesAtom,
flatTrackersAtom,
groupTrackersByConnection,
@@ -25,18 +26,23 @@ import { HomeSettingsModal } from './HomeSettingsModal';
import { GroupTelemetryOverlay } from './GroupTelemetryOverlay';
import { LayoutIcon } from '@/components/commons/icon/LayoutIcon';
import { IconButton } from '@/components/commons/IconButton';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { Button } from '@/components/commons/Button';
import { ArrowLink } from '@/components/commons/ArrowLink';
import { DOCS_SITE } from '@/App';
export function Home() {
const { config } = useConfig();
const trackers = useAtomValue(assignedTrackersAtom);
const allTrackers = useAtomValue(flatTrackersAtom);
const dongles = useAtomValue(donglesAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const { highlightedTrackers } = useTrackingChecklist();
const navigate = useNavigate();
const groups = useMemo(
() => groupTrackersByConnection(allTrackers, dongles),
[allTrackers, dongles]
() => groupTrackersByConnection(allTrackers, dongles, boneRegistry),
[allTrackers, dongles, boneRegistry]
);
const sendToSettings = (tracker: TrackerDataT) => {
@@ -83,50 +89,25 @@ export function Home() {
<LayoutIcon size={18} />
</IconButton>
</div>
{config?.homeLayout == 'default' && groups.length > 0 && (
<div className="pl-2 pr-2 flex flex-col gap-4 pb-4">
{groups.map((group) => (
<TrackerConnectionGroupSection
key={group.key}
group={group}
variant="primary"
toolbox={
<TrackerConnectionGroupDefaultToolbox
group={group}
onOpenMetrics={(g) => setTelemetryGroup(g)}
/>
}
>
<div className="flex flex-col gap-3 pr-2">
{group.assigned.length > 0 && (
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-4 px-2">
{group.assigned.map(({ tracker, device }, index) => (
<TrackerCard
key={index}
tracker={tracker}
device={device}
onClick={() => sendToSettings(tracker)}
smol
showUpdates
interactable
warning={
!!highlightedTrackers?.trackers.find(
(t) => t === tracker.trackerId
) && highlightedTrackers.step
}
/>
))}
</div>
)}
{group.unassigned.length > 0 && (
<>
{group.assigned.length > 0 && (
<TrackerConnectionGroupUnassignedDivider
count={group.unassigned.length}
/>
)}
<div className="w-full overflow-x-auto h-full">
{config?.homeLayout == 'default' && groups.length > 0 && (
<div className="pl-2 pr-2 flex flex-col gap-4 pb-4">
{groups.map((group) => (
<TrackerConnectionGroupSection
key={group.key}
group={group}
variant="primary"
toolbox={
<TrackerConnectionGroupDefaultToolbox
group={group}
onOpenMetrics={(g) => setTelemetryGroup(g)}
/>
}
>
<div className="flex flex-col gap-3 pr-2">
{group.assigned.length > 0 && (
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-4 px-2">
{group.unassigned.map(({ tracker, device }, index) => (
{group.assigned.map(({ tracker, device }, index) => (
<TrackerCard
key={index}
tracker={tracker}
@@ -143,23 +124,98 @@ export function Home() {
/>
))}
</div>
</>
)}
</div>
</TrackerConnectionGroupSection>
))}
</div>
)}
)}
{group.unassigned.length > 0 && (
<>
{group.assigned.length > 0 && (
<TrackerConnectionGroupUnassignedDivider
count={group.unassigned.length}
/>
)}
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-4 px-2">
{group.unassigned.map(
({ tracker, device }, index) => (
<TrackerCard
key={index}
tracker={tracker}
device={device}
onClick={() => sendToSettings(tracker)}
smol
showUpdates
interactable
warning={
!!highlightedTrackers?.trackers.find(
(t) => t === tracker.trackerId
) && highlightedTrackers.step
}
/>
)
)}
</div>
</>
)}
</div>
</TrackerConnectionGroupSection>
))}
</div>
)}
{config?.homeLayout === 'table' && groups.length > 0 && (
<div className="mx-2 flex flex-col">
<TrackersTable
groups={groups}
clickedTracker={(tracker) => sendToSettings(tracker)}
onOpenMetrics={(g) => setTelemetryGroup(g)}
/>
</div>
)}
{config?.homeLayout === 'table' && groups.length > 0 && (
<div className="mx-2 flex flex-col">
<TrackersTable
groups={groups}
clickedTracker={(tracker) => sendToSettings(tracker)}
onOpenMetrics={(g) => setTelemetryGroup(g)}
/>
</div>
)}
{groups.length === 0 && (
<div className="flex flex-col items-center justify-center gap-4 text-center p-6 flex-grow">
<div className="relative flex items-center justify-center antialiased">
<div
className="absolute w-64 h-64 rounded-full pointer-events-none"
style={{
background:
'radial-gradient(circle, rgb(var(--accent-background-30), 0.25) 0%, rgb(var(--accent-background-30), 0) 70%)',
}}
/>
<LoaderIcon
slimeState={SlimeState.CURIOUS}
size={140}
lowPriority
/>
</div>
<div className="flex flex-col gap-1 max-w-xs">
<Typography
bold
variant="section-title"
id="home-no_trackers-title"
/>
<Typography
variant="standard"
color="secondary"
id="home-no_trackers-description"
/>
</div>
<Button
variant="primary"
to="/onboarding/connect-trackers"
state={{ alonePage: true }}
id="home-no_trackers-connect"
>
Connect trackers
</Button>
<ArrowLink
to={`${DOCS_SITE}/quick-setup.html`}
direction="right"
variant="flat"
>
<Typography id="home-no_trackers-guide" />
</ArrowLink>
</div>
)}
</div>
</div>
</div>
);
@@ -12,13 +12,13 @@ export function HomeSettingsModal({
return (
<BaseModal
isOpen={open[0]}
appendClasses={'max-w-xl w-full'}
appendClasses={'max-w-2xl w-full max-h-[85vh] overflow-y-auto !p-0'}
closeable
onRequestClose={() => {
open[1](false);
}}
>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-4 p-6">
<Typography variant="main-title" id="home-settings" />
<HomeLayoutSettings variant="modal" />
<div className="flex justify-end">
@@ -7,7 +7,7 @@ import {
useMemo,
} from 'react';
import { useAtomValue } from 'jotai';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import {
BodyInteractions,
BodyInteractionsProps,
@@ -49,10 +49,10 @@ const LEFT_GROUPS = (side: BodySide): BodyPart[][] => [
];
const RIGHT_GROUPS = (side: BodySide): BodyPart[][] => [
[BodyPart.UPPER_CHEST, BodyPart.CHEST],
[BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST],
[side.shoulder, side.upperArm],
[side.lowerArm, side.hand],
[BodyPart.WAIST],
[BodyPart.UPPER_WAIST, BodyPart.LOWER_WAIST],
[side.upperLeg, side.lowerLeg, side.foot],
];
@@ -121,13 +121,23 @@ type AssignmentRenderState = {
};
const defaultCard =
(onRoleSelected: (role: BodyPart) => void): PartCardRenderer =>
(
onRoleSelected: (role: BodyPart) => void,
activeParts: BodyPart[] = []
): PartCardRenderer =>
(props) => (
<AssignmentPartCard {...props} onClick={() => onRoleSelected(props.role)} />
<AssignmentPartCard
{...props}
pressed={activeParts.includes(props.role)}
onClick={() => onRoleSelected(props.role)}
/>
);
const defaultGroup =
(onRoleSelected: (role: BodyPart) => void): ExtremityGroupRenderer =>
(
onRoleSelected: (role: BodyPart) => void,
activeParts: BodyPart[] = []
): ExtremityGroupRenderer =>
({ id, labelId, direction, rows, edge, flow }) => (
<ExtremityGroupCard
key={id}
@@ -137,7 +147,7 @@ const defaultGroup =
direction={direction}
rows={rows}
renderRow={(props) =>
defaultCard(onRoleSelected)({ ...props, compact: true })
defaultCard(onRoleSelected, activeParts)({ ...props, compact: true })
}
/>
);
@@ -194,7 +204,8 @@ function BodyAssignmentView({
state;
const left = +!mirror;
const right = +mirror;
const card = renderCard ?? defaultCard(onRoleSelected);
const card =
renderCard ?? defaultCard(onRoleSelected, interactions.activeParts);
const sideNames = useMemo<BodySideNames>(
() => ({
@@ -317,7 +328,8 @@ function ExtremityAssignmentView({
[trackerByPart, rolesWithErrors]
);
const group = renderGroup ?? defaultGroup(onRoleSelected);
const group =
renderGroup ?? defaultGroup(onRoleSelected, interactions.activeParts);
const digit = useCallback(
(name: string, { direction, edge }: ExtremitySlot, flow: DigitFlow) => {
@@ -1,4 +1,4 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { ExtremityDescriptor } from '@/utils/extremities';
import {
Digit,
@@ -1,4 +1,4 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { ExtremityDescriptor } from '@/utils/extremities';
import {
Digit,
@@ -1,7 +1,7 @@
import { Control, Controller, useForm } from 'react-hook-form';
import { Clickable } from '@/components/commons/Clickable';
import { BodyPart } from '@/utils/body-part';
import {
BodyPart,
ChangeSkeletonProportionsRequestT,
ResetType,
RpcMessage,
@@ -69,7 +69,7 @@ function ActionButton({
onClick={onClick}
disabled={disabled}
className={classNames(
'flex flex-col rounded-md p-2 justify-between gap-1 items-center text-standard fill-background-10',
'flex flex-col rounded-md p-2 justify-between gap-1 items-center text-standard fill-background-10 text-center',
disabled
? 'cursor-not-allowed opacity-30'
: 'hover:bg-background-50 cursor-pointer',
@@ -318,7 +318,7 @@ function ButtonsControl({ control }: { control: ManualProportionControls }) {
);
};
const beneathFloor = useMemo(() => {
const head = bones.find((bone) => bone.bodyPart === BodyPart.HEAD);
const head = bones.get(BodyPart.HEAD);
return !(head?.headPosition && head.headPosition.y >= MIN_HEIGHT);
}, [bones]);
@@ -1,5 +1,5 @@
import { ReactNode } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { Localized } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { useMountingSelection } from '@/hooks/tracker-mounting';
@@ -1,5 +1,6 @@
import classNames from 'classnames';
import { BodyPart, QuatT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { QuatT } from 'solarxr-protocol';
import { Typography } from '@/components/commons/Typography';
import { ArrowUpIcon } from '@/components/commons/icon/ArrowIcons';
import {
@@ -48,6 +49,7 @@ export function MountingPartCard({
type="button"
id={BodyPart[role]}
data-connector={connector ? undefined : 'off'}
aria-haspopup="dialog"
onClick={() => selectPart(role)}
style={velocityGlowStyle(velocity)}
className={classNames(
@@ -1,12 +1,14 @@
import classNames from 'classnames';
import { KeyboardEvent, useEffect, useState } from 'react';
import { Button } from '@/components/commons/Button';
import { BaseModal } from '@/components/commons/BaseModal';
import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
import { FootIcon } from '@/components/commons/icon/FootIcon';
import { rotationToQuatMap, similarQuaternions } from '@/maths/quaternion';
import { Quaternion } from 'three';
import { SlimeUpIcon } from '@/components/commons/icon/SlimeUpIcon';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { useLocaleConfig } from '@/i18n/config';
import { FingersIcon } from '@/components/commons/icon/FingersIcon';
import {
@@ -14,7 +16,8 @@ import {
renderFootRight,
} from '@/components/commons/BodyPartIcon';
import { FINGER_BODY_PARTS, TOE_BODY_PARTS } from '@/hooks/body-parts';
import ReactModal from 'react-modal';
import { a11yClick, stepKeys } from '@/utils/a11y';
import { useNavAim } from '@/hooks/controller-nav';
const FINGERS = new Set(FINGER_BODY_PARTS);
const LEFT_TOES = new Set(
@@ -24,6 +27,113 @@ const RIGHT_TOES = new Set(
TOE_BODY_PARTS.filter((part) => BodyPart[part].startsWith('RIGHT_'))
);
type Wedge = {
id: string;
direction: Quaternion;
d: string;
angle: number;
noText: boolean;
trackerTransform: string;
trackerWidth: number;
};
const WEDGES: Wedge[] = [
{
id: 'tracker-rotation-left',
direction: rotationToQuatMap.LEFT,
d: 'M0 0-89 44A99 99 0 0 1-89-44Z',
angle: 270,
noText: false,
trackerTransform: 'translate(75, 0) scale(-1, 1)',
trackerWidth: 10,
},
{
id: 'tracker-rotation-front_left',
direction: rotationToQuatMap.FRONT_LEFT,
d: 'M0 0-89-44A99 99 0 0 1-44-89Z',
angle: 315,
noText: true,
trackerTransform: 'translate(-2, 175) rotate(-135)',
trackerWidth: 7,
},
{
id: 'tracker-rotation-front',
direction: rotationToQuatMap.FRONT,
d: 'M0 0-44-89A99 99 0 0 1 44-89Z',
angle: 0,
noText: false,
trackerTransform: 'translate(0, 75) rotate(-90)',
trackerWidth: 10,
},
{
id: 'tracker-rotation-front_right',
direction: rotationToQuatMap.FRONT_RIGHT,
d: 'M0 0 44-89A99 99 0 0 1 89-44Z',
angle: 45,
noText: true,
trackerTransform: 'translate(73, 0) rotate(-45)',
trackerWidth: 7,
},
{
id: 'tracker-rotation-right',
direction: rotationToQuatMap.RIGHT,
d: 'M0 0 89-44A99 99 0 0 1 89 44Z',
angle: 90,
noText: false,
trackerTransform: 'translate(175,0)',
trackerWidth: 10,
},
{
id: 'tracker-rotation-back_right',
direction: rotationToQuatMap.BACK_RIGHT,
d: 'M0 0 89 44A99 99 0 0 1 44 89Z',
angle: 135,
noText: true,
trackerTransform: 'translate(252, 75) rotate(45)',
trackerWidth: 7,
},
{
id: 'tracker-rotation-back',
direction: rotationToQuatMap.BACK,
d: 'M0 0 44 89A99 99 0 0 1-44 89Z',
angle: 180,
noText: false,
trackerTransform: 'translate(250, 175) rotate(90)',
trackerWidth: 10,
},
{
id: 'tracker-rotation-back_left',
direction: rotationToQuatMap.BACK_LEFT,
d: 'M0 0-44 89A99 99 0 0 1-89 44Z',
angle: 225,
noText: true,
trackerTransform: 'translate(177, 250) rotate(135)',
trackerWidth: 7,
},
];
const FRONT_INDEX = WEDGES.findIndex((w) => w.angle === 0);
const wedgeOptionId = (i: number) => `mounting-wedge-${i}`;
function angleGap(a: number, b: number): number {
const diff = Math.abs(a - b) % 360;
return diff > 180 ? 360 - diff : diff;
}
function nearestWedge(bearing: number): number {
let best = 0;
let bestGap = Infinity;
WEDGES.forEach((w, i) => {
const gap = angleGap(bearing, w.angle);
if (gap < bestGap) {
bestGap = gap;
best = i;
}
});
return best;
}
export function MountingBodyPartIcon({
bodyPart = BodyPart.NONE,
width = 24,
@@ -41,36 +151,36 @@ export function MountingBodyPartIcon({
}
function PieSliceOfFeet({
direction,
wedge,
optionId,
onDirectionSelected,
currRotation,
id,
d,
noText = false,
trackerTransform,
trackerWidth = 10,
selected,
focused,
}: {
direction: Quaternion;
wedge: Wedge;
optionId: string;
onDirectionSelected: (direction: Quaternion) => void;
currRotation?: Quaternion;
id: string;
d: string;
noText?: boolean;
trackerTransform: string;
trackerWidth?: number;
selected: boolean;
focused: boolean;
}) {
const { l10n } = useLocalization();
const { id, d, direction, noText, trackerTransform, trackerWidth } = wedge;
return (
<g
id={optionId}
role="option"
aria-selected={selected}
aria-label={l10n.getString(id)}
onClick={() => onDirectionSelected(direction)}
className={classNames('group fill-background-10 stroke-background-10')}
>
<path
d={d}
className={classNames(
'fill-background-40 opacity-50 stroke-background-90',
'group-hover:fill-background-30 group-active:fill-background-20'
'opacity-50 stroke-background-90 group-hover:fill-background-30',
'group-active:fill-background-20',
focused ? 'fill-background-30' : 'fill-background-40'
)}
transform="translate(125 125)"
id={id}
@@ -84,9 +194,11 @@ function PieSliceOfFeet({
transform={trackerTransform}
className={classNames(
'stroke-none group-hover:fill-accent-background-20',
currRotation && similarQuaternions(currRotation, direction)
? 'fill-background-90'
: 'fill-none'
focused
? 'fill-accent-background-20'
: selected
? 'fill-background-90'
: 'fill-none'
)}
>
<SlimeUpIcon width={trackerWidth} />
@@ -109,12 +221,39 @@ export function MountingSelectionMenu({
currRotation?: Quaternion;
}) {
const { l10n } = useLocalization();
const [cursor, setCursor] = useState(FRONT_INDEX);
const appliedIndex = currRotation
? WEDGES.findIndex((w) => similarQuaternions(currRotation, w.direction))
: -1;
useEffect(() => {
if (isOpen) setCursor(appliedIndex >= 0 ? appliedIndex : FRONT_INDEX);
}, [isOpen]);
useNavAim(isOpen, (bearing) => setCursor(nearestWedge(bearing)));
const step = stepKeys({
value: cursor,
min: 0,
max: WEDGES.length - 1,
step: (v, add) => (v + (add ? 1 : WEDGES.length - 1)) % WEDGES.length,
bigStep: (v, add) => (v + (add ? 2 : WEDGES.length - 2)) % WEDGES.length,
onChange: setCursor,
});
const onKeyDown = (e: KeyboardEvent) => {
if (a11yClick(e)) {
e.preventDefault();
onDirectionSelected(WEDGES[cursor].direction);
return;
}
step(e);
};
return (
<ReactModal
<BaseModal
isOpen={isOpen}
shouldCloseOnOverlayClick
shouldCloseOnEsc
onRequestClose={onClose}
overlayClassName={classNames(
'fixed top-0 right-0 left-0 bottom-0 flex flex-col items-center w-full h-full bg-background-90 bg-opacity-90 z-50'
@@ -128,97 +267,48 @@ export function MountingSelectionMenu({
{l10n.getString('mounting_selection_menu')}
</Typography>
<div className="flex w-full flex-col flex-grow items-center gap-3 justify-center">
<svg width="400" viewBox="0 0 250 250" className="fill-background-40">
<g transform="translate(80, 0)" className="fill-background-10">
<MountingBodyPartIcon width={100} bodyPart={bodyPart} />
</g>
<g strokeWidth="4" className="stroke-background-90">
<PieSliceOfFeet
d="M0 0-89 44A99 99 0 0 1-89-44Z"
direction={rotationToQuatMap.LEFT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-left"
trackerTransform="translate(75, 0) scale(-1, 1)"
/>
<PieSliceOfFeet
d="M0 0-89-44A99 99 0 0 1-44-89Z"
direction={rotationToQuatMap.FRONT_LEFT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation_left_front"
noText={true}
trackerTransform="translate(-2, 175) rotate(-135)"
trackerWidth={7}
/>
<PieSliceOfFeet
d="M0 0-44-89A99 99 0 0 1 44-89Z"
direction={rotationToQuatMap.FRONT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-front"
trackerTransform="translate(0, 75) rotate(-90)"
/>
<PieSliceOfFeet
d="M0 0 44-89A99 99 0 0 1 89-44Z"
direction={rotationToQuatMap.FRONT_RIGHT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-front_right"
noText={true}
trackerTransform="translate(73, 0) rotate(-45)"
trackerWidth={7}
/>
<PieSliceOfFeet
d="M0 0 89-44A99 99 0 0 1 89 44Z"
direction={rotationToQuatMap.RIGHT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-right"
trackerTransform="translate(175,0)"
/>
<PieSliceOfFeet
d="M0 0 89 44A99 99 0 0 1 44 89Z"
direction={rotationToQuatMap.BACK_RIGHT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-back_right"
noText={true}
trackerTransform="translate(252, 75) rotate(45)"
trackerWidth={7}
/>
<PieSliceOfFeet
d="M0 0 44 89A99 99 0 0 1-44 89Z"
direction={rotationToQuatMap.BACK}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-back"
trackerTransform="translate(250, 175) rotate(90)"
/>
<PieSliceOfFeet
d="M0 0-44 89A99 99 0 0 1-89 44Z"
direction={rotationToQuatMap.BACK_LEFT}
onDirectionSelected={onDirectionSelected}
currRotation={currRotation}
id="tracker-rotation-back_left"
noText={true}
trackerTransform="translate(177, 250) rotate(135)"
trackerWidth={7}
/>
</g>
</svg>
<div
role="listbox"
tabIndex={-1}
data-nav-entry
data-nav-arrows
data-nav-aim
aria-label={l10n.getString('mounting_selection_menu')}
aria-activedescendant={wedgeOptionId(cursor)}
onKeyDown={onKeyDown}
className="rounded-lg outline-none"
>
<svg
width="400"
viewBox="0 0 250 250"
className="fill-background-40"
>
<g transform="translate(80, 0)" className="fill-background-10">
<MountingBodyPartIcon width={100} bodyPart={bodyPart} />
</g>
<g strokeWidth="4" className="stroke-background-90">
{WEDGES.map((wedge, i) => (
<PieSliceOfFeet
key={wedge.id}
wedge={wedge}
optionId={wedgeOptionId(i)}
onDirectionSelected={onDirectionSelected}
selected={i === appliedIndex}
focused={i === cursor}
/>
))}
</g>
</svg>
</div>
</div>
</div>
<div
className="flex w-full justify-between absolute bottom-0 left-0 p-10 z-0"
onClick={onClose}
>
<div className="flex w-full justify-between absolute bottom-0 left-0 p-10 z-0">
<div className="flex flex-col justify-end pointer-events-auto">
<Button variant="primary" onClick={onClose}>
{l10n.getString('mounting_selection_menu-close')}
</Button>
</div>
</div>
</ReactModal>
</BaseModal>
);
}
@@ -2,7 +2,7 @@ import classNames from 'classnames';
import { useLocalization } from '@fluent/react';
import { Clickable } from '@/components/commons/Clickable';
import { HTMLAttributes, ReactNode, useCallback, useMemo } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { MirrorLegend } from '@/components/onboarding/BodyAssignment';
import {
BodyPartAssignment,
@@ -364,7 +364,7 @@ function DragBodyPartCard({
className={classNames(
'flex flex-col control rounded-md relative touch-none select-none',
'transition-colors duration-150 ease-linear',
compact ? 'gap-0 w-full px-1.5 py-0.5' : 'gap-1 w-40 px-2 py-1',
'gap-0 w-full px-1.5 py-2',
td ? 'cursor-grab active:cursor-grabbing' : 'cursor-pointer',
isDragging && 'opacity-40',
direction === 'left' ? 'items-start' : 'items-end',
@@ -384,21 +384,19 @@ function DragBodyPartCard({
number={number}
labelId={labelId}
/>
<div className={compact ? 'min-h-6 w-full' : 'min-h-10'}>
{td ? (
<AssignedTrackerLabel tracker={td} compact={compact} />
) : (
<div
className={classNames(
'flex items-center',
compact ? 'h-6' : 'h-8',
direction === 'right' && 'justify-end'
)}
>
<Typography color="text-background-30" id="body_part-NONE" />
</div>
)}
</div>
{td ? (
<AssignedTrackerLabel tracker={td} compact={compact} />
) : (
<div
className={classNames(
'flex items-center',
compact ? 'h-6' : 'h-8',
direction === 'right' && 'justify-end'
)}
>
<Typography color="text-background-30" id="body_part-NONE" />
</div>
)}
</div>
);
}
@@ -2,7 +2,7 @@ import type { FluentVariable } from '@fluent/bundle';
import { useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { CSSProperties, ReactNode, useMemo } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { Button } from '@/components/commons/Button';
import { ProgressBar } from '@/components/commons/ProgressBar';
import { Typography } from '@/components/commons/Typography';
@@ -19,9 +19,12 @@ import {
velocityGlowStyle,
} from '@/hooks/tracker';
import {
boneRegistryAtom,
FlatDeviceTracker,
groupTrackersByConnection,
unassignedTrackersAtom,
} from '@/store/app-store';
import { useAtomValue } from 'jotai';
import { BodyAssignmentPanel } from './BodyAssignmentPanel';
import {
AssignmentEmptyState,
@@ -155,17 +158,12 @@ export function MobileTrackerAssign() {
selectTracker,
} = assignment;
const boneRegistry = useAtomValue(boneRegistryAtom);
const groups = useMemo(
() => groupTrackersByConnection(flatTrackers, dongles),
[flatTrackers, dongles]
);
const unassignedTrackers = useMemo(
() =>
flatTrackers.filter(
({ tracker }) => tracker.info?.bodyPart === BodyPart.NONE
),
[flatTrackers]
() => groupTrackersByConnection(flatTrackers, dongles, boneRegistry),
[flatTrackers, dongles, boneRegistry]
);
const unassignedTrackers = useAtomValue(unassignedTrackersAtom);
const unassignedTrackerData = useMemo(
() => unassignedTrackers.map(({ tracker }) => tracker),
[unassignedTrackers]
@@ -1,6 +1,6 @@
import classNames from 'classnames';
import { createPortal } from 'react-dom';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BaseModal } from '@/components/commons/BaseModal';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
@@ -2,7 +2,8 @@ import classNames from 'classnames';
import { Clickable } from '@/components/commons/Clickable';
import { useLocalization } from '@fluent/react';
import { CSSProperties, ReactNode, useMemo } from 'react';
import { BodyPart, DeviceDataT, TrackerDataT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { DeviceDataT, TrackerDataT } from 'solarxr-protocol';
import { BodyPartIcon } from '@/components/commons/BodyPartIcon';
import { Button } from '@/components/commons/Button';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
@@ -21,6 +22,8 @@ import {
useIsTrackerBeingDragged,
} from '@/hooks/tracker-drag';
import {
bodyPartOfBone,
boneRegistryAtom,
FlatDeviceTracker,
groupTrackersByConnection,
groupTrackersByDevice,
@@ -28,6 +31,7 @@ import {
} from '@/store/app-store';
import { ShowAllPartsToggle } from '@/components/onboarding/BodyAssignment';
import { useAssignment } from '@/hooks/tracker-assignment';
import { useAtomValue } from 'jotai';
export function TrackerAssignmentList() {
const { state } = useOnboarding();
@@ -42,9 +46,10 @@ export function TrackerAssignmentList() {
pendingTrackerId,
} = useAssignment();
const assignedCount = assignedTrackers.length;
const boneRegistry = useAtomValue(boneRegistryAtom);
const groups = useMemo(
() => groupTrackersByConnection(trackers, dongles),
[trackers, dongles]
() => groupTrackersByConnection(trackers, dongles, boneRegistry),
[trackers, dongles, boneRegistry]
);
const variant = state.alonePage ? 'primary' : 'tertiary';
@@ -295,6 +300,7 @@ export function SimpleTrackerRow({
}) {
const { useVelocity } = useTracker(tracker);
const velocity = useVelocity();
const boneRegistry = useAtomValue(boneRegistryAtom);
const row = (
<div
@@ -309,7 +315,7 @@ export function SimpleTrackerRow({
>
<div className="fill-background-10">
<BodyPartIcon
bodyPart={tracker.info?.bodyPart}
bodyPart={bodyPartOfBone(boneRegistry, tracker.info?.boneId)}
device={device}
trackerId={tracker.trackerId}
width={32}
@@ -1,6 +1,6 @@
import classNames from 'classnames';
import { Fragment, ReactNode } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BodyPartIcon } from '@/components/commons/BodyPartIcon';
import { Tooltip } from '@/components/commons/Tooltip';
import { Typography } from '@/components/commons/Typography';
@@ -37,7 +37,8 @@ export function AssignmentPartCard({
compact = false,
number,
connector = true,
}: PartCardProps & { onClick?: () => void }) {
pressed,
}: PartCardProps & { onClick?: () => void; pressed?: boolean }) {
const velocity = useVelocity(td?.tracker);
return (
@@ -45,6 +46,7 @@ export function AssignmentPartCard({
type="button"
id={BodyPart[role]}
data-connector={connector ? undefined : 'off'}
aria-pressed={pressed}
onClick={onClick}
style={velocityGlowStyle(velocity)}
className={classNames(
@@ -52,7 +54,8 @@ export function AssignmentPartCard({
compact
? 'gap-0 w-full px-1.5 py-0.5'
: 'gap-1 w-[88px] smol:w-[120px] sm:w-[150px] px-2 py-1',
direction === 'left' ? 'text-left' : 'text-right'
direction === 'left' ? 'text-left' : 'text-right',
pressed && 'bg-accent-background-30/40'
)}
>
<PartCardWarning error={roleError} direction={direction} />
@@ -38,7 +38,7 @@ export function SettingSelectorMobile() {
value: { url: '/settings/driver', scrollTo: 'driver' },
},
{
label: l10n.getString('settings-sidebar-osc_trackers'),
label: l10n.getString('settings-sidebar-vrchat_osc'),
value: { url: '/settings/osc/vrchat', scrollTo: 'vrchat' },
},
{
@@ -86,7 +86,7 @@ export function SettingsSidebar() {
<SettingsLink
to="/settings/osc/vrchat"
scrollTo="vrchat"
id="settings-sidebar-osc_trackers"
id="settings-sidebar-vrchat_osc"
/>
<SettingsLink
to="/settings/osc/vmc"
@@ -2,8 +2,8 @@ import { useLocalization } from '@fluent/react';
import { Clickable } from '@/components/commons/Clickable';
import classNames from 'classnames';
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { BodyPart } from '@/utils/body-part';
import {
BodyPart,
BoneRouteT,
BoneRoutingSettingsRequestT,
BoneRoutingSettingsResponseT,
@@ -23,6 +23,13 @@ import {
} from '@/hooks/body-parts';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useLocaleConfig } from '@/i18n/config';
import { useAtomValue } from 'jotai';
import {
bodyPartOfBone,
boneIdOfBodyPart,
boneIdRegistryAtom,
boneRegistryAtom,
} from '@/store/app-store';
import {
CHECKBOX_CLASSES,
CheckboxInternal,
@@ -121,20 +128,31 @@ const OUTPUT_CELL_CLASSES =
type RouteMap = Map<BodyPart, Set<RoutingOutput>>;
function toRouteMap(routes: BoneRouteT[]): RouteMap {
function toRouteMap(
routes: BoneRouteT[],
boneRegistry: Map<number, BodyPart>
): RouteMap {
return new Map(
routes.map((route) => [route.bone, new Set(route.outputs ?? [])])
routes.map((route) => [
bodyPartOfBone(boneRegistry, route.boneId),
new Set(route.outputs ?? []),
])
);
}
function toBoneRoutes(routes: RouteMap): BoneRouteT[] {
function toBoneRoutes(
routes: RouteMap,
boneIdRegistry: Map<BodyPart, number>
): BoneRouteT[] {
return Array.from(routes.entries())
.filter(([, outputs]) => outputs.size > 0)
.map(([bone, outputs]) => {
.flatMap(([bone, outputs]) => {
const boneId = boneIdOfBodyPart(boneIdRegistry, bone);
if (boneId == null) return [];
const route = new BoneRouteT();
route.bone = bone;
route.boneId = boneId;
route.outputs = Array.from(outputs);
return route;
return [route];
});
}
@@ -317,6 +335,8 @@ export function BoneRoutingSettings() {
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const boneRegistry = useAtomValue(boneRegistryAtom);
const boneIdRegistry = useAtomValue(boneIdRegistryAtom);
const [settings, setSettings] = useState(new BoneRoutingSettingsResponseT());
const [automatic, setAutomatic] = useState(true);
@@ -334,17 +354,29 @@ export function BoneRoutingSettings() {
const accepts = useMemo(
() =>
new Map(
outputs.map((status) => [status.output, new Set(status.accepts ?? [])])
outputs.map((status) => [
status.output,
new Set(
(status.accepts ?? []).map((id) => bodyPartOfBone(boneRegistry, id))
),
])
),
[outputs]
[outputs, boneRegistry]
);
const requires = useMemo(
() =>
new Map(
outputs.map((status) => [status.output, new Set(status.requires ?? [])])
outputs.map((status) => [
status.output,
new Set(
(status.requires ?? []).map((id) =>
bodyPartOfBone(boneRegistry, id)
)
),
])
),
[outputs]
[outputs, boneRegistry]
);
const overridable = useMemo(
@@ -352,10 +384,14 @@ export function BoneRoutingSettings() {
new Map(
outputs.map((status) => [
status.output,
new Set(status.overridable ?? []),
new Set(
(status.overridable ?? []).map((id) =>
bodyPartOfBone(boneRegistry, id)
)
),
])
),
[outputs]
[outputs, boneRegistry]
);
const conflicts = useMemo(
@@ -435,15 +471,15 @@ export function BoneRoutingSettings() {
useEffect(() => {
setAutomatic(settings.automatic ?? true);
setRoutes(toRouteMap(settings.routes ?? []));
setRoutes(toRouteMap(settings.routes ?? [], boneRegistry));
const handsAlreadyOnDriver = (settings.routes ?? []).some(
(route) =>
HAND_BODY_PARTS.includes(route.bone) &&
HAND_BODY_PARTS.includes(bodyPartOfBone(boneRegistry, route.boneId)) &&
(route.outputs ?? []).includes(RoutingOutput.DRIVER)
);
if (handsAlreadyOnDriver) setHandsWarningAccepted(true);
}, [settings]);
}, [settings, boneRegistry]);
useRPCPacket(
RpcMessage.BoneRoutingSettingsResponse,
@@ -453,7 +489,7 @@ export function BoneRoutingSettings() {
const submit = (nextAutomatic: boolean, nextRoutes: RouteMap) => {
const req = new ChangeBoneRoutingSettingsRequestT();
req.automatic = nextAutomatic;
req.routes = toBoneRoutes(nextRoutes);
req.routes = toBoneRoutes(nextRoutes, boneIdRegistry);
sendRPCPacket(RpcMessage.ChangeBoneRoutingSettingsRequest, req);
};
@@ -1,4 +1,4 @@
import { CheckBox } from '@/components/commons/Checkbox';
import { CheckBox, CheckboxInternal } from '@/components/commons/Checkbox';
import { Clickable } from '@/components/commons/Clickable';
import { CheckIcon } from '@/components/commons/icon/CheckIcon';
import { HomeIcon } from '@/components/commons/icon/HomeIcon';
@@ -7,7 +7,15 @@ import {
SettingsPageLayout,
SettingsPagePaneLayout,
} from '@/components/settings/SettingsPageLayout';
import { Config, useConfig } from '@/hooks/config';
import {
Config,
defaultTrackerDisplay,
defaultTrackersTableColumns,
TrackerDisplayConfig,
trackersTableColumnOrder,
TrackersTableColumnsConfig,
useConfig,
} from '@/hooks/config';
import {
trackingchecklistIdtoLabel,
useTrackingChecklist,
@@ -133,6 +141,110 @@ export function LayoutSelector({
);
}
const trackersTableColumnLabel: Record<
keyof TrackersTableColumnsConfig,
string
> = {
type: 'tracker-table-column-type',
battery: 'tracker-table-column-battery',
ping: 'tracker-table-column-ping',
tps: 'tracker-table-column-tps',
rotation: 'tracker-table-column-rotation',
temperature: 'tracker-table-column-temperature',
linearAcceleration: 'tracker-table-column-linear-acceleration',
position: 'tracker-table-column-position',
stayAligned: 'tracker-table-column-stay_aligned',
url: 'tracker-table-column-url',
};
export function TrackersTableColumnsSettings({
variant,
}: {
variant: 'settings' | 'modal';
}) {
const { l10n } = useLocalization();
const { config, setConfig } = useConfig();
const columns = config?.trackersTableColumns ?? defaultTrackersTableColumns;
const toggleColumn = (key: keyof TrackersTableColumnsConfig) => {
setConfig({
trackersTableColumns: { ...columns, [key]: !columns[key] },
});
};
return (
<div className="flex flex-col gap-2">
<div className="flex flex-col pt-4 pb-2">
<Typography bold id="settings-home-table_columns" />
<Typography color="secondary" id="settings-home-table_columns-desc" />
</div>
<div className="grid sm:grid-cols-2 md:grid-cols-3 gap-2">
{trackersTableColumnOrder.map((key) => (
<CheckboxInternal
key={key}
variant="toggle"
outlined
color={variant === 'settings' ? 'primary' : 'secondary'}
name={key}
checked={columns[key]}
onChange={() => toggleColumn(key)}
label={l10n.getString(trackersTableColumnLabel[key])}
/>
))}
</div>
</div>
);
}
const trackerDisplayToggleOrder: (keyof TrackerDisplayConfig)[] = [
'showBatteryVoltage',
'showNumericSignal',
];
const trackerDisplayToggleLabel: Record<keyof TrackerDisplayConfig, string> = {
showBatteryVoltage: 'settings-home-tracker_display-battery_voltage',
showNumericSignal: 'settings-home-tracker_display-numeric_signal',
};
export function TrackerDisplaySettings({
variant,
}: {
variant: 'settings' | 'modal';
}) {
const { l10n } = useLocalization();
const { config, setConfig } = useConfig();
const trackerDisplay = config?.trackerDisplay ?? defaultTrackerDisplay;
const toggle = (key: keyof TrackerDisplayConfig) => {
setConfig({
trackerDisplay: { ...trackerDisplay, [key]: !trackerDisplay[key] },
});
};
return (
<div className="flex flex-col gap-2">
<div className="flex flex-col pt-4 pb-2">
<Typography bold id="settings-home-tracker_display" />
<Typography color="secondary" id="settings-home-tracker_display-desc" />
</div>
<div className="grid sm:grid-cols-2 gap-2">
{trackerDisplayToggleOrder.map((key) => (
<CheckboxInternal
key={key}
variant="toggle"
outlined
color={variant === 'settings' ? 'primary' : 'secondary'}
name={key}
checked={trackerDisplay[key]}
onChange={() => toggle(key)}
label={l10n.getString(trackerDisplayToggleLabel[key])}
/>
))}
</div>
</div>
);
}
export function HomeLayoutSettings({
variant,
}: {
@@ -179,6 +291,10 @@ export function HomeLayoutSettings({
</div>
</LayoutSelector>
</div>
<TrackerDisplaySettings variant={variant} />
{config?.homeLayout === 'table' && (
<TrackersTableColumnsSettings variant={variant} />
)}
</div>
);
}
@@ -37,7 +37,6 @@ interface InterfaceSettingsForm {
controllerNav: boolean;
};
notifications: {
watchNewDevices: boolean;
feedbackSound: boolean;
feedbackSoundVolume: number;
connectedTrackersWarning: boolean;
@@ -60,8 +59,6 @@ export function InterfaceSettings() {
fonts: config?.fonts.join(',') ?? defaultConfig.fonts.join(','),
},
notifications: {
watchNewDevices:
config?.watchNewDevices ?? defaultConfig.watchNewDevices,
feedbackSound: config?.feedbackSound ?? defaultConfig.feedbackSound,
feedbackSoundVolume:
config?.feedbackSoundVolume ?? defaultConfig.feedbackSoundVolume,
@@ -91,14 +88,9 @@ export function InterfaceSettings() {
fastDataFeed:
config?.devSettings?.fastDataFeed ??
defaultConfig.devSettings.fastDataFeed,
sortByName:
config?.devSettings?.sortByName ??
defaultConfig.devSettings.sortByName,
rawSlimeRotation:
config?.devSettings?.rawSlimeRotation ??
defaultConfig.devSettings.rawSlimeRotation,
moreInfo:
config?.devSettings?.moreInfo ?? defaultConfig.devSettings.moreInfo,
},
},
});
@@ -134,14 +126,13 @@ export function InterfaceSettings() {
handleResetSounds(values.notifications.feedbackSoundVolume, {
resetType: ResetType.FULL,
status: ResetStatus.FINISHED,
bodyParts: [],
boneIds: [],
progress: 0,
duration: 0,
});
}
setConfig({
watchNewDevices: values.notifications.watchNewDevices,
feedbackSound: values.notifications.feedbackSound,
feedbackSoundVolume: values.notifications.feedbackSoundVolume,
connectedTrackersWarning: values.notifications.connectedTrackersWarning,
@@ -176,9 +167,7 @@ export function InterfaceSettings() {
highContrast: 'high_contrast',
preciseRotation: 'precise_rotation',
fastDataFeed: 'fast_data_feed',
sortByName: 'sort_by_name',
rawSlimeRotation: 'raw_slime_rotation',
moreInfo: 'more_info',
};
return (
@@ -201,31 +190,6 @@ export function InterfaceSettings() {
{l10n.getString('settings-interface-notifications')}
</Typography>
<div className="pt-2">
<Typography variant="section-title">
{l10n.getString('settings-general-interface-serial_detection')}
</Typography>
</div>
<div className="flex flex-col pt-1 pb-2">
<Typography>
{l10n.getString(
'settings-general-interface-serial_detection-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-2 pb-4">
<CheckBox
variant="toggle"
control={control}
outlined
name="notifications.watchNewDevices"
label={l10n.getString(
'settings-general-interface-serial_detection-label'
)}
/>
</div>
<Typography variant="section-title">
{l10n.getString('settings-general-interface-feedback_sound')}
</Typography>
@@ -9,10 +9,13 @@ import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
import { Button } from '@/components/commons/Button';
import { KeybindsRow } from '@/components/commons/KeybindsRow';
import { useElectron } from '@/hooks/electron';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { ReactNode, useEffect, useMemo, useRef, useState } from 'react';
import {
ChangeKeybindRequestT,
KeybindActivatedResponseT,
KeybindId,
KeybindRequestT,
KeybindResponseT,
KeybindSupport,
@@ -53,6 +56,7 @@ function areBindingsEqual(a?: string[], b?: string[]): boolean {
export function KeybindSettings() {
const { l10n } = useLocalization();
const electron = useElectron();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [isOpen, setIsOpen] = useState<boolean>(false);
const [defaultKeybindsState, setDefaultKeybindsState] = useState<KeybindForm>(
@@ -86,26 +90,30 @@ export function KeybindSettings() {
// Snapshot of the edited binding, restored if the modal is cancelled
const bindingSnapshot = useRef<string[] | null>(null);
const [collisionError, setCollisionError] = useState<string | null>(null);
const { fields } = useFieldArray({
control,
name: 'keybinds',
});
const submitKeybind = (kb: KeybindForm['keybinds'][number]) => {
const changeKeybindRequest = new ChangeKeybindRequestT();
const keybind = new KeybindT();
keybind.keybindId = kb.keybindId;
keybind.keybindValue = kb.binding.join('+');
keybind.keybindDelay = kb.delay;
changeKeybindRequest.keybind = keybind;
sendRPCPacket(RpcMessage.ChangeKeybindRequest, changeKeybindRequest);
};
const onSubmit = (data?: KeybindForm) => {
const value = data ?? getValues();
value.keybinds.forEach(submitKeybind);
};
value.keybinds.forEach((kb) => {
const currentBindingStr = kb.binding.join('+');
const changeKeybindRequest = new ChangeKeybindRequestT();
const keybind = new KeybindT();
keybind.keybindId = kb.keybindId;
keybind.keybindValue = currentBindingStr;
keybind.keybindDelay = kb.delay;
changeKeybindRequest.keybind = keybind;
sendRPCPacket(RpcMessage.ChangeKeybindRequest, changeKeybindRequest);
});
const onSubmitIndex = (index: number) => {
submitKeybind(getValues(`keybinds.${index}`));
setIsOpen(false);
};
@@ -125,7 +133,7 @@ export function KeybindSettings() {
if (defaultKb) {
setValue(`keybinds.${index}.binding`, defaultKb.binding);
setValue(`keybinds.${index}.delay`, defaultKb.delay);
handleSubmit(onSubmit)();
submitKeybind(getValues(`keybinds.${index}`));
}
};
@@ -155,15 +163,22 @@ export function KeybindSettings() {
}
);
const isFirstRender = useRef(true);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
const req = new SetKeybindRecordingRequestT();
req.recording = isOpen;
sendRPCPacket(RpcMessage.SetKeybindRecordingRequest, req);
if (electron.isElectron) electron.api.setKeybindRecording(isOpen);
}, [isOpen]);
const handleOpenRecorderModal = (index: number) => {
currentIndex.current = index;
bindingSnapshot.current = getValues(`keybinds.${index}.binding`);
setCollisionError(null);
setIsOpen(true);
};
@@ -175,11 +190,33 @@ export function KeybindSettings() {
);
}
setIsOpen(false);
setCollisionError(null);
clearErrors('keybinds');
};
const editedIndex = currentIndex.current;
useRPCPacket(
RpcMessage.KeybindActivatedResponse,
({ keybindId }: KeybindActivatedResponseT) => {
if (!isOpen || editedIndex == null || keybindId === KeybindId.NONE)
return;
const editedId = getValues(`keybinds.${editedIndex}.keybindId`);
if (keybindId === editedId) return;
const clash = getValues('keybinds').find(
(kb) => kb.keybindId === keybindId
);
if (!clash) return;
setCollisionError(
l10n.getString('settings-keybinds-already-assigned', {
name: l10n.getString('settings-keybinds_' + clash.name),
})
);
}
);
const takenBindings =
editedIndex != null
? getValues('keybinds')
@@ -191,7 +228,7 @@ export function KeybindSettings() {
}))
: [];
const createKeybindRows = (): ReactNode => {
const createKeybindRows = (bindingEditable: boolean): ReactNode => {
return fields.map((field, index) => {
const currentKb = watch(`keybinds.${index}`);
const defaultKb = currentKb
@@ -210,9 +247,12 @@ export function KeybindSettings() {
id={field.name}
control={control}
index={index}
openKeybindRecorderModal={handleOpenRecorderModal}
openKeybindRecorderModal={
bindingEditable ? handleOpenRecorderModal : undefined
}
onResetSingle={handleResetSingle}
isModified={isModified}
bindingEditable={bindingEditable}
/>
);
});
@@ -224,8 +264,9 @@ export function KeybindSettings() {
useEffect(() => {
const subscription = watch((_, { name, type }) => {
if (type === 'change' && name?.endsWith('.delay'))
handleSubmit(onSubmit)();
if (type !== 'change' || !name?.endsWith('.delay')) return;
const match = name.match(/^keybinds\.(\d+)\.delay$/);
if (match) submitKeybind(getValues(`keybinds.${Number(match[1])}`));
});
return () => subscription.unsubscribe();
}, [watch]);
@@ -253,21 +294,22 @@ export function KeybindSettings() {
</div>
)}
{support === KeybindSupport.SYSTEM_MANAGED && (
<div className="flex flex-col gap-4 p-4 rounded-2xl bg-background-80">
<Typography id="settings-keybinds-system-managed-description" />
<div>
<Button
id="settings-keybinds-open-system-settings-button"
onClick={handleOpenSystemSettingsButton}
variant="primary"
/>
</div>
</div>
)}
{support === KeybindSupport.APP_MANAGED && (
{(support === KeybindSupport.SYSTEM_MANAGED ||
support === KeybindSupport.APP_MANAGED) && (
<FormProvider {...methods}>
{support === KeybindSupport.SYSTEM_MANAGED && (
<div className="flex flex-col gap-4 p-4 rounded-2xl bg-background-80">
<Typography id="settings-keybinds-system-managed-description" />
<div>
<Button
id="settings-keybinds-open-system-settings-button"
onClick={handleOpenSystemSettingsButton}
variant="primary"
/>
</div>
</div>
)}
<div className="rounded-2xl bg-background-80 shadow-sm my-1 overflow-hidden">
<table className="w-full text-left border-collapse block md:table">
<thead className="hidden md:table-header-group">
@@ -294,7 +336,7 @@ export function KeybindSettings() {
</tr>
</thead>
<tbody className="divide-y divide-background-60 block md:table-row-group">
{createKeybindRows()}
{createKeybindRows(support === KeybindSupport.APP_MANAGED)}
</tbody>
</table>
</div>
@@ -310,22 +352,24 @@ export function KeybindSettings() {
/>
</div>
{editedIndex != null && (
<KeybindRecorderModal
id={fields[editedIndex].name}
control={control}
name={`keybinds.${editedIndex}.binding`}
isVisisble={isOpen}
onClose={onClose}
onUnbind={() => {
setValue(`keybinds.${editedIndex}.binding`, []);
handleSubmit(onSubmit)();
}}
onSubmit={() => handleSubmit(onSubmit)()}
onReset={() => handleResetSingle(editedIndex)}
takenBindings={takenBindings}
/>
)}
{support === KeybindSupport.APP_MANAGED &&
editedIndex != null && (
<KeybindRecorderModal
id={fields[editedIndex].name}
control={control}
name={`keybinds.${editedIndex}.binding`}
isVisisble={isOpen}
onClose={onClose}
onUnbind={() => {
setValue(`keybinds.${editedIndex}.binding`, []);
onSubmitIndex(editedIndex);
}}
onSubmit={() => onSubmitIndex(editedIndex)}
onReset={() => handleResetSingle(editedIndex)}
takenBindings={takenBindings}
activatedError={collisionError}
/>
)}
</FormProvider>
)}
</div>
@@ -3,6 +3,7 @@ import { useForm } from 'react-hook-form';
import { useLocation } from 'react-router-dom';
import {
CloseSerialRequestT,
NewSerialDeviceResponseT,
OpenSerialRequestT,
RpcMessage,
SerialDevicesRequestT,
@@ -138,6 +139,16 @@ export function Serial() {
}
);
useRPCPacket(
RpcMessage.NewSerialDeviceResponse,
({ device }: NewSerialDeviceResponseT) => {
if (!device?.port) return;
setSerialDevices((old) =>
old.some((d) => d.port === device.port) ? old : [...old, device]
);
}
);
useEffect(() => {
if (isPaused) {
return;
@@ -15,7 +15,11 @@ import { HorizontalAlignIcon } from '@/components/commons/icon/HorizontalAlignIc
import { useAtomValue, atom, useSetAtom } from 'jotai';
import { selectAtom } from 'jotai/utils';
import { isEqual } from '@react-hookz/deep-equal';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import {
bodyPartOfBone,
boneRegistryAtom,
connectedIMUTrackersAtom,
} from '@/store/app-store';
import { bodypartToString } from '@/utils/formatting';
import { useLocaleConfig } from '@/i18n/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
@@ -75,6 +79,7 @@ function CopySettingsButton({ values }: { values: StayAlignedSettingsForm }) {
});
const trackers = useAtomValue(connectedIMUTrackersAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const copySettings = () => {
const config = values;
@@ -100,7 +105,7 @@ ${trackers
const info = t.tracker.info;
const stayAligned = t.tracker.stayAligned;
if (info && stayAligned) {
return `${bodypartToString(info.bodyPart)}: correction=${numberFormat.format(stayAligned.yawCorrectionInDeg)} locked=${stayAligned.locked}`;
return `${bodypartToString(bodyPartOfBone(boneRegistry, info.boneId))}: correction=${numberFormat.format(stayAligned.yawCorrectionInDeg)} locked=${stayAligned.locked}`;
}
})
.join('\n')}
@@ -1,8 +1,8 @@
import { useLocalization } from '@fluent/react';
import { useEffect } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import { BodyPart } from '@/utils/body-part';
import {
BodyPart,
ChangeTapDetectionSettingsRequestT,
RpcMessage,
TapDetectionSettingsRequestT,
@@ -18,6 +18,12 @@ import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
import { useLocaleConfig } from '@/i18n/config';
import {
bodyPartOfBone,
boneIdOfBodyPart,
boneIdRegistryAtom,
boneRegistryAtom,
} from '@/store/app-store';
type TapDetectionForm = {
yawResetEnabled: boolean;
@@ -45,7 +51,7 @@ const defaultValues: TapDetectionForm = {
yawResetTaps: 2,
fullResetTaps: 2,
mountingResetTaps: 2,
yawResetTracker: String(BodyPart.CHEST),
yawResetTracker: String(BodyPart.UPPER_CHEST),
fullResetTracker: String(BodyPart.LEFT_UPPER_LEG),
mountingResetTracker: String(BodyPart.RIGHT_UPPER_LEG),
numberTrackersOverThreshold: 1,
@@ -64,6 +70,8 @@ export function TapDetectionSettings() {
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const boneRegistry = useAtomValue(boneRegistryAtom);
const boneIdRegistry = useAtomValue(boneIdRegistryAtom);
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
@@ -73,7 +81,7 @@ export function TapDetectionSettings() {
});
const bodyParts: { value: string; label: string }[] = Object.values(BodyPart)
.filter((v): v is BodyPart => typeof v === 'number')
.filter((v): v is BodyPart => typeof v === 'string')
.filter((v) => TAP_DETECTION_BODY_PARTS.includes(v as BodyPart))
.map((value) => ({
value: String(value),
@@ -95,9 +103,17 @@ export function TapDetectionSettings() {
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.yawResetBoneId =
boneIdOfBodyPart(boneIdRegistry, values.yawResetTracker as BodyPart) ??
null;
settingsReq.mountingResetBoneId =
boneIdOfBodyPart(
boneIdRegistry,
values.mountingResetTracker as BodyPart
) ?? null;
settingsReq.fullResetBoneId =
boneIdOfBodyPart(boneIdRegistry, values.fullResetTracker as BodyPart) ??
null;
settingsReq.mountingResetEnabled = values.mountingResetEnabled;
settingsReq.mountingResetDelay = values.mountingResetDelay;
settingsReq.mountingResetTaps = values.mountingResetTaps;
@@ -137,21 +153,24 @@ export function TapDetectionSettings() {
fullResetTaps: settings.fullResetTaps ?? defaultValues.fullResetTaps,
mountingResetTaps:
settings.mountingResetTaps ?? defaultValues.mountingResetTaps,
yawResetTracker: String(
settings.yawResetTracker ?? defaultValues.yawResetTracker
),
fullResetTracker: String(
settings.fullResetTracker ?? defaultValues.fullResetTracker
),
mountingResetTracker: String(
settings.mountingResetTracker ?? defaultValues.mountingResetTracker
),
yawResetTracker:
settings.yawResetBoneId != null
? String(bodyPartOfBone(boneRegistry, settings.yawResetBoneId))
: defaultValues.yawResetTracker,
fullResetTracker:
settings.fullResetBoneId != null
? String(bodyPartOfBone(boneRegistry, settings.fullResetBoneId))
: defaultValues.fullResetTracker,
mountingResetTracker:
settings.mountingResetBoneId != null
? String(bodyPartOfBone(boneRegistry, settings.mountingResetBoneId))
: defaultValues.mountingResetTracker,
numberTrackersOverThreshold:
settings.numberTrackersOverThreshold ??
defaultValues.numberTrackersOverThreshold,
};
reset({ ...getValues(), ...formData });
}, [settings]);
}, [settings, boneRegistry]);
useRPCPacket(
RpcMessage.TapDetectionSettingsResponse,
@@ -20,6 +20,8 @@ import { DongleTelemetry } from './DongleTelemetry';
import { TrackerStatus } from './TrackerStatus';
import { ConnectionGroupIcon } from './TrackerConnectionGroup';
import {
bodyPartOfBone,
boneRegistryAtom,
donglesAtom,
flatTrackersAtom,
groupTrackersByConnection,
@@ -69,12 +71,15 @@ export function DongleSettingsPage() {
);
const flatTrackers = useAtomValue(flatTrackersAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const pairedTrackers = useMemo(() => {
const group = groupTrackersByConnection(flatTrackers, dongles).find(
(g) => g.kind === 'dongle' && g.dongleId === dongleId
);
const group = groupTrackersByConnection(
flatTrackers,
dongles,
boneRegistry
).find((g) => g.kind === 'dongle' && g.dongleId === dongleId);
return group ? [...group.assigned, ...group.unassigned] : [];
}, [flatTrackers, dongles, dongleId]);
}, [flatTrackers, dongles, dongleId, boneRegistry]);
const displayName = dongle?.displayName?.toString();
const customName = dongle?.customName?.toString();
@@ -234,7 +239,10 @@ export function DongleSettingsPage() {
>
<div className="flex gap-3 items-center fill-background-10">
<BodyPartIcon
bodyPart={tracker.info?.bodyPart}
bodyPart={bodyPartOfBone(
boneRegistry,
tracker.info?.boneId
)}
device={device}
trackerId={tracker.trackerId}
width={32}
@@ -10,7 +10,8 @@ import { DropdownInside } from '@/components/commons/Dropdown';
import { CheckboxInternal } from '@/components/commons/Checkbox';
import { getLocalizedTrackerName } from '@/hooks/tracker';
import { useDongleTelemetryFeed } from '@/hooks/dongle-telemetry-feed';
import { FlatDeviceTracker } from '@/store/app-store';
import { boneRegistryAtom, FlatDeviceTracker } from '@/store/app-store';
import { useAtomValue } from 'jotai';
import { RssiLossChart } from './RssiLossChart';
import { GapEventsChart } from './GapEventsChart';
import { defaultDongleTelemetryConfig, useConfig } from '@/hooks/config';
@@ -141,6 +142,7 @@ export function DongleTelemetry({
variant?: 'default' | 'modal';
}) {
const { l10n } = useLocalization();
const boneRegistry = useAtomValue(boneRegistryAtom);
const colorsRef = useRef<Map<number, string>>(new Map());
const colorFor = (deviceId: number): string => {
@@ -159,10 +161,12 @@ export function DongleTelemetry({
.filter((t) => t.device)
.map((t) => ({
deviceId: t.device!.id,
name: String(getLocalizedTrackerName(l10n, t.tracker.info)),
name: String(
getLocalizedTrackerName(l10n, t.tracker.info, boneRegistry)
),
color: colorFor(t.device!.id),
})),
[trackers, l10n]
[trackers, l10n, boneRegistry]
);
const trackerKey = list
@@ -1,7 +1,7 @@
import classNames from 'classnames';
import ReactModal from 'react-modal';
import { useEffect, useRef } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BaseModal } from '@/components/commons/BaseModal';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { CrossIcon } from '@/components/commons/icon/CrossIcon';
@@ -51,10 +51,17 @@ export function SingleTrackerBodyAssignmentMenu({
const picker = {
...pickerShell,
activePart: BodyPart.NONE,
activePart: bodyPart ?? BodyPart.NONE,
selectPart: tryOpenChokerWarning,
};
const activeParts =
bodyPart != null && bodyPart !== BodyPart.NONE ? [bodyPart] : [];
const dotClass = (part: BodyPart) =>
part === bodyPart
? 'scale-150 ring-3 ring-accent-background-30'
: undefined;
useEffect(() => {
if (!isOpen) return;
const selection = getPickerSelection(bodyPart);
@@ -77,11 +84,10 @@ export function SingleTrackerBodyAssignmentMenu({
return (
<>
<ReactModal
<BaseModal
isOpen={isOpen}
shouldCloseOnOverlayClick
shouldCloseOnEsc
onRequestClose={onClose}
aria={{ labelledby: 'single-tracker-assign-title' }}
overlayClassName={classNames(
'fixed inset-0 flex bg-background-90 bg-opacity-90 z-20'
)}
@@ -107,7 +113,10 @@ export function SingleTrackerBodyAssignmentMenu({
>
<div className="flex min-w-0 flex-col gap-3">
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1 [overflow-wrap:anywhere]">
<div
id="single-tracker-assign-title"
className="min-w-0 flex-1 [overflow-wrap:anywhere]"
>
<Typography
variant={isMobile ? 'section-title' : 'main-title'}
bold
@@ -155,6 +164,7 @@ export function SingleTrackerBodyAssignmentMenu({
</div>
<div
ref={selectionRef}
data-nav-entry
className={classNames(
'flex min-h-0 min-w-0 flex-col gap-3',
isMobile ? 'h-full min-h-0' : 'h-full p-4'
@@ -188,6 +198,8 @@ export function SingleTrackerBodyAssignmentMenu({
compact={isMobile}
fitContent={isMobile}
fillHeight
activeParts={activeParts}
dotClass={dotClass}
onRoleSelected={picker.selectPart}
/>
) : (
@@ -196,6 +208,8 @@ export function SingleTrackerBodyAssignmentMenu({
mirror={config?.mirrorView ?? false}
dotSize={dotSize.tap}
fillHeight
activeParts={activeParts}
dotClass={dotClass}
onRoleSelected={picker.selectPart}
/>
)}
@@ -233,7 +247,7 @@ export function SingleTrackerBodyAssignmentMenu({
</PickerContext.Provider>
</div>
)}
</ReactModal>
</BaseModal>
<NeckWarningModal
isOpen={shouldShowChokerWarn}
@@ -9,7 +9,6 @@ export function TrackerBattery({
voltage,
runtime,
disabled,
moreInfo = false,
textColor = 'primary',
}: {
/**
@@ -21,7 +20,6 @@ export function TrackerBattery({
voltage?: number | null;
runtime?: bigint | null;
disabled?: boolean;
moreInfo?: boolean;
textColor?: string;
}) {
const { currentLocales } = useLocaleConfig();
@@ -35,8 +33,8 @@ export function TrackerBattery({
});
const charging = (voltage || 0) > 4.3;
const debug = config?.debug || config?.devSettings.moreInfo;
const showVoltage = moreInfo && voltage && debug;
const debug = config?.debug;
const showVoltage = voltage && config?.trackerDisplay?.showBatteryVoltage;
const pct = value > 2 ? 0 : Math.min(Math.max(value, 0), 1);
@@ -44,7 +42,7 @@ export function TrackerBattery({
<Tooltip
disabled={charging || !runtime || debug}
preferedDirection="left"
content=<Typography>{percentFormatter.format(pct)}</Typography>
content={<Typography>{percentFormatter.format(pct)}</Typography>}
>
<div className="flex gap-2">
<div className="flex flex-col justify-around">
@@ -18,6 +18,8 @@ import { Tooltip } from '@/components/commons/Tooltip';
import { FirmwareIcon } from '@/components/commons/FirmwareIcon';
import { WarningIcon } from '@/components/commons/icon/WarningIcon';
import { trackingchecklistIdtoLabel } from '@/hooks/tracking-checklist';
import { useAtomValue } from 'jotai';
import { bodyPartOfBone, boneRegistryAtom } from '@/store/app-store';
function TrackerBig({
device,
@@ -26,9 +28,8 @@ function TrackerBig({
tracker: TrackerDataT;
device?: DeviceDataT;
}) {
const { config } = useConfig();
const { useName } = useTracker(tracker);
const boneRegistry = useAtomValue(boneRegistryAtom);
const trackerName = useName();
@@ -36,7 +37,7 @@ function TrackerBig({
<div className="flex flex-col justify-center rounded-md py-3 pr-4 pl-4 w-full gap-2 box-border my-8 px-6 h-32">
<div className="flex justify-center fill-background-10">
<BodyPartIcon
bodyPart={tracker.info?.bodyPart}
bodyPart={bodyPartOfBone(boneRegistry, tracker.info?.boneId)}
device={device}
trackerId={tracker.trackerId}
/>
@@ -58,7 +59,6 @@ function TrackerBig({
value={device.hardwareStatus.batteryPctEstimate / 100}
runtime={device.hardwareStatus.batteryRuntimeEstimate}
disabled={tracker.status === TrackerStatusEnum.DISCONNECTED}
moreInfo={config?.debug && config?.devSettings.moreInfo}
/>
)}
<div className="flex gap-2">
@@ -91,6 +91,7 @@ function TrackerSmol({
const { config } = useConfig();
const { useName } = useTracker(tracker);
const boneRegistry = useAtomValue(boneRegistryAtom);
const trackerName = useName();
@@ -112,7 +113,7 @@ function TrackerSmol({
)}
>
<BodyPartIcon
bodyPart={tracker.info?.bodyPart}
bodyPart={bodyPartOfBone(boneRegistry, tracker.info?.boneId)}
width={38}
device={device}
trackerId={tracker.trackerId}
@@ -143,7 +144,7 @@ function TrackerSmol({
device.hardwareStatus.ping != null) && (
<TrackerWifi
rssi={device.hardwareStatus.rssi}
rssiShowNumeric={config?.debug && config?.devSettings.moreInfo}
rssiShowNumeric={config?.trackerDisplay?.showNumericSignal}
ping={device.hardwareStatus.ping}
disabled={tracker.status === TrackerStatusEnum.DISCONNECTED}
/>
@@ -1,7 +1,7 @@
import classNames from 'classnames';
import { Clickable } from '@/components/commons/Clickable';
import { MouseEventHandler } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { getTrackerName } from '@/hooks/tracker';
import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
@@ -4,10 +4,10 @@ import { IPv4 } from 'ip-num';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';
import { BodyPart } from '@/utils/body-part';
import {
AssignTrackerRequestT,
BoardType,
BodyPart,
ForgetDeviceRequestT,
ImuType,
MagnetometerStatus,
@@ -34,8 +34,12 @@ import { TrackerCard } from './TrackerCard';
import { Quaternion } from 'three';
import { useAppContext } from '@/hooks/app';
import { MagnetometerToggleSetting } from '@/components/settings/pages/components/MagnetometerToggleSetting';
import { useSetAtom } from 'jotai';
import { ignoredTrackersAtom } from '@/store/app-store';
import { useAtomValue, useSetAtom } from 'jotai';
import {
bodyPartOfBone,
boneRegistryAtom,
ignoredTrackersAtom,
} from '@/store/app-store';
import { checkForUpdate } from '@/hooks/firmware-update';
import { Tooltip } from '@/components/commons/Tooltip';
@@ -54,6 +58,7 @@ export function TrackerSettingsPage() {
const { l10n } = useLocalization();
const { sendRPCPacket } = useWebsocketAPI();
const boneRegistry = useAtomValue(boneRegistryAtom);
const [selectRotation, setSelectRotation] = useState<boolean>(false);
const [selectBodyPart, setSelectBodyPart] = useState<boolean>(false);
const { trackernum, deviceid } = useParams<{
@@ -72,6 +77,7 @@ export function TrackerSettingsPage() {
const { trackerName } = watch();
const tracker = useTrackerFromId(trackernum, deviceid);
const bodyPart = bodyPartOfBone(boneRegistry, tracker?.tracker.info?.boneId);
const assignTracker = useAssignTracker();
const { currRotation, setDirection } = useMountingOrientation(tracker);
@@ -93,7 +99,7 @@ export function TrackerSettingsPage() {
if (trackerName == tracker.tracker.info?.customName) return;
const assignReq = new AssignTrackerRequestT();
assignReq.bodyPosition = tracker?.tracker.info?.bodyPart || BodyPart.NONE;
assignReq.boneId = tracker?.tracker.info?.boneId ?? 0;
assignReq.displayName = trackerName ?? null;
assignReq.trackerId = tracker?.tracker.trackerId;
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignReq);
@@ -160,10 +166,10 @@ export function TrackerSettingsPage() {
isOpen={selectBodyPart}
onClose={() => setSelectBodyPart(false)}
onRoleSelected={onRoleSelected}
bodyPart={tracker?.tracker.info?.bodyPart}
bodyPart={bodyPart}
/>
<MountingSelectionMenu
bodyPart={tracker?.tracker.info?.bodyPart}
bodyPart={bodyPart}
currRotation={currRotation}
isOpen={selectRotation}
onClose={() => setSelectRotation(false)}
@@ -408,22 +414,18 @@ export function TrackerSettingsPage() {
</Typography>
<div className="flex justify-between bg-background-80 w-full p-3 rounded-lg">
<div className="flex gap-3 items-center fill-background-10">
{tracker?.tracker.info?.bodyPart !== BodyPart.NONE && (
<BodyPartIcon bodyPart={tracker?.tracker.info?.bodyPart} />
{bodyPart !== BodyPart.NONE && (
<BodyPartIcon bodyPart={bodyPart} />
)}
{tracker?.tracker.info?.bodyPart === BodyPart.NONE && (
{bodyPart === BodyPart.NONE && (
<WarningIcon className="fill-status-warning" />
)}
<Typography
color={classNames({
'text-status-warning':
tracker?.tracker.info?.bodyPart === BodyPart.NONE,
'text-status-warning': bodyPart === BodyPart.NONE,
})}
>
{l10n.getString(
'body_part-' +
BodyPart[tracker?.tracker.info?.bodyPart || BodyPart.NONE]
)}
{l10n.getString('body_part-' + BodyPart[bodyPart])}
</Typography>
</div>
<div className="flex">
+214 -60
View File
@@ -1,15 +1,36 @@
import classNames from 'classnames';
import { IPv4 } from 'ip-num';
import { ReactNode, useMemo } from 'react';
import { useConfig } from '@/hooks/config';
import { useTracker, velocityGlowStyle } from '@/hooks/tracker';
import { ReactNode, useMemo, useState } from 'react';
import {
defaultTrackersTableColumns,
trackersTableColumnOrder,
TrackersTableColumnsConfig,
TrackersTableOptionalColumn,
useConfig,
} from '@/hooks/config';
import {
getLocalizedTrackerName,
useTracker,
velocityGlowStyle,
} from '@/hooks/tracker';
import { ReactLocalization, useLocalization } from '@fluent/react';
import { BodyPartIcon } from '@/components/commons/BodyPartIcon';
import { Typography } from '@/components/commons/Typography';
import { formatVector3 } from '@/utils/formatting';
import { TrackerBattery } from './TrackerBattery';
import { TrackerStatus } from './TrackerStatus';
import { TrackerWifi } from './TrackerWifi';
import { FlatDeviceTracker, TrackerConnectionGroup } from '@/store/app-store';
import {
bodyPartOfBone,
boneRegistryAtom,
FlatDeviceTracker,
TrackerConnectionGroup,
} from '@/store/app-store';
import { useAtomValue } from 'jotai';
import {
ArrowDownIcon,
ArrowUpIcon,
} from '@/components/commons/icon/ArrowIcons';
import {
TrackerConnectionGroupDefaultToolbox,
TrackerConnectionGroupSection,
@@ -19,6 +40,7 @@ import { StayAlignedInfo } from '@/components/stay-aligned/StayAlignedInfo';
import { Tooltip } from '@/components/commons/Tooltip';
import { WarningIcon } from '@/components/commons/icon/WarningIcon';
import { FirmwareIcon } from '@/components/commons/FirmwareIcon';
import { BodyPart } from '@/utils/body-part';
import {
DeviceDataT,
TrackerDataT,
@@ -31,8 +53,70 @@ import {
useTrackingChecklist,
} from '@/hooks/tracking-checklist';
const trackerSortName = ({ tracker }: FlatDeviceTracker) =>
tracker?.info?.customName?.toString() || '';
function lastVisibleColumn(
columns: TrackersTableColumnsConfig
): TrackersTableOptionalColumn | null {
for (let i = trackersTableColumnOrder.length - 1; i >= 0; i--) {
const column = trackersTableColumnOrder[i];
if (columns[column]) return column;
}
return null;
}
function columnProps(
column: TrackersTableOptionalColumn,
columns: TrackersTableColumnsConfig,
lastColumn: TrackersTableOptionalColumn | null
): { show: boolean; last: boolean } {
return { show: columns[column], last: lastColumn === column };
}
type SortColumn = 'name' | 'type' | 'battery' | 'ping' | 'tps' | 'temperature';
type SortDirection = 'asc' | 'desc';
type SortState = { column: SortColumn; direction: SortDirection } | null;
const trackerSortValue = (
{ tracker, device }: FlatDeviceTracker,
column: SortColumn,
l10n: ReactLocalization,
boneRegistry: Map<number, BodyPart>
): string | number => {
switch (column) {
case 'name':
return getLocalizedTrackerName(
l10n,
tracker?.info ?? null,
boneRegistry
).toString();
case 'type':
return device?.hardwareInfo?.manufacturer?.toString() || '';
case 'battery':
return device?.hardwareStatus?.batteryPctEstimate ?? -1;
case 'ping':
return device?.hardwareStatus?.rssi ?? -Infinity;
case 'tps':
return tracker.tps ?? -1;
case 'temperature':
return tracker.temp ?? -Infinity;
}
};
function compareTrackers(
a: FlatDeviceTracker,
b: FlatDeviceTracker,
sortState: SortState,
l10n: ReactLocalization,
boneRegistry: Map<number, BodyPart>
) {
if (!sortState) return 0;
const av = trackerSortValue(a, sortState.column, l10n, boneRegistry);
const bv = trackerSortValue(b, sortState.column, l10n, boneRegistry);
const result =
typeof av === 'string' && typeof bv === 'string'
? av.localeCompare(bv)
: (av as number) - (bv as number);
return sortState.direction === 'asc' ? result : -result;
}
export function TrackerNameCell({
tracker,
@@ -44,6 +128,7 @@ export function TrackerNameCell({
warning: TrackingChecklistStepT | boolean;
}) {
const { useName } = useTracker(tracker);
const boneRegistry = useAtomValue(boneRegistryAtom);
const name = useName();
@@ -65,7 +150,7 @@ export function TrackerNameCell({
)}
>
<BodyPartIcon
bodyPart={tracker.info?.bodyPart}
bodyPart={bodyPartOfBone(boneRegistry, tracker.info?.boneId)}
device={device}
trackerId={tracker.trackerId}
/>
@@ -111,22 +196,44 @@ function Header({
first = false,
last = false,
show = true,
sortKey,
sortState,
onSort,
}: {
first?: boolean;
last?: boolean;
name: string;
className?: string;
show?: boolean;
sortKey?: SortColumn;
sortState?: SortState;
onSort?: (column: SortColumn) => void;
}) {
const sortable = !!sortKey && !!onSort;
const active = sortable && sortState?.column === sortKey;
return (
<div
className={classNames('text-start px-2 flex items-center', {
className={classNames('text-start px-2 flex items-center gap-1', {
hidden: !show,
'pl-4': first,
'pr-4': last,
'cursor-pointer select-none hover:text-background-10': sortable,
})}
onClick={sortable ? () => onSort!(sortKey!) : undefined}
>
<Typography id={name} whitespace="whitespace-nowrap" />
{sortable && (
<span
className={classNames({ 'opacity-0': !active }, 'fill-background-10')}
>
{active && sortState?.direction === 'desc' ? (
<ArrowDownIcon size={12} />
) : (
<ArrowUpIcon size={12} />
)}
</span>
)}
</div>
);
}
@@ -161,15 +268,20 @@ function Row({
highlightedTrackers,
clickedTracker,
gridTemplateColumns,
columns,
lastColumn,
}: {
data: FlatDeviceTracker;
highlightedTrackers: highlightedTrackers | undefined;
clickedTracker: (tracker: TrackerDataT) => void;
gridTemplateColumns: string;
columns: TrackersTableColumnsConfig;
lastColumn: TrackersTableOptionalColumn | null;
}) {
const { config } = useConfig();
const fontColor = config?.devSettings?.highContrast ? 'primary' : 'secondary';
const moreInfo = config?.devSettings?.moreInfo;
const col = (column: TrackersTableOptionalColumn) =>
columnProps(column, columns, lastColumn);
const { tracker, device } = data;
const { useVelocity } = useTracker(tracker);
@@ -209,31 +321,30 @@ function Row({
style={{ gridTemplateColumns }}
onClick={() => clickedTracker(tracker)}
>
<Cell first>
<Cell first last={!lastColumn}>
<TrackerNameCell
tracker={tracker}
device={device}
warning={warning}
/>
</Cell>
<Cell>
<Cell {...col('type')}>
<Typography color={fontColor}>
{device?.hardwareInfo?.manufacturer || '--'}
</Typography>
</Cell>
<Cell>
<Cell {...col('battery')}>
{device?.hardwareStatus?.batteryPctEstimate != null && (
<TrackerBattery
value={device.hardwareStatus.batteryPctEstimate / 100}
voltage={device.hardwareStatus.batteryVoltage}
runtime={device.hardwareStatus.batteryRuntimeEstimate}
disabled={tracker.status === TrackerStatusEnum.DISCONNECTED}
moreInfo={config?.debug && config?.devSettings.moreInfo}
textColor={fontColor}
/>
)}
</Cell>
<Cell>
<Cell {...col('ping')}>
{(device?.hardwareStatus?.rssi != null ||
device?.hardwareStatus?.ping != null) && (
<TrackerWifi
@@ -249,14 +360,14 @@ function Row({
/>
)}
</Cell>
<Cell>
<Cell {...col('tps')}>
{tracker.tps !== null && (
<Typography color={fontColor}>
{tracker.tps.toString()}
</Typography>
)}
</Cell>
<Cell>
<Cell {...col('rotation')}>
<TrackerRotCell
tracker={tracker}
precise={config?.devSettings?.preciseRotation}
@@ -264,31 +375,31 @@ function Row({
color={fontColor}
/>
</Cell>
<Cell last={!moreInfo}>
<Cell {...col('temperature')}>
{tracker?.temp && tracker?.temp != 0 && (
<Typography color={fontColor} whitespace="whitespace-nowrap">
{tracker.temp.toFixed(2)}
</Typography>
)}
</Cell>
<Cell show={moreInfo}>
<Cell {...col('linearAcceleration')}>
{tracker.linearAcceleration && (
<Typography color={fontColor} whitespace="whitespace-nowrap">
{formatVector3(tracker.linearAcceleration, 1)}
</Typography>
)}
</Cell>
<Cell show={moreInfo}>
<Cell {...col('position')}>
{tracker.position && (
<Typography color={fontColor} whitespace="whitespace-nowrap">
{formatVector3(tracker.position, 2)}
</Typography>
)}
</Cell>
<Cell show={moreInfo}>
<Cell {...col('stayAligned')}>
<StayAlignedInfo color={fontColor} tracker={tracker} />
</Cell>
<Cell last={moreInfo} show={moreInfo}>
<Cell {...col('url')}>
<Typography color={fontColor} whitespace="whitespace-nowrap">
udp://
{IPv4.fromNumber(
@@ -314,42 +425,57 @@ export function TrackersTable({
}) {
const { config } = useConfig();
const { highlightedTrackers } = useTrackingChecklist();
const { l10n } = useLocalization();
const boneRegistry = useAtomValue(boneRegistryAtom);
const sortingEnabled = config?.debug && config?.devSettings?.sortByName;
const [sortState, setSortState] = useState<SortState>(null);
const onSort = (column: SortColumn) => {
setSortState((curr) => {
if (curr?.column !== column) return { column, direction: 'asc' };
if (curr.direction === 'asc') return { column, direction: 'desc' };
return null;
});
};
const sortedGroups = useMemo(() => {
if (!sortingEnabled) return groups;
const byName = (a: FlatDeviceTracker, b: FlatDeviceTracker) =>
trackerSortName(a).localeCompare(trackerSortName(b));
if (!sortState) return groups;
const cmp = (a: FlatDeviceTracker, b: FlatDeviceTracker) =>
compareTrackers(a, b, sortState, l10n, boneRegistry);
return groups.map((group) => ({
...group,
assigned: group.assigned.toSorted(byName),
unassigned: group.unassigned.toSorted(byName),
assigned: group.assigned.toSorted(cmp),
unassigned: group.unassigned.toSorted(cmp),
}));
}, [groups, sortingEnabled]);
}, [groups, sortState, l10n, boneRegistry]);
const moreInfo = config?.devSettings?.moreInfo;
const columns = config?.trackersTableColumns ?? defaultTrackersTableColumns;
const lastColumn = useMemo(() => lastVisibleColumn(columns), [columns]);
const col = (column: TrackersTableOptionalColumn) =>
columnProps(column, columns, lastColumn);
const sortProps = (column: SortColumn) => ({
sortKey: column,
sortState,
onSort,
});
const gridTemplateColumns = useMemo(() => {
const cols = [
'minmax(15rem, 1.5fr)', // Name
'9rem', // Type
'9rem', // Battery
'9rem', // Ping (w-24)
'5rem', // TPS
config?.devSettings?.preciseRotation ? '11rem' : '9rem', // Rotation
'9rem', // Temp
];
const cols = ['minmax(15rem, 1.5fr)']; // Name
if (moreInfo) {
cols.push('9rem'); // Linear Acc
cols.push('9rem'); // Position
cols.push('9rem'); // Stay Aligned
cols.push('11rem'); // URL
}
if (columns.type) cols.push('9rem');
if (columns.battery) cols.push('9rem');
if (columns.ping) cols.push('9rem'); // (w-24)
if (columns.tps) cols.push('5rem');
if (columns.rotation)
cols.push(config?.devSettings?.preciseRotation ? '11rem' : '9rem');
if (columns.temperature) cols.push('9rem');
if (columns.linearAcceleration) cols.push('9rem');
if (columns.position) cols.push('9rem');
if (columns.stayAligned) cols.push('9rem');
if (columns.url) cols.push('11rem');
return cols.join(' ');
}, [config?.devSettings?.preciseRotation, moreInfo]);
}, [columns, config?.devSettings?.preciseRotation]);
return (
<div className="w-full py-2 px-2">
@@ -361,30 +487,54 @@ export function TrackersTable({
className="grid items-center mb-1"
style={{ gridTemplateColumns }}
>
<Header name={'tracker-table-column-name'} first />
<Header name={'tracker-table-column-type'} />
<Header name={'tracker-table-column-battery'} />
<Header name={'tracker-table-column-ping'} />
<Header name={'tracker-table-column-tps'} />
<Header name={'tracker-table-column-rotation'} />
<Header
name={'tracker-table-column-name'}
first
last={!lastColumn}
{...sortProps('name')}
/>
<Header
name={'tracker-table-column-type'}
{...col('type')}
{...sortProps('type')}
/>
<Header
name={'tracker-table-column-battery'}
{...col('battery')}
{...sortProps('battery')}
/>
<Header
name={'tracker-table-column-ping'}
{...col('ping')}
{...sortProps('ping')}
/>
<Header
name={'tracker-table-column-tps'}
{...col('tps')}
{...sortProps('tps')}
/>
<Header
name={'tracker-table-column-rotation'}
{...col('rotation')}
/>
<Header
name={'tracker-table-column-temperature'}
last={!moreInfo}
{...col('temperature')}
{...sortProps('temperature')}
/>
<Header
name={'tracker-table-column-linear-acceleration'}
show={moreInfo}
{...col('linearAcceleration')}
/>
<Header
name={'tracker-table-column-position'}
{...col('position')}
/>
<Header name={'tracker-table-column-position'} show={moreInfo} />
<Header
name={'tracker-table-column-stay_aligned'}
show={moreInfo}
/>
<Header
name={'tracker-table-column-url'}
show={moreInfo}
last={moreInfo}
{...col('stayAligned')}
/>
<Header name={'tracker-table-column-url'} {...col('url')} />
</div>
</div>
<div className="flex flex-col gap-2.5">
@@ -408,6 +558,8 @@ export function TrackersTable({
data={data}
highlightedTrackers={highlightedTrackers}
gridTemplateColumns={gridTemplateColumns}
columns={columns}
lastColumn={lastColumn}
/>
))}
{group.assigned.length > 0 && group.unassigned.length > 0 && (
@@ -423,6 +575,8 @@ export function TrackersTable({
data={data}
highlightedTrackers={highlightedTrackers}
gridTemplateColumns={gridTemplateColumns}
columns={columns}
lastColumn={lastColumn}
/>
))}
</div>
@@ -6,6 +6,7 @@ import {
} from '@/hooks/tracking-checklist';
import classNames from 'classnames';
import { Clickable } from '@/components/commons/Clickable';
import { BodyPart } from '@/utils/body-part';
import {
EnableSteamVRDriverRequestT,
ResetType,
@@ -13,7 +14,6 @@ import {
TrackingChecklistPublicNetworksT,
TrackingChecklistSteamVRDisconnectedT,
TrackingChecklistStepId,
BodyPart,
RoutingOutput,
BoneRoutingSettingsRequestT,
BoneRoutingSettingsResponseT,
@@ -41,6 +41,8 @@ import { NavLink, useNavigate } from 'react-router-dom';
import { useBreakpoint } from '@/hooks/breakpoint';
import { openUrl } from '@/hooks/crossplatform';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useAtomValue } from 'jotai';
import { bodyPartOfBone, boneRegistryAtom } from '@/store/app-store';
function Step({
step: { status, id, optional, firstRequired },
@@ -179,6 +181,7 @@ function SteamVRDisconnected({
function SteamVRHandsEnabled() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const boneRegistry = useAtomValue(boneRegistryAtom);
const [routing, setRouting] = useState<BoneRoutingSettingsResponseT | null>(
null
);
@@ -203,10 +206,10 @@ function SteamVRHandsEnabled() {
req.routes = (routing.routes ?? [])
.map((route) => {
const next = new BoneRouteT();
next.bone = route.bone;
next.boneId = route.boneId;
const bodyPart = bodyPartOfBone(boneRegistry, route.boneId);
next.outputs =
route.bone === BodyPart.LEFT_HAND ||
route.bone === BodyPart.RIGHT_HAND
bodyPart === BodyPart.LEFT_HAND || bodyPart === BodyPart.RIGHT_HAND
? (route.outputs ?? []).filter(
(output) => output !== RoutingOutput.DRIVER
)
@@ -27,14 +27,21 @@ import {
Vector3,
WebGLRenderer,
} from 'three';
import { BodyPart, BoneT, MountingMethod } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BoneT, MountingMethod } from 'solarxr-protocol';
import { QuaternionFromQuatT } from '@/maths/quaternion';
import { Vector3FromVec3fT } from '@/maths/vector3';
import classNames from 'classnames';
import { useLocalization } from '@fluent/react';
import { ErrorBoundary } from 'react-error-boundary';
import { Typography } from '@/components/commons/Typography';
import { useAtomValue } from 'jotai';
import { assignedTrackersAtom, bonesAtom } from '@/store/app-store';
import {
assignedTrackersAtom,
bodyPartOfBone,
boneRegistryAtom,
bonesAtom,
} from '@/store/app-store';
import { Config, useConfig } from '@/hooks/config';
import { Tween } from '@tweenjs/tween.js';
import { EyeIcon } from '@/components/commons/icon/EyeIcon';
@@ -146,8 +153,9 @@ function createRadialFloorMesh(size = 8.0): Mesh {
function initializePreview(
canvas: HTMLCanvasElement,
bones: Map<BodyPart, BoneT>,
style: Config['skeletonPreviewStyle']
initialStyle: Config['skeletonPreviewStyle']
) {
let style = initialStyle;
let lastRenderTimeRef = 0;
let frameInterval = 0;
@@ -191,6 +199,23 @@ function initializePreview(
let heightOffset = 0;
const followOffset = new Vector3();
const desiredFollow = new Vector3();
const followDelta = new Vector3();
const computeFollow = (out: Vector3) => {
const root =
bones.get(BodyPart.HEAD) ??
bones.get(BodyPart.HIP) ??
bones.get(BodyPart.LOWER_WAIST);
if (!root) return out.copy(followOffset);
out.copy(Vector3FromVec3fT(root.headPosition));
skeletonGroup.updateWorldMatrix(true, false);
skeletonGroup.localToWorld(out);
out.y = 0;
return out;
};
const rebuildSkeleton = (newBones: Map<BodyPart, BoneT>) => {
skeletonGroup.remove(skeletonHelper);
skeletonHelper.dispose();
@@ -219,7 +244,23 @@ function initializePreview(
skeletonHelper.setTrackers(trackers);
};
const setStyle = (newStyle: Config['skeletonPreviewStyle']) => {
if (newStyle === style) return;
style = newStyle;
rebuildSkeleton(bones);
};
const render = (delta: number) => {
computeFollow(desiredFollow);
followDelta.subVectors(desiredFollow, followOffset);
if (followDelta.lengthSq() > 0) {
views.forEach((v) => {
v.camera.position.add(followDelta);
v.controls.target.add(followDelta);
});
followOffset.copy(desiredFollow);
}
views.forEach((v) => {
if (v.hidden || !renderer) return;
v.controls.update(delta);
@@ -286,6 +327,7 @@ function initializePreview(
frameInterval = interval;
},
rebuildSkeleton,
setStyle,
updatesBones: (newBones: Map<BodyPart, BoneT>) => {
bones = newBones;
skeletonHelper.setBones(bones);
@@ -297,6 +339,7 @@ function initializePreview(
heightOffset = newHeight;
views.forEach((v) => {
v.onHeightChange(v, heightOffset);
v.controls.target.add(followOffset);
});
}
},
@@ -343,12 +386,12 @@ function initializePreview(
const tween = new Tween(position)
.onUpdate(() => {
camera.position.copy(position);
camera.position.copy(position).add(followOffset);
})
.onStart(() => (frameInterval = 0))
.onComplete(() => (frameInterval = 1000 / LOW_FRAMERATE));
camera.position.copy(position);
camera.position.copy(position).add(followOffset);
const view: SkeletonPreviewView = {
camera,
@@ -388,17 +431,15 @@ function SkeletonVisualizer({
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const resizeObserver = useRef(new ResizeObserver(([e]) => onResize(e)));
const bonesList = useAtomValue(bonesAtom);
const bones = useAtomValue(bonesAtom);
const assignedTrackers = useAtomValue(assignedTrackersAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const bones = useMemo(() => {
return new Map(bonesList.map((b) => [b.bodyPart, b]));
}, [bonesList]);
const trackersByPart = useMemo(() => {
const trackers = new Map<BodyPart, TrackerPreviewData>();
for (const { tracker } of assignedTrackers) {
const bodyPart = tracker.info?.bodyPart;
if (bodyPart == null || bodyPart === BodyPart.NONE) continue;
const bodyPart = bodyPartOfBone(boneRegistry, tracker.info?.boneId);
if (bodyPart === BodyPart.NONE) continue;
trackers.set(bodyPart, {
trackerId: tracker.trackerId,
mountingOrientation: QuaternionFromQuatT(
@@ -410,7 +451,7 @@ function SkeletonVisualizer({
});
}
return trackers;
}, [assignedTrackers]);
}, [assignedTrackers, boneRegistry]);
useEffect(() => {
if (bones.size === 0) return;
@@ -432,6 +473,14 @@ function SkeletonVisualizer({
context.updateTrackers(trackersByPart);
}, [trackersByPart, disabled]);
useEffect(() => {
const context = previewContext.current;
if (!context || disabled) return;
context.setStyle(style);
context.updatesBones(bones);
context.updateTrackers(trackersByPart);
}, [style, disabled]);
const onResize = (e: ResizeObserverEntry) => {
const context = previewContext.current;
if (!context || !containerRef.current || !canvasRef.current) return;
@@ -479,7 +528,7 @@ function SkeletonVisualizer({
containerRef.current.removeEventListener('mouseenter', onEnter);
containerRef.current.removeEventListener('mouseleave', onLeave);
};
}, [disabled, style]);
}, [disabled]);
return (
<div ref={containerRef} className={classNames('w-full h-full')}>
+13 -2
View File
@@ -11,7 +11,13 @@ import { useConfig } from './config';
import { useBonesDataFeedConfig, useDataFeedConfig } from './datafeed-config';
import { useWebsocketAPI } from './websocket-api';
import { useAtomValue, useSetAtom } from 'jotai';
import { bonesAtom, datafeedAtom, devicesAtom } from '@/store/app-store';
import {
bodyPartOfBone,
bonesAtom,
boneRegistryAtom,
datafeedAtom,
devicesAtom,
} from '@/store/app-store';
import { getSentryOrCompute, updateSentryContext } from '@/utils/sentry';
import { fetchCurrentFirmwareRelease, FirmwareRelease } from './firmware-update';
import { DEFAULT_LOCALE, LangContext } from '@/i18n/config';
@@ -32,6 +38,7 @@ export function useProvideAppContext(): AppContext {
const setDatafeed = useSetAtom(datafeedAtom);
const setBones = useSetAtom(bonesAtom);
const devices = useAtomValue(devicesAtom);
const boneRegistry = useAtomValue(boneRegistryAtom);
const [currentFirmwareRelease, setCurrentFirmwareRelease] =
useState<FirmwareRelease | null>(null);
@@ -48,7 +55,11 @@ export function useProvideAppContext(): AppContext {
if (packet.index === 0) {
setDatafeed(packet);
} else if (packet.index === 1) {
setBones(packet.bones);
setBones(
new Map(
packet.bones.map((bone) => [bodyPartOfBone(boneRegistry, bone.id), bone])
)
);
}
});
+4 -3
View File
@@ -1,11 +1,12 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
export const SPINE_BODY_PARTS = [
BodyPart.HEAD,
BodyPart.NECK,
BodyPart.UPPER_CHEST,
BodyPart.CHEST,
BodyPart.WAIST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
];
export const LEG_BODY_PARTS = [
+1 -1
View File
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
/**
* I dedicate this hook to @uriel ;)
+63 -6
View File
@@ -17,18 +17,65 @@ export interface DeveloperModeConfig {
highContrast: boolean;
preciseRotation: boolean;
fastDataFeed: boolean;
sortByName: boolean;
rawSlimeRotation: boolean;
moreInfo: boolean;
}
export const defaultDevSettings: DeveloperModeConfig = {
highContrast: false,
preciseRotation: false,
fastDataFeed: false,
sortByName: false,
rawSlimeRotation: false,
moreInfo: false,
};
export interface TrackersTableColumnsConfig {
type: boolean;
battery: boolean;
ping: boolean;
tps: boolean;
rotation: boolean;
temperature: boolean;
linearAcceleration: boolean;
position: boolean;
stayAligned: boolean;
url: boolean;
}
export const defaultTrackersTableColumns: TrackersTableColumnsConfig = {
type: true,
battery: true,
ping: true,
tps: true,
rotation: true,
temperature: true,
linearAcceleration: false,
position: false,
stayAligned: false,
url: false,
};
export const trackersTableColumnOrder = [
'type',
'battery',
'ping',
'tps',
'rotation',
'temperature',
'linearAcceleration',
'position',
'stayAligned',
'url',
] as const satisfies readonly (keyof TrackersTableColumnsConfig)[];
export type TrackersTableOptionalColumn = (typeof trackersTableColumnOrder)[number];
export interface TrackerDisplayConfig {
showBatteryVoltage: boolean;
showNumericSignal: boolean;
}
export const defaultTrackerDisplay: TrackerDisplayConfig = {
showBatteryVoltage: false,
showNumericSignal: false,
};
export interface DongleTelemetryConfig {
@@ -48,9 +95,10 @@ export interface Config {
debug: boolean;
lang: string;
doneOnboarding: boolean;
watchNewDevices: boolean;
devSettings: DeveloperModeConfig;
dongleTelemetry: DongleTelemetryConfig;
trackersTableColumns: TrackersTableColumnsConfig;
trackerDisplay: TrackerDisplayConfig;
feedbackSound: boolean;
feedbackSoundVolume: number;
connectedTrackersWarning: boolean;
@@ -84,7 +132,6 @@ export const defaultConfig: Config = {
lang: 'en',
debug: false,
doneOnboarding: false,
watchNewDevices: true,
feedbackSound: true,
feedbackSoundVolume: 0.5,
connectedTrackersWarning: true,
@@ -99,6 +146,8 @@ export const defaultConfig: Config = {
vrcMutedWarnings: [],
devSettings: defaultDevSettings,
dongleTelemetry: defaultDongleTelemetryConfig,
trackersTableColumns: defaultTrackersTableColumns,
trackerDisplay: defaultTrackerDisplay,
bvhDirectory: null,
homeLayout: 'default',
skeletonPreview: true,
@@ -135,6 +184,14 @@ function fallbackToDefaults(loadedConfig: any): Config {
...defaultDongleTelemetryConfig,
...(loadedConfig?.dongleTelemetry ?? loadedConfig?.telemetry ?? {}),
},
trackersTableColumns: {
...defaultTrackersTableColumns,
...(loadedConfig?.trackersTableColumns ?? {}),
},
trackerDisplay: {
...defaultTrackerDisplay,
...(loadedConfig?.trackerDisplay ?? {}),
},
};
}
+132 -30
View File
@@ -1,4 +1,4 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import {
ARROW_KEY,
@@ -9,6 +9,7 @@ import {
type Direction,
} from '@/utils/focus-nav';
import {
aimBearing,
BUTTON_A,
BUTTON_B,
decodeInput,
@@ -22,6 +23,40 @@ const EDIT_CLASS = 'nav-editing';
const ARROW_OWNER = '[aria-expanded="true"],[data-nav-arrows]';
const EDIT_WIDGET = '[data-nav-edit]';
/** A widget that reads the stick angle itself; the nav layer leaves its directions alone. */
const AIM_WIDGET = '[data-nav-aim]';
const KEY_DIR: Record<string, Direction | undefined> = {
ArrowUp: 'up',
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowRight: 'right',
};
const TEXT_INPUT_TYPES = new Set([
'text',
'search',
'url',
'tel',
'email',
'password',
'number',
'date',
'datetime-local',
'month',
'week',
'time',
]);
/** A field where keystrokes are text. The nav layer stays out. */
function isTextEntry(el: EventTarget | null): boolean {
if (!(el instanceof HTMLElement)) return false;
if (el.isContentEditable) return true;
const tag = el.tagName;
if (tag === 'TEXTAREA' || tag === 'SELECT') return true;
if (tag === 'INPUT') return TEXT_INPUT_TYPES.has((el as HTMLInputElement).type);
return false;
}
const REPEAT_DELAY_MS = 400;
const REPEAT_INTERVAL_MS = 120;
@@ -39,9 +74,11 @@ const nav = {
held: new Map<Direction, { firedAt: number; repeating: boolean }>(),
prevButtons: new Set<number>(),
stickDir: null as Direction | null,
/** A dial-style widget listening for the raw stick/D-pad angle. */
aim: null as ((bearing: number | null) => void) | null,
pads: new Set<number>(),
rafId: 0,
listening: false,
kbStarts: 0,
starts: 0,
};
@@ -130,6 +167,9 @@ function doMove(dir: Direction) {
markActive();
const active = document.activeElement as HTMLElement | null;
// A dial-style widget owns every direction while focused.
if (active?.closest(AIM_WIDGET)) return;
if (nav.editing) {
if (active === nav.editing) {
synthKey(nav.editing, ARROW_KEY[dir]);
@@ -204,6 +244,9 @@ function poll() {
const now = performance.now();
const frame = decodeInput(navigator.getGamepads());
// A dial widget wants the real angle, not the four-way resolution.
if (nav.aim) nav.aim(aimBearing(frame));
nav.stickDir = resolveStick(frame.axX, frame.axY, nav.stickDir);
const pressedDirs = pressedDirections(frame, nav.stickDir);
@@ -225,9 +268,7 @@ function startLoop() {
}
function onConnect(e: GamepadEvent) {
const wasEmpty = nav.pads.size === 0;
nav.pads.add(e.gamepad.index);
if (wasEmpty) activateListeners();
startLoop();
markActive();
nav.shellHref = null;
@@ -236,18 +277,59 @@ function onConnect(e: GamepadEvent) {
function onDisconnect(e: GamepadEvent) {
nav.pads.delete(e.gamepad.index);
if (nav.pads.size === 0) deactivateListeners();
}
function onInterrupt() {
resetHeld();
}
function onUserInput(e: Event) {
function onPointerInput(e: Event) {
if (!e.isTrusted) return;
clearActive();
}
function onKeyNav(e: KeyboardEvent) {
if (!e.isTrusted) return;
// A widget that records or interprets raw keystrokes owns every key.
if ((e.target as HTMLElement | null)?.closest('[data-nav-raw]')) return;
const dir = KEY_DIR[e.key];
if (dir && (e.ctrlKey || e.altKey) && !e.shiftKey && !e.metaKey) {
e.preventDefault();
markActive();
doMove(dir);
return;
}
if (isTextEntry(e.target)) return;
if (e.key === 'Enter' || e.key === ' ') {
const active = document.activeElement as HTMLElement | null;
const shell = active?.closest<HTMLElement>('[data-nav-region="shell"]');
nav.shellHref = shell ? (active?.getAttribute('href') ?? null) : null;
nav.shellArea = shell?.dataset.navArea ?? null;
if ((e.ctrlKey || e.altKey) && !e.metaKey && active) {
e.preventDefault();
markActive();
if (!synthKey(active, 'Enter')) active.click();
}
return;
}
if (e.ctrlKey || e.altKey || e.metaKey) return;
if (e.key === 'Escape') {
if (nav.editing) {
exitEdit();
e.stopPropagation();
}
return;
}
clearActive();
}
/** Focus is still measurable during the blur, so a later move can resume. */
function onFocusOut(e: FocusEvent) {
const el = e.target as HTMLElement | null;
@@ -255,24 +337,22 @@ function onFocusOut(e: FocusEvent) {
nav.origin = el.getBoundingClientRect();
}
function activateListeners() {
if (nav.listening) return;
nav.listening = true;
function startKeyboard() {
if (++nav.kbStarts > 1) return;
document.addEventListener('focusout', onFocusOut, true);
window.addEventListener('pointerdown', onUserInput, true);
window.addEventListener('keydown', onUserInput, true);
window.addEventListener('pointerdown', onPointerInput, true);
window.addEventListener('keydown', onKeyNav, true);
}
function deactivateListeners() {
if (!nav.listening) return;
nav.listening = false;
function stopKeyboard() {
if (--nav.kbStarts > 0) return;
document.removeEventListener('focusout', onFocusOut, true);
window.removeEventListener('pointerdown', onUserInput, true);
window.removeEventListener('keydown', onUserInput, true);
window.removeEventListener('pointerdown', onPointerInput, true);
window.removeEventListener('keydown', onKeyNav, true);
clearActive();
}
function start() {
function startPad() {
if (++nav.starts > 1) return;
if (typeof navigator === 'undefined' || !navigator.getGamepads) return;
@@ -284,13 +364,10 @@ function start() {
for (const pad of navigator.getGamepads()) {
if (pad) nav.pads.add(pad.index);
}
if (nav.pads.size) {
activateListeners();
startLoop();
}
if (nav.pads.size) startLoop();
}
function stop() {
function stopPad() {
if (--nav.starts > 0) return;
if (nav.rafId) cancelAnimationFrame(nav.rafId);
@@ -299,7 +376,6 @@ function stop() {
window.removeEventListener('gamepaddisconnected', onDisconnect);
window.removeEventListener('blur', onInterrupt);
document.removeEventListener('visibilitychange', onInterrupt);
deactivateListeners();
resetHeld();
nav.pads.clear();
nav.origin = null;
@@ -308,17 +384,43 @@ function stop() {
export function useControllerNav() {
const { config } = useConfig();
const location = useLocation();
const enabled = config?.controllerNav !== false;
const padEnabled = config?.controllerNav !== false;
useEffect(() => {
if (!enabled) return;
start();
return stop;
}, [enabled]);
startKeyboard();
return stopKeyboard;
}, []);
useEffect(() => {
if (!padEnabled) return;
startPad();
return stopPad;
}, [padEnabled]);
useEffect(() => {
nav.origin = null;
if (!enabled || !isActive()) return;
if (!isActive()) return;
placeCursorSoon();
}, [location.pathname, enabled]);
}, [location.pathname]);
}
/**
* Receive the raw stick / D-pad bearing (degrees clockwise from up) each frame
* while `enabled`, for a widget that aims rather than steps. Rides the nav poll
* loop, so it only fires while a pad is connected and pad nav is on. Mark the
* element `data-nav-aim` so the nav layer leaves its directions alone.
*/
export function useNavAim(enabled: boolean, onAim: (bearing: number) => void) {
const onAimRef = useRef(onAim);
onAimRef.current = onAim;
useEffect(() => {
if (!enabled) return;
nav.aim = (bearing) => {
if (bearing !== null) onAimRef.current(bearing);
};
return () => {
nav.aim = null;
};
}, [enabled]);
}
+1 -1
View File
@@ -25,6 +25,7 @@ export function useDataFeedConfig() {
trackerData.tps = true;
trackerData.rawMagneticVector = true;
trackerData.stayAligned = true;
trackerData.origin = true;
const dataMask = new DeviceDataMaskT();
dataMask.deviceData = true;
@@ -65,7 +66,6 @@ export function useBonesDataFeedConfig() {
const dataFeedConfig = new DataFeedConfigT();
const boneMask = new BoneMaskT();
boneMask.bodyPart = true;
boneMask.boneLength = true;
boneMask.rotation = false;
boneMask.orientation = true;
+40
View File
@@ -0,0 +1,40 @@
import { useEffect } from 'react';
/**
* Ctrl / Shift / middle click is the browser's "open in a new window" gesture.
* On an internal link that only spawns a useless second app window. Swallow the
* modified event and re-fire a plain click on the same anchor, so React Router
* (or a bare hash link) navigates in-app and keeps any `state` the Link carries.
* External links and explicit `target="_blank"` are left alone.
*/
export function useInternalLinkGuard() {
useEffect(() => {
const onClick = (e: MouseEvent) => {
if (e.defaultPrevented) return;
if (!(e.ctrlKey || e.metaKey || e.shiftKey || e.button === 1)) return;
const anchor = (e.target as Element | null)?.closest('a');
if (!anchor?.getAttribute('href')) return;
if (anchor.target === '_blank') return;
const url = new URL(anchor.href);
const samePage =
url.origin === window.location.origin &&
url.pathname === window.location.pathname;
if (!samePage || !url.hash) return;
e.preventDefault();
e.stopPropagation();
anchor.dispatchEvent(
new MouseEvent('click', { bubbles: true, cancelable: true, view: window })
);
};
window.addEventListener('click', onClick, true);
window.addEventListener('auxclick', onClick, true);
return () => {
window.removeEventListener('click', onClick, true);
window.removeEventListener('auxclick', onClick, true);
};
}, []);
}
+3 -2
View File
@@ -38,9 +38,10 @@ const BONE_MAPPING: Map<string, SkeletonBone[]> = new Map([
'skeleton_bone-torso_group',
[
SkeletonBone.UPPER_CHEST,
SkeletonBone.CHEST,
SkeletonBone.LOWER_CHEST,
SkeletonBone.HIP,
SkeletonBone.WAIST,
SkeletonBone.UPPER_WAIST,
SkeletonBone.LOWER_WAIST,
],
],
['skeleton_bone-leg_group', [SkeletonBone.UPPER_LEG, SkeletonBone.LOWER_LEG]],
+26 -10
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { BodyPart } from '@/utils/body-part';
import {
BodyPart,
ResetRequestT,
ResetResponseT,
ResetStatus,
@@ -9,7 +9,14 @@ import {
} from 'solarxr-protocol';
import { useWebsocketAPI } from './websocket-api';
import { useAtomValue } from 'jotai';
import { assignedTrackersAtom, serverGuardsAtom } from '@/store/app-store';
import {
assignedTrackersAtom,
bodyPartOfBone,
boneIdOfBodyPart,
boneIdRegistryAtom,
boneRegistryAtom,
serverGuardsAtom,
} from '@/store/app-store';
import { FEET_BODY_PARTS, FINGER_BODY_PARTS, TOE_BODY_PARTS } from './body-parts';
import { useLocaleConfig } from '@/i18n/config';
import * as Sentry from '@sentry/react';
@@ -40,6 +47,8 @@ export function useReset(
const assignedTrackers = useAtomValue(assignedTrackersAtom);
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const boneRegistry = useAtomValue(boneRegistryAtom);
const boneIdRegistry = useAtomValue(boneIdRegistryAtom);
const finishedTimeoutRef = useRef<NodeJS.Timeout>();
const [status, setStatus] = useState<ResetBtnStatus>('idle');
const [progress, setProgress] = useState(0);
@@ -50,7 +59,9 @@ export function useReset(
const triggerReset = () => {
const req = new ResetRequestT();
req.resetType = options.type;
req.bodyParts = parts;
req.boneIds = parts
.map((part) => boneIdOfBodyPart(boneIdRegistry, part))
.filter((id): id is number => id != null);
switch (options.type) {
case ResetType.YAW:
req.delay = 0;
@@ -102,11 +113,14 @@ export function useReset(
useRPCPacket(
RpcMessage.ResetResponse,
({ status, resetType, progress, duration, bodyParts }: ResetResponseT) => {
({ status, resetType, progress, duration, boneIds }: ResetResponseT) => {
const responseBodyParts = (boneIds ?? []).map((id) =>
bodyPartOfBone(boneRegistry, id)
);
if (
resetType !== options.type ||
(resetType == ResetType.POSE_MOUNTING &&
JSON.stringify(parts) !== JSON.stringify(bodyParts))
JSON.stringify(parts) !== JSON.stringify(responseBodyParts))
) {
onResetCanceled();
return;
@@ -146,11 +160,13 @@ export function useReset(
error = 'reset-error-mounting-need_full_reset';
} else if (options.type === ResetType.POSE_MOUNTING && options.group !== 'default') {
if (
!assignedTrackers.some(
({ tracker }) =>
tracker.info?.bodyPart &&
BODY_PARTS_GROUPS[options.group].includes(tracker.info?.bodyPart)
)
!assignedTrackers.some(({ tracker }) => {
const bodyPart = bodyPartOfBone(boneRegistry, tracker.info?.boneId);
return (
bodyPart !== BodyPart.NONE &&
BODY_PARTS_GROUPS[options.group].includes(bodyPart)
);
})
) {
disabled = true;
error = `reset-error-no_${options.group}_tracker`;
+4 -3
View File
@@ -1,7 +1,7 @@
import { createContext, useContext, useEffect, useState } from 'react';
import { BodyPart } from '@/utils/body-part';
import {
AssignTrackerRequestT,
BodyPart,
QuatT,
ResetTrackerAssignmentsT,
RpcMessage,
@@ -13,7 +13,7 @@ import { useWebsocketAPI } from './websocket-api';
import { useConfig } from './config';
import { playTapSetupSound } from '@/sounds/sounds';
import { useAtomValue } from 'jotai';
import { donglesAtom } from '@/store/app-store';
import { boneIdOfBodyPart, boneIdRegistryAtom, donglesAtom } from '@/store/app-store';
import { hoveredBodyPartAtom } from './tracker-drag';
import { providePicker } from './tracker-picker';
@@ -26,6 +26,7 @@ export type Pending =
export function useAssignTracker() {
const { sendRPCPacket } = useWebsocketAPI();
const boneIdRegistry = useAtomValue(boneIdRegistryAtom);
return (
trackerId: number,
@@ -34,7 +35,7 @@ export function useAssignTracker() {
) => {
const request = new AssignTrackerRequestT();
request.trackerId = trackerId;
request.bodyPosition = bodyPart;
request.boneId = boneIdOfBodyPart(boneIdRegistry, bodyPart) ?? 0;
request.mountingOrientation = mountingOrientation;
sendRPCPacket(RpcMessage.AssignTrackerRequest, request);
};
+4 -4
View File
@@ -1,6 +1,6 @@
import { useAtomValue } from 'jotai';
import { selectAtom } from 'jotai/utils';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { createPointerDrag } from './pointer-drag';
export interface TrackerDragPayload {
@@ -10,10 +10,10 @@ export interface TrackerDragPayload {
export const trackerDrag = createPointerDrag<TrackerDragPayload, BodyPart>({
attribute: 'data-drop-body-part',
serialize: (part) => BodyPart[part],
serialize: (part) => part,
parse: (raw) => {
const part = (BodyPart as unknown as Record<string, number>)[raw];
return typeof part === 'number' ? part : null;
const part = (BodyPart as unknown as Record<string, string>)[raw];
return typeof part === 'string' ? (part as BodyPart) : null;
},
});
+5 -3
View File
@@ -1,17 +1,19 @@
import { useState } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { Quaternion } from 'three';
import * as Sentry from '@sentry/react';
import {
MountingOrientationDegreesToQuatT,
QuaternionFromQuatT,
} from '@/maths/quaternion';
import { FlatDeviceTracker } from '@/store/app-store';
import { bodyPartOfBone, boneRegistryAtom, FlatDeviceTracker } from '@/store/app-store';
import { useAssignTracker } from './tracker-assignment';
import { providePicker } from './tracker-picker';
import { useAtomValue } from 'jotai';
export function useMountingOrientation(td: FlatDeviceTracker | undefined) {
const assignTracker = useAssignTracker();
const boneRegistry = useAtomValue(boneRegistryAtom);
const mountingOrientation = td?.tracker.info?.mountingOrientation;
const currRotation = mountingOrientation
@@ -21,7 +23,7 @@ export function useMountingOrientation(td: FlatDeviceTracker | undefined) {
const setDirection = (mountingOrientationDegrees: Quaternion) => {
if (!td) return;
const bodyPart = td.tracker.info?.bodyPart || BodyPart.NONE;
const bodyPart = bodyPartOfBone(boneRegistry, td.tracker.info?.boneId);
const orientation = MountingOrientationDegreesToQuatT(mountingOrientationDegrees);
assignTracker(td.tracker.trackerId, bodyPart, orientation);
+14 -10
View File
@@ -1,6 +1,6 @@
import { useLocalization } from '@fluent/react';
import { createContext, useContext, useMemo, useState } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { useAtomValue } from 'jotai';
import { useConfig } from './config';
import {
@@ -39,8 +39,9 @@ export const LOWER_BODY = new Set([
]);
export const SPINE_PARTS = [
BodyPart.UPPER_CHEST,
BodyPart.CHEST,
BodyPart.WAIST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
];
export const ASSIGNMENT_RULES: Partial<Record<BodyPart, (BodyPart | BodyPart[])[]>> = {
@@ -54,8 +55,9 @@ export const ASSIGNMENT_RULES: Partial<Record<BodyPart, (BodyPart | BodyPart[])[
[BodyPart.RIGHT_LOWER_LEG]: [BodyPart.RIGHT_UPPER_LEG, SPINE_PARTS],
[BodyPart.LEFT_UPPER_LEG]: [SPINE_PARTS],
[BodyPart.RIGHT_UPPER_LEG]: [SPINE_PARTS],
[BodyPart.HIP]: [BodyPart.CHEST],
[BodyPart.WAIST]: [BodyPart.CHEST],
[BodyPart.HIP]: [BodyPart.UPPER_CHEST],
[BodyPart.LOWER_WAIST]: [BodyPart.UPPER_CHEST],
[BodyPart.UPPER_WAIST]: [BodyPart.UPPER_CHEST],
// TODO chest OR upperChest.
// Also don't warn if no legs.
};
@@ -77,7 +79,7 @@ export const ALL_ASSIGNABLE_PARTS = [
];
export const TAP_DETECTION_BODY_PARTS = [
BodyPart.CHEST,
BodyPart.UPPER_CHEST,
BodyPart.HIP,
BodyPart.LEFT_UPPER_ARM,
BodyPart.RIGHT_UPPER_ARM,
@@ -95,13 +97,13 @@ export const getSuggestedBodyParts = (
): BodyPart[] => {
const parts = new Set<BodyPart>();
addParts(parts, [BodyPart.CHEST, ...LEGS_PARTS]);
addParts(parts, [BodyPart.UPPER_CHEST, ...LEGS_PARTS]);
if (connectedIMUTrackersCount >= 6) parts.add(BodyPart.HIP);
if (connectedIMUTrackersCount === 7) parts.add(BodyPart.WAIST);
if (connectedIMUTrackersCount === 7) parts.add(BodyPart.LOWER_WAIST);
if (connectedIMUTrackersCount >= 8) {
addParts(parts, [BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT]);
}
if (connectedIMUTrackersCount >= 9) parts.add(BodyPart.WAIST);
if (connectedIMUTrackersCount >= 9) parts.add(BodyPart.LOWER_WAIST);
if (connectedIMUTrackersCount >= 10) {
addParts(parts, [BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM]);
}
@@ -214,7 +216,9 @@ export function providePicker() {
// Special exception for waist/hip: https://github.com/SlimeVR/SlimeVR-Server/issues/612
if (
(assignedRole === BodyPart.HIP || assignedRole === BodyPart.WAIST) &&
(assignedRole === BodyPart.HIP ||
assignedRole === BodyPart.LOWER_WAIST ||
assignedRole === BodyPart.UPPER_WAIST) &&
!trackerRoles.some((t) => LOWER_BODY.has(t))
) {
return;
+13 -5
View File
@@ -1,19 +1,23 @@
import { CSSProperties, useEffect, useMemo, useRef, useState } from 'react';
import { BodyPart, TrackerDataT, TrackerInfoT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { TrackerDataT, TrackerInfoT } from 'solarxr-protocol';
import { QuaternionFromQuatT, QuaternionToEulerDegrees } from '@/maths/quaternion';
import { ReactLocalization, useLocalization } from '@fluent/react';
import { useDataFeedConfig } from './datafeed-config';
import { Quaternion, Vector3 } from 'three';
import { Vector3FromVec3fT } from '@/maths/vector3';
import { useAtomValue } from 'jotai';
import { trackerFromIdAtom } from '@/store/app-store';
import { bodyPartOfBone, boneRegistryAtom, trackerFromIdAtom } from '@/store/app-store';
export const getLocalizedTrackerName = (
l10n: ReactLocalization,
info: TrackerInfoT | null
info: TrackerInfoT | null,
boneRegistry: Map<number, BodyPart>
) => {
if (info?.customName) return info?.customName;
if (info?.bodyPart) return l10n.getString('body_part-' + BodyPart[info?.bodyPart]);
const bodyPart = bodyPartOfBone(boneRegistry, info?.boneId);
if (bodyPart !== BodyPart.NONE)
return l10n.getString('body_part-' + BodyPart[bodyPart]);
return info?.displayName || 'NONE';
};
@@ -30,10 +34,14 @@ export const velocityGlowStyle = (velocity: number): CSSProperties => {
export const useTracker = (tracker: TrackerDataT) => {
const { l10n } = useLocalization();
const boneRegistry = useAtomValue(boneRegistryAtom);
return {
useName: () =>
useMemo(() => getLocalizedTrackerName(l10n, tracker.info), [tracker.info, l10n]),
useMemo(
() => getLocalizedTrackerName(l10n, tracker.info, boneRegistry),
[tracker.info, l10n, boneRegistry]
),
useRawRotationEulerDegrees: () =>
useMemo(() => QuaternionToEulerDegrees(tracker?.rotation), [tracker.rotation]),
useRefAdjRotationEulerDegrees: () =>
+32 -1
View File
@@ -8,7 +8,14 @@ import {
RpcMessage,
} from 'solarxr-protocol';
import { useWebsocketAPI } from './websocket-api';
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
import {
createContext,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useState,
} from 'react';
import * as Sentry from '@sentry/react';
export const trackingchecklistIdtoLabel: Record<TrackingChecklistStepId, string> = {
@@ -172,6 +179,27 @@ export function provideTrackingChecklist() {
[steps]
);
const [closed, setClosed] = useState(true);
const [closing, setClosing] = useState(false);
const toggleClosed = () => setClosed((closed) => !closed);
useLayoutEffect(() => {
setClosing(true);
const ref = setTimeout(() => setClosing(false), 1000);
return () => {
clearTimeout(ref);
setClosing(false);
};
}, [closed]);
useEffect(() => {
if (completion === 'complete') {
setClosed(true);
} else if (completion === 'incomplete') {
setClosed(false);
}
}, [completion]);
const ignoreStep = (
step: TrackingChecklistStepId,
ignore: boolean,
@@ -211,6 +239,9 @@ export function provideTrackingChecklist() {
progress,
completion,
warnings,
closed,
closing,
toggleClosed,
ignoreStep,
toggleSession: (step: TrackingChecklistStepId) =>
ignoreStep(step, !sessionIgnoredSteps.includes(step)),
+86 -5
View File
@@ -1,17 +1,33 @@
import { createContext, useContext, useEffect, useRef, useState } from 'react';
import {
BoneRegistryRequestT,
BoneRegistryT,
ClientHelloT,
ConfigurationDoneT,
ConnectionMessage,
ConnectionMessageHeaderT,
DataFeedMessage,
DataFeedMessageHeaderT,
HelloStatus,
MessageBundle,
MessageBundleT,
RpcMessage,
RpcMessageHeaderT,
ServerHelloT,
} from 'solarxr-protocol';
import { Builder, ByteBuffer } from 'flatbuffers';
import { useStore } from 'jotai';
import { useInterval, useTimeout } from './timeout';
import { log } from '@/utils/logging';
import { boneRegistryAtom } from '@/store/app-store';
import { bodyPartOfKey } from '@/utils/body-part';
// Must match SOLARXR_PROTOCOL_VERSION in server/core/.../solarxr/protocol.kt
const SOLARXR_PROTOCOL_VERSION = 2;
type ConnectionPhase = 'awaiting-hello' | 'configuring' | 'ready';
export interface WebSocketApi {
isConnected: boolean;
@@ -30,10 +46,12 @@ export type RPCPacketType = RpcMessageHeaderT['message'];
export type DataFeedPacketType = DataFeedMessageHeaderT['message'];
export function useProvideWebsocketApi(): WebSocketApi {
const store = useStore();
const rpcPacketCounterRef = useRef<number>(0);
const webSocketRef = useRef<WebSocket | null>(null);
const rpclistenerRef = useRef<EventTarget>(new EventTarget());
const datafeedlistenerRef = useRef<EventTarget>(new EventTarget());
const phaseRef = useRef<ConnectionPhase>('awaiting-hello');
const [isFirstConnection, setFirstConnection] = useState(true);
const [timedOut, setTimedOut] = useState(false);
const [isConnected, setConnected] = useState(false);
@@ -49,14 +67,31 @@ export function useProvideWebsocketApi(): WebSocketApi {
}
}, 3000);
const sendConnectionMessage = (
message: ConnectionMessageHeaderT['message'],
messageType: ConnectionMessage
) => {
if (webSocketRef?.current?.readyState !== WebSocket.OPEN) return;
const fbb = new Builder(64);
const bundle = new MessageBundleT();
bundle.connectionMsgs = [new ConnectionMessageHeaderT(messageType, message)];
MessageBundle.finishMessageBundleBuffer(fbb, bundle.pack(fbb));
webSocketRef.current.send(fbb.asUint8Array());
};
const onConnected = () => {
if (!webSocketRef.current) return;
setFirstConnection(false);
setTimedOut(false);
setConnected(true);
sendConnectionMessage(
new ClientHelloT(SOLARXR_PROTOCOL_VERSION),
ConnectionMessage.ClientHello
);
};
const onConnectionClose = () => {
phaseRef.current = 'awaiting-hello';
store.set(boneRegistryAtom, new Map());
setConnected(false);
rpcPacketCounterRef.current = 0;
};
@@ -64,11 +99,55 @@ export function useProvideWebsocketApi(): WebSocketApi {
const onMessage = async (event: { data: Blob }) => {
if (!event.data.arrayBuffer) return;
const buffer = await event.data.arrayBuffer();
const fbb = new ByteBuffer(new Uint8Array(buffer));
const message = MessageBundle.getRootAsMessageBundle(fbb).unpack();
message.connectionMsgs.forEach((connectionHeader) => {
switch (connectionHeader.messageType) {
case ConnectionMessage.ServerHello: {
const hello = connectionHeader.message as ServerHelloT;
if (hello.status !== HelloStatus.ACCEPTED) {
log(`SolarXR handshake rejected (status ${hello.status}), reconnecting`);
reconnect();
return;
}
phaseRef.current = 'configuring';
sendConnectionMessage(
new BoneRegistryRequestT(),
ConnectionMessage.BoneRegistryRequest
);
sendConnectionMessage(new ConfigurationDoneT(), ConnectionMessage.ConfigurationDone);
break;
}
case ConnectionMessage.BoneRegistry: {
const registry = connectionHeader.message as BoneRegistryT;
store.set(
boneRegistryAtom,
new Map(
registry.bones.map((bone) => [
bone.id,
bodyPartOfKey(bone.key?.toString() ?? ''),
])
)
);
break;
}
case ConnectionMessage.ConfigurationDone:
phaseRef.current = 'ready';
setFirstConnection(false);
setConnected(true);
break;
case ConnectionMessage.ConnectionError:
log(`SolarXR connection error: ${JSON.stringify(connectionHeader.message)}`);
break;
default:
break;
}
});
if (phaseRef.current !== 'ready') return;
message.rpcMsgs.forEach((rpcHeader) => {
rpclistenerRef.current?.dispatchEvent(
new CustomEvent(RpcMessage[rpcHeader.messageType], {
@@ -97,7 +176,7 @@ export function useProvideWebsocketApi(): WebSocketApi {
rpcHeader.message = data;
message.rpcMsgs = [rpcHeader];
fbb.finish(message.pack(fbb));
MessageBundle.finishMessageBundleBuffer(fbb, message.pack(fbb));
webSocketRef.current.send(fbb.asUint8Array());
@@ -118,12 +197,13 @@ export function useProvideWebsocketApi(): WebSocketApi {
datafeedHeader.message = data;
message.dataFeedMsgs = [datafeedHeader];
fbb.finish(message.pack(fbb));
MessageBundle.finishMessageBundleBuffer(fbb, message.pack(fbb));
webSocketRef.current.send(fbb.asUint8Array());
};
const connect = () => {
phaseRef.current = 'awaiting-hello';
webSocketRef.current = new WebSocket(`ws://${targetIp}:${targetPort}`);
// Connection opened
@@ -140,6 +220,7 @@ export function useProvideWebsocketApi(): WebSocketApi {
webSocketRef.current.removeEventListener('message', onMessage);
webSocketRef.current.close();
webSocketRef.current = null;
phaseRef.current = 'awaiting-hello';
setConnected(false);
};
+57 -11
View File
@@ -1,6 +1,6 @@
import { atom } from 'jotai';
import { BodyPart } from '@/utils/body-part';
import {
BodyPart,
BoneT,
DataFeedUpdateT,
DeviceDataT,
@@ -22,7 +22,35 @@ export const ignoredTrackersAtom = atom(new Set<string>());
export const datafeedAtom = atom(new DataFeedUpdateT());
export const bonesAtom = atom<BoneT[]>([]);
// Keyed by BodyPart, resolved from each Bone's registry ID as it arrives (see useProvideAppContext).
export const bonesAtom = atom<Map<BodyPart, BoneT>>(new Map());
export const boneRegistryAtom = atom<Map<number, BodyPart>>(new Map());
export function bodyPartOfBone(
registry: Map<number, BodyPart>,
boneId: number | undefined
): BodyPart {
return (boneId != null ? registry.get(boneId) : undefined) ?? BodyPart.NONE;
}
// Inverse of boneRegistryAtom, derived so the two can never drift out of sync.
// BodyPart.NONE is excluded so it never resolves back to a real bone id.
export const boneIdRegistryAtom = atom((get) => {
const registry = get(boneRegistryAtom);
const inverse = new Map<BodyPart, number>();
for (const [boneId, bodyPart] of registry) {
if (bodyPart === BodyPart.NONE) continue;
inverse.set(bodyPart, boneId);
}
return inverse;
});
export function boneIdOfBodyPart(
idRegistry: Map<BodyPart, number>,
bodyPart: BodyPart
): number | undefined {
return idRegistry.get(bodyPart);
}
export const devicesAtom = selectAtom(
datafeedAtom,
@@ -59,7 +87,8 @@ export type TrackerConnectionGroup = {
export function groupTrackersByConnection(
trackers: FlatDeviceTracker[],
dongles: DongleDataT[]
dongles: DongleDataT[],
boneRegistry: Map<number, BodyPart>
): TrackerConnectionGroup[] {
const dongleByDeviceId = new Map<number, DongleDataT>(
dongles.flatMap((dongle) => dongle.devicesIds.map((id) => [id, dongle]))
@@ -117,7 +146,8 @@ export function groupTrackersByConnection(
for (const flatTracker of trackers) {
const group = getGroup(flatTracker);
const isUnassigned = flatTracker.tracker.info?.bodyPart === BodyPart.NONE;
const isUnassigned =
bodyPartOfBone(boneRegistry, flatTracker.tracker.info?.boneId) === BodyPart.NONE;
const targetList = isUnassigned ? group.unassigned : group.assigned;
targetList.push(flatTracker);
@@ -162,11 +192,12 @@ export function groupTrackersByDevice(
}
export function groupTrackerByBodyPart(
trackers: FlatDeviceTracker[]
trackers: FlatDeviceTracker[],
boneRegistry: Map<number, BodyPart>
): Partial<Record<BodyPart, FlatDeviceTracker>> {
const byPart: Partial<Record<BodyPart, FlatDeviceTracker>> = {};
trackers.forEach((td) => {
byPart[td.tracker.info?.bodyPart ?? BodyPart.NONE] = td;
byPart[bodyPartOfBone(boneRegistry, td.tracker.info?.boneId)] = td;
});
return byPart;
}
@@ -181,22 +212,37 @@ export const flatTrackersAtom = atom((get) => {
export const assignedTrackersAtom = atom((get) => {
const trackers = get(flatTrackersAtom);
return trackers.filter(({ tracker }) => tracker.info?.bodyPart !== BodyPart.NONE);
const boneRegistry = get(boneRegistryAtom);
return trackers.filter(
({ tracker }) =>
bodyPartOfBone(boneRegistry, tracker.info?.boneId) !== BodyPart.NONE
);
});
export const trackerByBodyPartAtom = atom((get) =>
groupTrackerByBodyPart(get(assignedTrackersAtom))
groupTrackerByBodyPart(get(assignedTrackersAtom), get(boneRegistryAtom))
);
const assignedRolesRawAtom = atom((get) => {
const boneRegistry = get(boneRegistryAtom);
return get(assignedTrackersAtom).map(({ tracker }) =>
bodyPartOfBone(boneRegistry, tracker.info?.boneId)
);
});
export const assignedRolesAtom = selectAtom(
assignedTrackersAtom,
(trackers) => trackers.map(({ tracker }) => tracker.info?.bodyPart ?? BodyPart.NONE),
assignedRolesRawAtom,
(parts) => parts,
(a, b) => a.length === b.length && a.every((part, i) => part === b[i])
);
export const unassignedTrackersAtom = atom((get) => {
const trackers = get(flatTrackersAtom);
return trackers.filter(({ tracker }) => tracker.info?.bodyPart === BodyPart.NONE);
const boneRegistry = get(boneRegistryAtom);
return trackers.filter(
({ tracker }) =>
bodyPartOfBone(boneRegistry, tracker.info?.boneId) === BodyPart.NONE
);
});
export const connectedTrackersAtom = atom((get) => {
+79
View File
@@ -0,0 +1,79 @@
// SolarXR has no BodyPart type on the wire: bones are opaque registry ids and string
// keys. This mirrors the server's own definition (server/core/.../bones/BodyPart.kt)
// by name, not by number, so a bone's id can be renumbered without breaking the GUI.
export enum BodyPart {
NONE = 'NONE',
HEAD = 'HEAD',
NECK = 'NECK',
UPPER_CHEST = 'UPPER_CHEST',
LOWER_CHEST = 'LOWER_CHEST',
UPPER_WAIST = 'UPPER_WAIST',
LOWER_WAIST = 'LOWER_WAIST',
HIP = 'HIP',
LEFT_UPPER_LEG = 'LEFT_UPPER_LEG',
RIGHT_UPPER_LEG = 'RIGHT_UPPER_LEG',
LEFT_LOWER_LEG = 'LEFT_LOWER_LEG',
RIGHT_LOWER_LEG = 'RIGHT_LOWER_LEG',
LEFT_FOOT = 'LEFT_FOOT',
RIGHT_FOOT = 'RIGHT_FOOT',
LEFT_UPPER_ARM = 'LEFT_UPPER_ARM',
RIGHT_UPPER_ARM = 'RIGHT_UPPER_ARM',
LEFT_LOWER_ARM = 'LEFT_LOWER_ARM',
RIGHT_LOWER_ARM = 'RIGHT_LOWER_ARM',
LEFT_HAND = 'LEFT_HAND',
RIGHT_HAND = 'RIGHT_HAND',
LEFT_SHOULDER = 'LEFT_SHOULDER',
RIGHT_SHOULDER = 'RIGHT_SHOULDER',
LEFT_THUMB_METACARPAL = 'LEFT_THUMB_METACARPAL',
LEFT_THUMB_PROXIMAL = 'LEFT_THUMB_PROXIMAL',
LEFT_THUMB_DISTAL = 'LEFT_THUMB_DISTAL',
LEFT_INDEX_PROXIMAL = 'LEFT_INDEX_PROXIMAL',
LEFT_INDEX_INTERMEDIATE = 'LEFT_INDEX_INTERMEDIATE',
LEFT_INDEX_DISTAL = 'LEFT_INDEX_DISTAL',
LEFT_MIDDLE_PROXIMAL = 'LEFT_MIDDLE_PROXIMAL',
LEFT_MIDDLE_INTERMEDIATE = 'LEFT_MIDDLE_INTERMEDIATE',
LEFT_MIDDLE_DISTAL = 'LEFT_MIDDLE_DISTAL',
LEFT_RING_PROXIMAL = 'LEFT_RING_PROXIMAL',
LEFT_RING_INTERMEDIATE = 'LEFT_RING_INTERMEDIATE',
LEFT_RING_DISTAL = 'LEFT_RING_DISTAL',
LEFT_LITTLE_PROXIMAL = 'LEFT_LITTLE_PROXIMAL',
LEFT_LITTLE_INTERMEDIATE = 'LEFT_LITTLE_INTERMEDIATE',
LEFT_LITTLE_DISTAL = 'LEFT_LITTLE_DISTAL',
RIGHT_THUMB_METACARPAL = 'RIGHT_THUMB_METACARPAL',
RIGHT_THUMB_PROXIMAL = 'RIGHT_THUMB_PROXIMAL',
RIGHT_THUMB_DISTAL = 'RIGHT_THUMB_DISTAL',
RIGHT_INDEX_PROXIMAL = 'RIGHT_INDEX_PROXIMAL',
RIGHT_INDEX_INTERMEDIATE = 'RIGHT_INDEX_INTERMEDIATE',
RIGHT_INDEX_DISTAL = 'RIGHT_INDEX_DISTAL',
RIGHT_MIDDLE_PROXIMAL = 'RIGHT_MIDDLE_PROXIMAL',
RIGHT_MIDDLE_INTERMEDIATE = 'RIGHT_MIDDLE_INTERMEDIATE',
RIGHT_MIDDLE_DISTAL = 'RIGHT_MIDDLE_DISTAL',
RIGHT_RING_PROXIMAL = 'RIGHT_RING_PROXIMAL',
RIGHT_RING_INTERMEDIATE = 'RIGHT_RING_INTERMEDIATE',
RIGHT_RING_DISTAL = 'RIGHT_RING_DISTAL',
RIGHT_LITTLE_PROXIMAL = 'RIGHT_LITTLE_PROXIMAL',
RIGHT_LITTLE_INTERMEDIATE = 'RIGHT_LITTLE_INTERMEDIATE',
RIGHT_LITTLE_DISTAL = 'RIGHT_LITTLE_DISTAL',
LEFT_BIG_TOE = 'LEFT_BIG_TOE',
LEFT_INDEX_TOE = 'LEFT_INDEX_TOE',
LEFT_MIDDLE_TOE = 'LEFT_MIDDLE_TOE',
LEFT_RING_TOE = 'LEFT_RING_TOE',
LEFT_LITTLE_TOE = 'LEFT_LITTLE_TOE',
RIGHT_BIG_TOE = 'RIGHT_BIG_TOE',
RIGHT_INDEX_TOE = 'RIGHT_INDEX_TOE',
RIGHT_MIDDLE_TOE = 'RIGHT_MIDDLE_TOE',
RIGHT_RING_TOE = 'RIGHT_RING_TOE',
RIGHT_LITTLE_TOE = 'RIGHT_LITTLE_TOE',
}
// Standard bones are keyed `slimevr:<lowercase name>` (BoneRegistry.standard on the
// server); this is the only way a wire BoneDefinition resolves back to a BodyPart.
const KEY_TO_BODY_PART: ReadonlyMap<string, BodyPart> = new Map(
Object.values(BodyPart)
.filter((value) => value !== BodyPart.NONE)
.map((value) => [`slimevr:${value.toLowerCase()}`, value])
);
export function bodyPartOfKey(key: string): BodyPart {
return KEY_TO_BODY_PART.get(key) ?? BodyPart.NONE;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { ReactNode } from 'react';
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
export type ExtremitySide = 'left' | 'right';
+1 -1
View File
@@ -1,4 +1,4 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
export const bodypartToString = (id: BodyPart) => BodyPart[id].replace(/_/g, ' ');
+27
View File
@@ -46,6 +46,33 @@ export function pressedDirections(
return dirs;
}
/** Screen bearing of a vector, degrees clockwise from straight up. */
function bearingOf(x: number, y: number): number {
return (Math.atan2(x, -y) * (180 / Math.PI) + 360) % 360;
}
/**
* Where the stick or D-pad points, as a bearing clockwise from up, or null when
* nothing is held. For dial-style widgets that aim rather than step: the stick
* gives its real angle, the D-pad resolves its (possibly diagonal) combination.
*/
export function aimBearing(frame: GamepadFrame): number | null {
const mag = Math.max(Math.abs(frame.axX), Math.abs(frame.axY));
if (mag >= DEADZONE_ENTER) return bearingOf(frame.axX, frame.axY);
let x = 0;
let y = 0;
for (const i of frame.buttons) {
const dir = DPAD[i];
if (dir === 'up') y -= 1;
else if (dir === 'down') y += 1;
else if (dir === 'left') x -= 1;
else if (dir === 'right') x += 1;
}
if (x === 0 && y === 0) return null;
return bearingOf(x, y);
}
export function resolveStick(
axX: number,
axY: number,
+19 -14
View File
@@ -10,7 +10,8 @@ import {
import { LineSegments2 } from 'three/examples/jsm/lines/LineSegments2';
import { LineMaterial } from 'three/examples/jsm/lines/LineMaterial.js';
import { LineSegmentsGeometry } from 'three/examples/jsm/lines/LineSegmentsGeometry.js';
import { BodyPart, BoneT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BoneT } from 'solarxr-protocol';
import { QuaternionFromQuatT } from '@/maths/quaternion';
import { Vector3FromVec3fT } from '@/maths/vector3';
import { FINGER_BODY_PARTS, TOE_BODY_PARTS } from '@/hooks/body-parts';
@@ -28,11 +29,14 @@ const BONE_COLOR_GROUPS: [BodyPart[], string][] = [
[BodyPart.UPPER_CHEST, BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG],
'chartreuse',
],
[[BodyPart.CHEST], 'purple'],
[[BodyPart.WAIST, BodyPart.LEFT_LOWER_ARM, BodyPart.RIGHT_LOWER_ARM], 'red'],
[[BodyPart.LOWER_CHEST], 'purple'],
[[BodyPart.LOWER_WAIST, BodyPart.LEFT_LOWER_ARM, BodyPart.RIGHT_LOWER_ARM], 'red'],
[[BodyPart.HIP], 'orange'],
[[BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG], 'teal'],
[[BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM], 'indianred'],
[
[BodyPart.UPPER_WAIST, BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM],
'indianred',
],
[[BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND], 'fuchsia'],
[[BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER], '#00ffff'],
];
@@ -63,6 +67,7 @@ export interface TrackerPreviewData {
}
export interface SkeletonRenderPart {
bodyPart: BodyPart;
bone: BoneT;
tracker?: TrackerPreviewData;
}
@@ -86,14 +91,14 @@ export class BasedSkeletonHelper extends LineSegments2 {
}
constructor(bones: Map<BodyPart, BoneT>) {
const parts = [...bones.values()]
.filter((bone) => bone.bodyPart !== BodyPart.NONE)
.map((bone) => ({ bone }));
const parts = [...bones.entries()]
.filter(([bodyPart]) => bodyPart !== BodyPart.NONE)
.map(([bodyPart, bone]) => ({ bodyPart, bone }));
const geometry = new LineSegmentsGeometry();
geometry.setPositions(parts.flatMap(() => [0, 0, 0, 0, 0, 0]));
geometry.setColors(
parts.flatMap(({ bone }) => {
const color = getBoneColor(bone.bodyPart);
parts.flatMap(({ bodyPart }) => {
const color = getBoneColor(bodyPart);
return [color.r, color.g, color.b, color.r, color.g, color.b];
})
);
@@ -110,13 +115,13 @@ export class BasedSkeletonHelper extends LineSegments2 {
setBones(bones: Map<BodyPart, BoneT>) {
for (const part of this.parts) {
part.bone = bones.get(part.bone.bodyPart) ?? part.bone;
part.bone = bones.get(part.bodyPart) ?? part.bone;
}
}
setTrackers(trackers: Map<BodyPart, TrackerPreviewData>) {
for (const part of this.parts) {
part.tracker = trackers.get(part.bone.bodyPart);
part.tracker = trackers.get(part.bodyPart);
if (!part.tracker && part.marker) part.marker.visible = false;
}
}
@@ -125,7 +130,7 @@ export class BasedSkeletonHelper extends LineSegments2 {
const vertices: number[] = [];
for (const part of this.parts) {
const { bone, tracker } = part;
const { bodyPart, bone, tracker } = part;
boneHead.copy(Vector3FromVec3fT(bone.headPosition));
getBoneTail(bone, boneTail);
vertices.push(boneHead.x, boneHead.y, boneHead.z);
@@ -133,7 +138,7 @@ export class BasedSkeletonHelper extends LineSegments2 {
if (!tracker) continue;
if (!part.marker) {
const color = getBoneColor(bone.bodyPart);
const color = getBoneColor(bodyPart);
part.marker = new Mesh(
this.trackerMarkerGeometry,
new MeshStandardMaterial({
@@ -150,7 +155,7 @@ export class BasedSkeletonHelper extends LineSegments2 {
.normalize()
.multiply(tracker.mountingOrientation);
part.marker.visible = true;
part.marker.scale.setScalar(getTrackerMarkerScale(bone.bodyPart));
part.marker.scale.setScalar(getTrackerMarkerScale(bodyPart));
part.marker.quaternion.copy(orientation);
part.marker.position.lerpVectors(boneHead, boneTail, tracker.boneOffset);
markerOffset.set(0, 0, 0.02).applyQuaternion(orientation);
+10 -8
View File
@@ -15,7 +15,8 @@ import {
SkeletonRenderPart,
TrackerPreviewData,
} from './skeletonHelper';
import { BodyPart, BoneT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BoneT } from 'solarxr-protocol';
import { QuaternionFromQuatT } from '@/maths/quaternion';
import { Vector3FromVec3fT } from '@/maths/vector3';
import {
@@ -94,12 +95,13 @@ export class BasedSkeletonMeshHelper extends Object3D {
const m0 = getPartMaterial(new Color('#cccccc'));
const m1 = getPartMaterial(new Color('#ad0ccc'));
for (const bone of bones.values()) {
if (bone.bodyPart === BodyPart.NONE) continue;
const config = SKELETON_PART_PRESETS[bone.bodyPart];
for (const [bodyPart, bone] of bones.entries()) {
if (bodyPart === BodyPart.NONE) continue;
const config = SKELETON_PART_PRESETS[bodyPart];
if (!config.visible) continue;
const part: BonePart = {
bodyPart,
bone,
shapes: [],
surfaceDistance: 0,
@@ -172,7 +174,7 @@ export class BasedSkeletonMeshHelper extends Object3D {
setBones(bones: Map<BodyPart, BoneT>) {
for (const part of this.parts) {
const bone = bones.get(part.bone.bodyPart);
const bone = bones.get(part.bodyPart);
if (!bone) continue;
if (bone.boneLength !== part.bone.boneLength) part.surfaceDirty = true;
part.bone = bone;
@@ -181,7 +183,7 @@ export class BasedSkeletonMeshHelper extends Object3D {
setTrackers(trackers: Map<BodyPart, TrackerPreviewData>) {
for (const part of this.parts) {
const tracker = trackers.get(part.bone.bodyPart);
const tracker = trackers.get(part.bodyPart);
if (
tracker?.trackerId !== part.tracker?.trackerId ||
tracker?.boneOffset !== part.tracker?.boneOffset ||
@@ -198,7 +200,7 @@ export class BasedSkeletonMeshHelper extends Object3D {
updateMatrixWorld(force: boolean) {
for (const part of this.parts) {
const { bone, shapes } = part;
const { bodyPart, bone, shapes } = part;
position.copy(Vector3FromVec3fT(bone.headPosition));
quat.copy(QuaternionFromQuatT(bone.orientation)).normalize();
@@ -238,7 +240,7 @@ export class BasedSkeletonMeshHelper extends Object3D {
}
part.marker.visible = true;
part.marker.scale.setScalar(getTrackerMarkerScale(bone.bodyPart));
part.marker.scale.setScalar(getTrackerMarkerScale(bodyPart));
part.marker.quaternion.copy(quat).multiply(part.tracker.mountingOrientation);
part.marker.position.copy(position);
localOffset
+17 -5
View File
@@ -1,4 +1,4 @@
import { BodyPart } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import {
Color,
DoubleSide,
@@ -257,16 +257,28 @@ export const SKELETON_PART_PRESETS: Record<BodyPart, BonePartConfig> = {
offset: inBoneLengths({ length: -0.2 }),
})
),
[BodyPart.CHEST]: part(
[BodyPart.LOWER_CHEST]: part(
model('chest', {
scale: spanBone({ girthFrom: 'shoulders', length: 1, width: 0.95, depth: 0.95 }),
scale: spanBone({
girthFrom: 'shoulders',
length: 0.95,
width: 0.95,
depth: 0.95,
}),
offset: inBoneLengths({ length: 0 }),
}),
{ trackerOffset: CHEST_TRACKER_OFFSET }
),
[BodyPart.WAIST]: part(
[BodyPart.UPPER_WAIST]: part(
model('waist', {
scale: spanBone({ girthFrom: 'hips', length: 1.1, width: 0.95, depth: 0.95 }),
scale: spanBone({ girthFrom: 'hips', length: 0.95, width: 0.95, depth: 0.95 }),
offset: inBoneLengths({ length: 0.1 }),
}),
{ trackerOffset: WAIST_TRACKER_OFFSET }
),
[BodyPart.LOWER_WAIST]: part(
model('waist', {
scale: spanBone({ girthFrom: 'hips', length: 1, width: 0.95, depth: 0.95 }),
offset: inBoneLengths({ length: -0.05 }),
}),
{ trackerOffset: WAIST_TRACKER_OFFSET }
+5 -3
View File
@@ -1,4 +1,5 @@
import { BodyPart, BoneT } from 'solarxr-protocol';
import { BodyPart } from '@/utils/body-part';
import { BoneT } from 'solarxr-protocol';
import { EYE_HEIGHT_TO_HEIGHT_RATIO } from '@/hooks/height';
/**
@@ -7,8 +8,9 @@ import { EYE_HEIGHT_TO_HEIGHT_RATIO } from '@/hooks/height';
export const Y_PARTS = [
BodyPart.NECK,
BodyPart.UPPER_CHEST,
BodyPart.CHEST,
BodyPart.WAIST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
BodyPart.LEFT_UPPER_LEG,
BodyPart.LEFT_LOWER_LEG,
+70 -10
View File
@@ -65,6 +65,14 @@ protocol.registerSchemesAsPrivileged([
let mainWindow: BrowserWindow | null = null;
// While the keybind recorder is open, F3/F5/F7/F12/Ctrl+R must reach the renderer as
// ordinary keydowns instead of being eaten by hardenWindow's reload/devtools guards below,
// otherwise those keys can never be captured into a shortcut at all.
let recordingKeybind = false;
handleIpc(IPC_CHANNELS.SET_KEYBIND_RECORDING, (e, recording) => {
recordingKeybind = recording;
});
handleIpc(
IPC_CHANNELS.GH_FETCH,
async <T extends GHGet>(_e: unknown, options: T): Promise<GHReturn[T['type']]> => {
@@ -135,17 +143,20 @@ handleIpc(IPC_CHANNELS.LOG, (e, type, ...args) => {
}
});
handleIpc(IPC_CHANNELS.OPEN_URL, (e, url) => {
const allowedUrls = [
/^steam:\/\//,
/^ms-settings:network$/,
/^https:\/\/(?:.+\.)?slimevr\.dev(?:\/.+)?$/,
/^https:\/\/github\.com\/SlimeVR(?:\/.+)?$/,
/^https:\/\/discord\.gg\/slimevr$/,
];
if (allowedUrls.find((a) => url.match(a))) open(url);
const EXTERNAL_URL_ALLOWLIST = [
/^steam:\/\//,
/^ms-settings:network$/,
/^https:\/\/(?:.+\.)?slimevr\.dev(?:\/.+)?$/,
/^https:\/\/github\.com\/SlimeVR(?:\/.+)?$/,
/^https:\/\/discord\.gg\/slimevr$/,
];
const openExternalUrl = (url: string) => {
if (EXTERNAL_URL_ALLOWLIST.some((a) => url.match(a))) open(url);
else logger.error({ url }, 'attempted to open non-whitelisted URL');
});
};
handleIpc(IPC_CHANNELS.OPEN_URL, (e, url) => openExternalUrl(url));
handleIpc(IPC_CHANNELS.STORAGE, async (e, { type, method, key, value }) => {
const store = stores[type];
@@ -262,6 +273,41 @@ const saveWindowState = async () => {
});
};
/**
* The renderer is our whole UI, not a web page: it should not spawn a second
* window, reload, or fire Chromium's page shortcuts. Shut that off here so the
* renderer never has to fight the browser. Dev tools stay reachable.
*/
function hardenWindow(win: BrowserWindow) {
win.webContents.setWindowOpenHandler(({ url }) => {
openExternalUrl(url);
return { action: 'deny' };
});
const devMode = !!process.env.ELECTRON_RENDERER_URL;
win.webContents.on('before-input-event', (event, input) => {
if (input.type !== 'keyDown') return;
if (recordingKeybind) return;
const key = input.key.toLowerCase();
const mod = input.control || input.meta;
// Ctrl/Cmd+Shift+I, Cmd+Alt+I, F12 -> dev tools.
if (key === 'f12' || (key === 'i' && mod && (input.shift || input.alt))) {
event.preventDefault();
win.webContents.toggleDevTools();
return;
}
const blocked =
(input.alt && key === 'enter') || // "save page" / properties
key === 'f3' || // find next
key === 'f7' || // caret browsing
(!devMode && (key === 'f5' || (mod && key === 'r')));
if (blocked) event.preventDefault();
});
}
function createWindow() {
const validatedState = validateWindowState(windowState);
@@ -283,6 +329,8 @@ function createWindow() {
},
});
hardenWindow(mainWindow);
if (process.env.ELECTRON_RENDERER_URL) {
mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL);
mainWindow.webContents.openDevTools();
@@ -506,6 +554,18 @@ app.whenReady().then(async () => {
checkEnvironmentVariables();
const server = await spawnServer();
// No app menu on Windows/Linux (the frame is custom and every default
// accelerator is unwanted). macOS keeps a minimal one so Cmd+C/V/Q work.
Menu.setApplicationMenu(
getPlatform() === 'macos'
? Menu.buildFromTemplate([
{ role: 'appMenu' },
{ role: 'editMenu' },
{ role: 'windowMenu' },
])
: null
);
createWindow();
logger.info('SlimeVR started!');
+2
View File
@@ -48,4 +48,6 @@ contextBridge.exposeInMainWorld('electronAPI', {
setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options),
getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe'),
isSteam: () => ipcRenderer.invoke(IPC_CHANNELS.IS_STEAM),
setKeybindRecording: (recording) =>
ipcRenderer.invoke(IPC_CHANNELS.SET_KEYBIND_RECORDING, recording),
} satisfies IElectronAPI);
+1
View File
@@ -60,6 +60,7 @@ export interface IElectronAPI {
setPresence: (options: DiscordPresence) => void;
getInstallDir: () => Promise<string>;
isSteam: () => Promise<boolean>;
setKeybindRecording: (recording: boolean) => void;
}
declare global {
+2
View File
@@ -21,6 +21,7 @@ export const IPC_CHANNELS = {
GH_FETCH: 'gh-fetch',
DISCORD_PRESENCE: 'discord-presence',
IS_STEAM: 'is-steam',
SET_KEYBIND_RECORDING: 'set-keybind-recording',
} as const;
export interface IpcInvokeMap {
@@ -50,4 +51,5 @@ export interface IpcInvokeMap {
) => Promise<GHReturn[T['type']]>;
[IPC_CHANNELS.DISCORD_PRESENCE]: (options: DiscordPresence) => void;
[IPC_CHANNELS.IS_STEAM]: () => boolean;
[IPC_CHANNELS.SET_KEYBIND_RECORDING]: (recording: boolean) => void;
}
@@ -27,6 +27,7 @@ import dev.slimevr.android.serial.createAndroidSerialServer
import dev.slimevr.android.timing.createAndroidWaiter
import dev.slimevr.android.udp.resolveAndroidUdpAddress
import dev.slimevr.android.vrchat.resolveAndroidLocalIpAddress
import dev.slimevr.bones.BoneRegistryManager
import dev.slimevr.bvh.BVHManager
import dev.slimevr.config.AppConfig
import dev.slimevr.firmware.FirmwareManager
@@ -35,6 +36,7 @@ import dev.slimevr.keybind.KeybindManager
import dev.slimevr.networkprofile.NetworkProfileManager
import dev.slimevr.provisioning.ProvisioningManager
import dev.slimevr.resets.ResetsManager
import dev.slimevr.resourcepacks.ResourcePackManager
import dev.slimevr.routing.BoneRoutingManager
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
@@ -148,16 +150,22 @@ class ForegroundService : Service() {
private suspend fun startServer(scope: CoroutineScope) {
val storage = AndroidConfigStorage(filesDir)
val config = AppConfig.create(scope = scope, storage = storage)
val resourcePacks = ResourcePackManager.loadCompiled(storage, javaClass.classLoader ?: ClassLoader.getSystemClassLoader())
val skeletonDefinition = resourcePacks.skeleton
val server = VRServer.create(scope = scope)
val serialServer = createAndroidSerialServer(context = this, scope = scope)
val bones = BoneRegistryManager.create(scope = scope, initial = skeletonDefinition.registry)
// Nothing registers extension bones yet, so this is a no-op today; it exists so the
// tracking stack below never observes a registry that could still change under it.
bones.freeze()
val phase1 = Phase1Context(server = server, config = config, serialServer = serialServer)
val phase1 = Phase1Context(server = server, config = config, serialServer = serialServer, bones = bones)
val firmwareManager = FirmwareManager.create(ctx = phase1, scope = scope, flasher = AndroidFirmwareFlasher)
val networkProfileManager = NetworkProfileManager.create(scope = scope, isSupported = false)
val skeleton = Skeleton.create(scope = scope, ctx = phase1, waiter = createAndroidWaiter())
val skeleton = Skeleton.create(scope = scope, ctx = phase1, definition = skeletonDefinition, waiter = createAndroidWaiter())
val provisioningManager = ProvisioningManager.create(ctx = phase1, scope = scope)
val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope)
val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope, definition = skeletonDefinition)
val trackingChecklist = TrackingChecklist.create(scope = scope)
val udpServer = UdpServer.create(scope = scope, addressResolver = ::resolveAndroidUdpAddress)
val boneRouting = BoneRoutingManager.create(scope = scope)
@@ -178,6 +186,7 @@ class ForegroundService : Service() {
server = server,
config = config,
serialServer = serialServer,
bones = bones,
serverInfos = serverInfos,
featureFlags = FeatureFlags(
skipCheckUdev = true,
@@ -1,15 +1,23 @@
package dev.slimevr.android.config
import dev.slimevr.config.ConfigStorage
import dev.slimevr.config.StorageEntry
import dev.slimevr.config.StorageEntryType
import dev.slimevr.config.TextFileHandle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.StandardCopyOption
class AndroidConfigStorage(private val root: File) : ConfigStorage {
override suspend fun readBytes(path: String): ByteArray? = withContext(Dispatchers.IO) {
val file = resolve(path)
if (file.exists()) file.readBytes() else null
}
override suspend fun read(path: String): String? = withContext(Dispatchers.IO) {
val file = resolve(path)
if (file.exists()) file.readText() else null
@@ -46,6 +54,22 @@ class AndroidConfigStorage(private val root: File) : ConfigStorage {
directory.isDirectory || directory.mkdirs()
}
override suspend fun list(path: String): List<StorageEntry> = withContext(Dispatchers.IO) {
val directory = resolve(path).toPath()
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) return@withContext emptyList()
Files.list(directory).use { stream ->
stream.map { child ->
val type = when {
Files.isSymbolicLink(child) -> StorageEntryType.SYMLINK
Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.DIRECTORY
Files.isRegularFile(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.FILE
else -> StorageEntryType.OTHER
}
StorageEntry(child.fileName.toString(), type)
}.sorted(compareBy { it.name }).toList()
}
}
override suspend fun openTextFile(path: String): TextFileHandle = withContext(Dispatchers.IO) {
val file = resolve(path)
file.parentFile?.mkdirs()
@@ -3,11 +3,12 @@ package dev.slimevr.android.ipc
import com.google.flatbuffers.FlatBufferBuilder
import dev.slimevr.AppContextProvider
import dev.slimevr.VRServerActions
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferWriter
import dev.slimevr.logging.AppLogger
import dev.slimevr.solarxr.OutboundFrame
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.checkedSolarXRFrame
import dev.slimevr.solarxr.onSolarXRMessage
import dev.slimevr.solarxr.writeSolarXRBundle
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.engine.embeddedServer
@@ -17,11 +18,15 @@ import io.ktor.server.websocket.webSocket
import io.ktor.util.moveToByteArray
import io.ktor.websocket.Frame
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.launch
import solarxr_protocol.MessageBundle
import java.nio.ByteBuffer
import kotlin.time.Duration.Companion.seconds
const val SOLARXR_PORT = 21110
@@ -31,7 +36,6 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider)
routing {
webSocket {
AppLogger.ipc.info("New connection")
coroutineScope {
val bridge = SolarXRBridge.create(
id = appContext.server.nextHandle(),
@@ -39,30 +43,44 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider)
scope = this,
)
AppLogger.ipc.info("SolarXR[${bridge.id}] connected (websocket)")
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
bridge.outbound.on<MessageBundle> { bundle ->
bridge.outbound.on<OutboundFrame> { frame ->
val fbb = FlatBufferBuilder(256)
fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb)))
writeSolarXRBundle(fbb, frame.bundle)
send(Frame.Binary(fin = true, data = fbb.dataBuffer().moveToByteArray()))
if (frame.closeReason != null) {
AppLogger.ipc.warn("SolarXR[${bridge.id}] closing (websocket): ${frame.closeReason}")
this@coroutineScope.cancel()
}
}.launchIn(this)
bridge.startObserving()
val initTimeout = launch {
delay(10.seconds)
if (!bridge.isReady) {
AppLogger.ipc.warn("SolarXR[${bridge.id}] initialization timed out (websocket)")
this@coroutineScope.cancel()
}
}
try {
flow {
for (frame in incoming) {
when (frame) {
is Frame.Binary -> emit(frame.data)
is Frame.Close -> AppLogger.ipc.info("Connection closed")
is Frame.Close -> AppLogger.ipc.info("SolarXR[${bridge.id}] connection closed")
else -> {}
}
}
}.collect { bytes ->
val reader = JvmFlatBufferReader(ByteBuffer.wrap(bytes))
onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge)
val buffer = ByteBuffer.wrap(bytes)
val reader = checkedSolarXRFrame(buffer)
onSolarXRMessage(MessageBundle.fromByteBuffer(reader), bridge)
if (bridge.isReady) initTimeout.cancel()
}
} finally {
AppLogger.ipc.info("SolarXR[${bridge.id}] disconnected (websocket)")
bridge.disconnect()
}
}
+27
View File
@@ -15,6 +15,24 @@ tasks.withType<Jar> {
from("../../LICENSE-MIT")
}
val generateCoreResourcePackIndex = tasks.register("generateCoreResourcePackIndex") {
val corePack = layout.projectDirectory.dir("src/main/resources/dev/slimevr/resourcepacks/core")
val index = layout.buildDirectory.file("generated/resources/dev/slimevr/resourcepacks/core/index.txt")
inputs.dir(corePack)
outputs.file(index)
doLast {
val root = corePack.asFile.toPath()
val files = corePack.asFile.walkTopDown()
.filter { it.isFile && !it.relativeTo(corePack.asFile).invariantSeparatorsPath.startsWith("schemas/") }
.map { root.relativize(it.toPath()).toString().replace('\\', '/') }
.sorted()
index.get().asFile.apply {
parentFile.mkdirs()
writeText(files.joinToString("\n", postfix = "\n"))
}
}
}
allprojects {
repositories {
// Use jcenter for resolving dependencies.
@@ -31,10 +49,15 @@ kotlin {
sourceSets {
val commonMain = getByName("commonMain") {
kotlin.srcDir("src/main/java")
resources.srcDir("src/main/resources")
resources.srcDir(layout.buildDirectory.dir("generated/resources"))
dependencies {
api(project(":solarxr-protocol:generated"))
api("com.google.flatbuffers:flatbuffers-java:22.10.26")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
implementation("com.github.erosb:json-sKema:0.31.0") {
exclude(group = "org.yaml", module = "snakeyaml")
}
implementation("com.mayakapps.kache:kache:2.1.1")
implementation("io.klogging:klogging:0.11.7")
api("com.appstractive:dns-sd-kt:1.1.0")
@@ -64,6 +87,10 @@ kotlin {
}
}
tasks.matching { it.name.endsWith("ProcessResources") }.configureEach {
dependsOn(generateCoreResourcePackIndex)
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
@@ -1,5 +1,6 @@
package dev.slimevr
import dev.slimevr.bones.BoneRegistryManager
import dev.slimevr.bvh.BVHManager
import dev.slimevr.config.AppConfig
import dev.slimevr.firmware.FirmwareManager
@@ -23,12 +24,14 @@ interface Phase1ContextProvider {
val server: VRServer
val config: AppConfig
val serialServer: SerialServer
val bones: BoneRegistryManager
}
data class Phase1Context(
override val server: VRServer,
override val config: AppConfig,
override val serialServer: SerialServer,
override val bones: BoneRegistryManager,
) : Phase1ContextProvider
interface AppContextProvider : Phase1ContextProvider {
@@ -57,6 +60,7 @@ class AppContext(
override val server: VRServer,
override val config: AppConfig,
override val serialServer: SerialServer,
override val bones: BoneRegistryManager,
override val serverInfos: ServerInfos,
override val featureFlags: FeatureFlags,
override val keybindManager: KeybindManager,
@@ -1,8 +1,9 @@
package dev.slimevr.autobone
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.boneId
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
@@ -19,11 +20,12 @@ fun slideContributionWeight(ankleA: Vector3, ankleB: Vector3, localBoneTailA: Ve
// TODO This is a placeholder
val PLACEHOLDER_BODY_PARTS_TO_ADJUST = arrayOf(
BodyPart.UPPER_CHEST,
BodyPart.CHEST,
BodyPart.WAIST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
// etc.
)
).map { it.boneId }
fun step(skeletonA: ComputedSkeleton, skeletonB: ComputedSkeleton) {
// TODO We need to consider both ankles, there are two... We can do contribution per
@@ -35,9 +37,9 @@ fun step(skeletonA: ComputedSkeleton, skeletonB: ComputedSkeleton) {
// 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
val contributions = PLACEHOLDER_BODY_PARTS_TO_ADJUST.map { boneId ->
val boneA = skeletonA[boneId] ?: return@map 0f
val boneB = skeletonB[boneId] ?: return@map 0f
slideContributionWeight(
ankleA,
@@ -0,0 +1,75 @@
package dev.slimevr.bones
/**
* The standard body parts a bone in a [BoneRegistry] may represent. Not a wire type: SolarXR
* only ever carries a bone's numeric id and string key, so nothing on the wire needs this.
*/
enum class BodyPart(val value: UByte) {
NONE(0u),
HEAD(1u),
NECK(2u),
UPPER_CHEST(3u),
LOWER_CHEST(4u),
UPPER_WAIST(5u),
LOWER_WAIST(6u),
HIP(7u),
LEFT_UPPER_LEG(8u),
RIGHT_UPPER_LEG(9u),
LEFT_LOWER_LEG(10u),
RIGHT_LOWER_LEG(11u),
LEFT_FOOT(12u),
RIGHT_FOOT(13u),
LEFT_UPPER_ARM(14u),
RIGHT_UPPER_ARM(15u),
LEFT_LOWER_ARM(16u),
RIGHT_LOWER_ARM(17u),
LEFT_HAND(18u),
RIGHT_HAND(19u),
LEFT_SHOULDER(20u),
RIGHT_SHOULDER(21u),
LEFT_THUMB_METACARPAL(22u),
LEFT_THUMB_PROXIMAL(23u),
LEFT_THUMB_DISTAL(24u),
LEFT_INDEX_PROXIMAL(25u),
LEFT_INDEX_INTERMEDIATE(26u),
LEFT_INDEX_DISTAL(27u),
LEFT_MIDDLE_PROXIMAL(28u),
LEFT_MIDDLE_INTERMEDIATE(29u),
LEFT_MIDDLE_DISTAL(30u),
LEFT_RING_PROXIMAL(31u),
LEFT_RING_INTERMEDIATE(32u),
LEFT_RING_DISTAL(33u),
LEFT_LITTLE_PROXIMAL(34u),
LEFT_LITTLE_INTERMEDIATE(35u),
LEFT_LITTLE_DISTAL(36u),
RIGHT_THUMB_METACARPAL(37u),
RIGHT_THUMB_PROXIMAL(38u),
RIGHT_THUMB_DISTAL(39u),
RIGHT_INDEX_PROXIMAL(40u),
RIGHT_INDEX_INTERMEDIATE(41u),
RIGHT_INDEX_DISTAL(42u),
RIGHT_MIDDLE_PROXIMAL(43u),
RIGHT_MIDDLE_INTERMEDIATE(44u),
RIGHT_MIDDLE_DISTAL(45u),
RIGHT_RING_PROXIMAL(46u),
RIGHT_RING_INTERMEDIATE(47u),
RIGHT_RING_DISTAL(48u),
RIGHT_LITTLE_PROXIMAL(49u),
RIGHT_LITTLE_INTERMEDIATE(50u),
RIGHT_LITTLE_DISTAL(51u),
LEFT_BIG_TOE(52u),
LEFT_INDEX_TOE(53u),
LEFT_MIDDLE_TOE(54u),
LEFT_RING_TOE(55u),
LEFT_LITTLE_TOE(56u),
RIGHT_BIG_TOE(57u),
RIGHT_INDEX_TOE(58u),
RIGHT_MIDDLE_TOE(59u),
RIGHT_RING_TOE(60u),
RIGHT_LITTLE_TOE(61u),
;
companion object {
fun fromValue(value: UByte): BodyPart? = entries.firstOrNull { it.value == value }
}
}
@@ -0,0 +1,167 @@
package dev.slimevr.bones
import java.util.EnumMap
/** A registry-local bone handle. `0` is reserved and never resolves to a definition. */
@JvmInline
value class BoneId(val value: UShort) {
override fun toString(): String = "BoneId($value)"
}
/**
* The [BoneId] a standard bone always has. [BoneRegistry.standard] assigns every standard
* bone's ID to its own [BodyPart.value], so this needs no registry lookup. A dynamic [BoneId]
* (e.g. from a tracker assignment) may be an extension bone, so going the other way needs
* [BoneRegistry.bodyPartOf] instead.
*/
val BodyPart.boneId: BoneId get() = BoneId(value.toUShort())
/**
* The registry key a standard bone always has: `"slimevr:" + name.lowercase()`. Keys are
* namespaced (`namespace:path`) so extension bones can't collide with standard ones or each
* other. Use this for compile-time constants (e.g. config defaults); elsewhere resolve a key
* through an actual [BoneRegistry], since an arbitrary stored key might not be standard.
*/
val BodyPart.key: String get() = "slimevr:${name.lowercase()}"
/**
* Static anatomy tables (constraints, IK chains, external-format mappings) are keyed by
* [BodyPart] below since every key is a standard body part. [BoneId]-keyed state (inputs,
* computed poses, IK targets, tracker assignment) uses [BoneMap]/[BoneSet] instead, since a
* bone the registry defines might not have a standard body part at all.
*/
typealias BodyPartMap<V> = EnumMap<BodyPart, V>
@PublishedApi
internal val ALL_BODY_PARTS: Array<BodyPart> = BodyPart.entries.toTypedArray()
fun <V> bodyPartMap(): BodyPartMap<V> = EnumMap(BodyPart::class.java)
inline fun <V> BodyPartMap<V>.mutateCopy(block: (BodyPartMap<V>) -> Unit): BodyPartMap<V> = EnumMap(this).also(block)
inline fun <V : Any, R : Any> BodyPartMap<V>.mapValues(transform: (BodyPart, V) -> R): BodyPartMap<R> {
val result = bodyPartMap<R>()
for (bodyPart in ALL_BODY_PARTS) {
result[bodyPart] = transform(bodyPart, this[bodyPart] ?: continue)
}
return result
}
inline fun <V : Any> BodyPartMap<V>.forEachBone(action: (BodyPart, V) -> Unit) {
for (bodyPart in ALL_BODY_PARTS) {
action(bodyPart, this[bodyPart] ?: continue)
}
}
/**
* Dense array-backed map keyed by [BoneId], scoped to the [registry] it was built for.
* IDs run `1..registry.maxId`, slot 0 is unused.
*
* Extends the read-only [AbstractMap]. Mutation only goes through [set]/[copy]/[mutateCopy],
* never through the `Map` interface, so there's no mutable-iterator/`Entry` machinery to write.
*/
class BoneMap<V> private constructor(
val registry: BoneRegistry,
private val array: Array<Any?>,
) : AbstractMap<BoneId, V>() {
private fun indexOf(key: BoneId): Int {
val index = key.value.toInt()
require(index in 1 until array.size) { "$key is outside this registry" }
return index
}
@Suppress("UNCHECKED_CAST")
override fun get(key: BoneId): V? {
val index = key.value.toInt()
if (index == 0) return null
require(index in 1 until array.size) { "$key is outside this registry" }
return array[index] as V?
}
operator fun set(key: BoneId, value: V) {
array[indexOf(key)] = value
}
override val entries: Set<Map.Entry<BoneId, V>>
get() = buildSet {
for (index in 1 until array.size) {
@Suppress("UNCHECKED_CAST")
val value = array[index] as V? ?: continue
add(java.util.AbstractMap.SimpleImmutableEntry(BoneId(index.toUShort()), value))
}
}
/** Copies into a fresh array; the original is untouched by later mutation. */
fun copy(): BoneMap<V> = BoneMap(registry, array.copyOf())
companion object {
fun <V> of(registry: BoneRegistry): BoneMap<V> = BoneMap(registry, arrayOfNulls(registry.maxId + 1))
}
}
/** Mutates a [copy][BoneMap.copy] of this map, leaving the receiver untouched. */
inline fun <V> BoneMap<V>.mutateCopy(block: (BoneMap<V>) -> Unit): BoneMap<V> = copy().also(block)
/** Like the stdlib `mapValues`, but keeps the result a [BoneMap] scoped to the same registry. */
inline fun <V, R : Any> BoneMap<V>.mapValues(transform: (BoneId, V) -> R): BoneMap<R> {
val result = BoneMap.of<R>(registry)
for ((id, value) in this) result[id] = transform(id, value)
return result
}
/**
* Dense boolean-array-backed set of [BoneId], scoped to a [registry]. Avoids boxing a `UShort`
* per element, which a generic `MutableSet<BoneId>` would do.
*
* Extends the read-only [AbstractSet]. Mutation only goes through [add]/[remove]/[clear] as
* plain methods, so there's no `MutableIterator` to write.
*/
class BoneSet private constructor(
val registry: BoneRegistry,
private val present: BooleanArray,
) : AbstractSet<BoneId>() {
private var count = 0
override val size: Int get() = count
override fun contains(element: BoneId): Boolean = present.getOrNull(element.value.toInt()) == true
fun add(element: BoneId): Boolean {
val index = element.value.toInt()
require(index in 1 until present.size) { "$element is outside this registry" }
if (present[index]) return false
present[index] = true
count++
return true
}
fun addAll(elements: Iterable<BoneId>): Boolean {
var changed = false
for (element in elements) if (add(element)) changed = true
return changed
}
fun remove(element: BoneId): Boolean {
val index = element.value.toInt()
if (index !in present.indices || !present[index]) return false
present[index] = false
count--
return true
}
fun clear() {
present.fill(false)
count = 0
}
override fun iterator(): Iterator<BoneId> = present.indices.asSequence()
.filter { it != 0 && present[it] }
.map { BoneId(it.toUShort()) }
.iterator()
companion object {
fun of(registry: BoneRegistry): BoneSet = BoneSet(registry, BooleanArray(registry.maxId + 1))
fun of(registry: BoneRegistry, ids: Iterable<BoneId>): BoneSet = of(registry).also { it.addAll(ids) }
}
}
@@ -1,4 +1,4 @@
package dev.slimevr.skeleton
package dev.slimevr.bones
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
@@ -98,12 +98,13 @@ fun decomposeToSwingTwist(
rotation: Quaternion,
twistAxis: Vector3,
): Pair<Quaternion, Quaternion> {
// TODO simplify this?
val projection = rotation.project(twistAxis).unit()
val twist = Quaternion(
sqrt(1.0f - projection.xyz.lenSq()).withSign(rotation.w),
projection.xyz,
)
val swing = (rotation * twist.inv())
val swing = (rotation / twist)
return Pair(swing, twist)
}
@@ -0,0 +1,78 @@
package dev.slimevr.bones
val BODY_PART_HIERARCHY_MAP: Map<BodyPart, Array<BodyPart>> = mapOf(
BodyPart.HEAD to arrayOf(BodyPart.NECK),
BodyPart.NECK to arrayOf(BodyPart.UPPER_CHEST, BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER),
BodyPart.LEFT_SHOULDER to arrayOf(BodyPart.LEFT_UPPER_ARM),
BodyPart.LEFT_UPPER_ARM to arrayOf(BodyPart.LEFT_LOWER_ARM),
BodyPart.LEFT_LOWER_ARM to arrayOf(BodyPart.LEFT_HAND),
BodyPart.LEFT_HAND to arrayOf(
BodyPart.LEFT_THUMB_METACARPAL,
BodyPart.LEFT_INDEX_PROXIMAL,
BodyPart.LEFT_MIDDLE_PROXIMAL,
BodyPart.LEFT_RING_PROXIMAL,
BodyPart.LEFT_LITTLE_PROXIMAL,
),
BodyPart.LEFT_THUMB_METACARPAL to arrayOf(BodyPart.LEFT_THUMB_PROXIMAL),
BodyPart.LEFT_THUMB_PROXIMAL to arrayOf(BodyPart.LEFT_THUMB_DISTAL),
BodyPart.LEFT_INDEX_PROXIMAL to arrayOf(BodyPart.LEFT_INDEX_INTERMEDIATE),
BodyPart.LEFT_INDEX_INTERMEDIATE to arrayOf(BodyPart.LEFT_INDEX_DISTAL),
BodyPart.LEFT_MIDDLE_PROXIMAL to arrayOf(BodyPart.LEFT_MIDDLE_INTERMEDIATE),
BodyPart.LEFT_MIDDLE_INTERMEDIATE to arrayOf(BodyPart.LEFT_MIDDLE_DISTAL),
BodyPart.LEFT_RING_PROXIMAL to arrayOf(BodyPart.LEFT_RING_INTERMEDIATE),
BodyPart.LEFT_RING_INTERMEDIATE to arrayOf(BodyPart.LEFT_RING_DISTAL),
BodyPart.LEFT_LITTLE_PROXIMAL to arrayOf(BodyPart.LEFT_LITTLE_INTERMEDIATE),
BodyPart.LEFT_LITTLE_INTERMEDIATE to arrayOf(BodyPart.LEFT_LITTLE_DISTAL),
BodyPart.RIGHT_SHOULDER to arrayOf(BodyPart.RIGHT_UPPER_ARM),
BodyPart.RIGHT_UPPER_ARM to arrayOf(BodyPart.RIGHT_LOWER_ARM),
BodyPart.RIGHT_LOWER_ARM to arrayOf(BodyPart.RIGHT_HAND),
BodyPart.RIGHT_HAND to arrayOf(
BodyPart.RIGHT_THUMB_METACARPAL,
BodyPart.RIGHT_INDEX_PROXIMAL,
BodyPart.RIGHT_MIDDLE_PROXIMAL,
BodyPart.RIGHT_RING_PROXIMAL,
BodyPart.RIGHT_LITTLE_PROXIMAL,
),
BodyPart.RIGHT_THUMB_METACARPAL to arrayOf(BodyPart.RIGHT_THUMB_PROXIMAL),
BodyPart.RIGHT_THUMB_PROXIMAL to arrayOf(BodyPart.RIGHT_THUMB_DISTAL),
BodyPart.RIGHT_INDEX_PROXIMAL to arrayOf(BodyPart.RIGHT_INDEX_INTERMEDIATE),
BodyPart.RIGHT_INDEX_INTERMEDIATE to arrayOf(BodyPart.RIGHT_INDEX_DISTAL),
BodyPart.RIGHT_MIDDLE_PROXIMAL to arrayOf(BodyPart.RIGHT_MIDDLE_INTERMEDIATE),
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to arrayOf(BodyPart.RIGHT_MIDDLE_DISTAL),
BodyPart.RIGHT_RING_PROXIMAL to arrayOf(BodyPart.RIGHT_RING_INTERMEDIATE),
BodyPart.RIGHT_RING_INTERMEDIATE to arrayOf(BodyPart.RIGHT_RING_DISTAL),
BodyPart.RIGHT_LITTLE_PROXIMAL to arrayOf(BodyPart.RIGHT_LITTLE_INTERMEDIATE),
BodyPart.RIGHT_LITTLE_INTERMEDIATE to arrayOf(BodyPart.RIGHT_LITTLE_DISTAL),
BodyPart.UPPER_CHEST to arrayOf(BodyPart.LOWER_CHEST),
BodyPart.LOWER_CHEST to arrayOf(BodyPart.UPPER_WAIST),
BodyPart.UPPER_WAIST to arrayOf(BodyPart.LOWER_WAIST),
BodyPart.LOWER_WAIST to arrayOf(BodyPart.HIP),
BodyPart.HIP to arrayOf(BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG),
BodyPart.LEFT_UPPER_LEG to arrayOf(BodyPart.LEFT_LOWER_LEG),
BodyPart.LEFT_LOWER_LEG to arrayOf(BodyPart.LEFT_FOOT),
BodyPart.RIGHT_UPPER_LEG to arrayOf(BodyPart.RIGHT_LOWER_LEG),
BodyPart.RIGHT_LOWER_LEG to arrayOf(BodyPart.RIGHT_FOOT),
BodyPart.LEFT_FOOT to arrayOf(
BodyPart.LEFT_BIG_TOE,
BodyPart.LEFT_INDEX_TOE,
BodyPart.LEFT_MIDDLE_TOE,
BodyPart.LEFT_RING_TOE,
BodyPart.LEFT_LITTLE_TOE,
),
BodyPart.RIGHT_FOOT to arrayOf(
BodyPart.RIGHT_BIG_TOE,
BodyPart.RIGHT_INDEX_TOE,
BodyPart.RIGHT_MIDDLE_TOE,
BodyPart.RIGHT_RING_TOE,
BodyPart.RIGHT_LITTLE_TOE,
),
)
@@ -0,0 +1,35 @@
package dev.slimevr.bones
import dev.slimevr.context.Context
import kotlinx.coroutines.CoroutineScope
data class BoneRegistryState(val registry: BoneRegistry, val frozen: Boolean)
sealed interface BoneRegistryActions {
data object Freeze : BoneRegistryActions
}
typealias BoneRegistryContext = Context<BoneRegistryState, BoneRegistryActions>
/**
* Owns the server's [BoneRegistry], seeded from the compiled resource-pack skeleton at bootstrap.
* [freeze] closes the window before the tracking stack starts: no tracker or skeleton state is
* ever built against a registry that can still change under it.
*/
class BoneRegistryManager(val context: BoneRegistryContext) {
val current: BoneRegistry get() = context.state.value.registry
fun freeze() = context.dispatch(BoneRegistryActions.Freeze)
companion object {
fun create(scope: CoroutineScope, initial: BoneRegistry = BoneRegistry.standard()): BoneRegistryManager {
val context = Context.create(
initialState = BoneRegistryState(registry = initial, frozen = false),
scope = scope,
reducer = ::reduce,
name = "BoneRegistry",
)
return BoneRegistryManager(context)
}
}
}
@@ -0,0 +1,5 @@
package dev.slimevr.bones
fun reduce(state: BoneRegistryState, action: BoneRegistryActions): BoneRegistryState = when (action) {
is BoneRegistryActions.Freeze -> state.copy(frozen = true)
}
@@ -0,0 +1,155 @@
package dev.slimevr.bones
import solarxr_protocol.connection.BoneDefinition
import solarxr_protocol.connection.BoneRegistry as WireBoneRegistry
private val BODY_PART_BY_VALUE: Array<BodyPart?> = arrayOfNulls<BodyPart>(UByte.MAX_VALUE.toInt() + 1).also { array ->
for (bodyPart in BodyPart.entries) array[bodyPart.value.toInt()] = bodyPart
}
/**
* The server's bone identity and hierarchy. IDs are dense (`1..maxId`),
* so [BoneMap]/[BoneSet] can use a plain array instead of a hash table.
*
* [BodyPart] is only used at the edges: to seed [standard], and to resolve specific bones by
* name. Everything else is [BoneId]-keyed, so a bone with no standard body part still works.
*/
class BoneRegistry private constructor(
val value: WireBoneRegistry,
val maxId: Int,
val root: BoneId,
private val byId: Array<BoneDefinition?>,
private val byKey: Map<String, BoneDefinition>,
private val childIds: Array<IntArray>,
) {
operator fun get(id: BoneId): BoneDefinition? = byId.getOrNull(id.value.toInt())
/** Constant-time lookup with no per-call allocation. */
operator fun get(bodyPart: BodyPart): BoneId? {
if (bodyPart == BodyPart.NONE) return null
val id = BoneId(bodyPart.value.toUShort())
return id.takeIf { this[it] != null }
}
fun byKey(key: String): BoneDefinition? = byKey[key]
/** The registry key is stable across a registry rebuild; a [BoneId] is not. */
operator fun get(key: String): BoneId? = byKey(key)?.let { BoneId(it.id) }
/** Inverse of `get(BodyPart)`; null when the ID is unknown or outside the standard `BodyPart` range. */
fun bodyPartOf(id: BoneId): BodyPart? {
if (this[id] == null) return null
return BODY_PART_BY_VALUE.getOrNull(id.value.toInt())?.takeIf { it != BodyPart.NONE }
}
/** Inverse of `get(String)`. */
fun keyOf(id: BoneId): String? = this[id]?.key
fun parentOf(id: BoneId): BoneId? = this[id]?.parent?.takeIf { it != 0.toUShort() }?.let(::BoneId)
fun childrenOf(id: BoneId): List<BoneId> = (childIds.getOrNull(id.value.toInt()) ?: IntArray(0)).map { BoneId(it.toUShort()) }
// Hierarchy is fixed for the registry's lifetime, so traversals are too: computed once here,
// not memoized lazily on first use. This registry is shared across every consumer once
// frozen, each free to call hierarchyFrom from its own dispatcher; a lazily-filled plain
// array has no happens-before edge between an unsynchronized writer and a reader on another
// thread, which a mutable ArrayList published that way can turn into a torn read instead of
// just wasted recomputation. Built once, single-threaded, during construction instead.
private val hierarchyCache: Array<List<Pair<BoneId?, BoneId>>> = Array(2 * (maxId + 1)) { cacheIndex ->
val root = BoneId((cacheIndex / 2).toUShort())
val onlyChildren = cacheIndex % 2 == 1
val result = mutableListOf<Pair<BoneId?, BoneId>>()
fun visit(parent: BoneId?, id: BoneId, skipSelf: Boolean) {
if (!skipSelf) result += parent to id
for (childId in childIds.getOrNull(id.value.toInt()) ?: IntArray(0)) {
visit(id, BoneId(childId.toUShort()), false)
}
}
visit(null, root, onlyChildren)
result
}
fun hierarchyFrom(root: BoneId, onlyChildren: Boolean = false): List<Pair<BoneId?, BoneId>> = hierarchyCache[root.value.toInt() * 2 + if (onlyChildren) 1 else 0]
/** Cached: a full rebuild starts from [root] alone, the most common call to [highest]. */
val rootSet: BoneSet = BoneSet.of(this, listOf(root))
/** Of [ids], the ones with no ancestor also in [ids]. */
fun highest(ids: BoneSet): BoneSet {
// root is everyone's ancestor, so if it changed it's the only "highest" bone.
if (root in ids) return rootSet
val result = BoneSet.of(this, ids)
for (id in ids) {
var parent = parentOf(id)
while (parent != null) {
if (parent in ids) {
result.remove(id)
break
}
parent = parentOf(parent)
}
}
return result
}
companion object {
fun standard(): BoneRegistry {
val parts = BodyPart.entries.filter { it != BodyPart.NONE }
val parentPartOf = buildMap {
for ((parent, children) in BODY_PART_HIERARCHY_MAP) for (child in children) put(child, parent)
}
return from(
WireBoneRegistry(
bones = parts.map { bodyPart ->
BoneDefinition(
id = bodyPart.boneId.value,
key = bodyPart.key,
displayName = bodyPart.name.replace('_', ' ').lowercase(),
parent = parentPartOf[bodyPart]?.boneId?.value ?: 0.toUShort(),
)
},
),
)
}
fun from(registry: WireBoneRegistry): BoneRegistry {
val n = registry.bones.size
val definitions = registry.bones.associateBy { it.id }
require(definitions.size == n) { "Bone registry contains duplicate IDs" }
require(registry.bones.map { it.key }.toSet().size == n) { "Bone registry contains duplicate keys" }
require(definitions.keys == (1..n).map { it.toUShort() }.toSet()) {
"Bone registry IDs must be exactly 1..$n"
}
require(registry.bones.all { it.parent == 0.toUShort() || it.parent in definitions }) { "Bone registry has an unknown parent" }
val visited = mutableSetOf<UShort>()
fun root(id: UShort): UShort {
require(visited.add(id)) { "Bone registry contains a cycle" }
val parent = definitions.getValue(id).parent
return if (parent == 0.toUShort()) id else root(parent)
}
definitions.keys.forEach {
visited.clear()
root(it)
}
val byId = arrayOfNulls<BoneDefinition>(n + 1)
val children = Array(n + 1) { mutableListOf<Int>() }
var root: BoneId? = null
for (definition in registry.bones) {
val id = definition.id.toInt()
byId[id] = definition
if (definition.parent == 0.toUShort()) {
require(root == null) { "Bone registry has more than one root: a skeleton has exactly one" }
root = BoneId(definition.id)
} else {
children[definition.parent.toInt()] += id
}
}
return BoneRegistry(
value = registry,
maxId = n,
root = requireNotNull(root) { "Bone registry has no root" },
byId = byId,
byKey = registry.bones.associateBy { it.key },
childIds = Array(children.size) { children[it].toIntArray() },
)
}
}
}
@@ -1,15 +1,14 @@
package dev.slimevr.bvh
import com.jme3.math.FastMath
import dev.slimevr.bones.BoneId
import dev.slimevr.config.TextFileHandle
import dev.slimevr.skeleton.BODY_PART_HIERARCHY_MAP
import dev.slimevr.skeleton.ComputedSkeleton
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import solarxr_protocol.datatypes.BodyPart
private const val FRAME_COUNT_DIGITS = Long.MAX_VALUE.toString().length
private const val OFFSET_SCALE = 1f
@@ -30,7 +29,7 @@ class BvhStream(
mutex.withLock {
check(!closed) { "BVH stream is closed" }
file.write("HIERARCHY\n")
writeBone(BodyPart.HEAD, null, bones, 0)
writeBone(bones.registry.root, null, bones, 0)
file.write("MOTION\n")
file.write("Frames: ")
file.flush()
@@ -56,10 +55,10 @@ class BvhStream(
}
lastFrameTime = now
val head = bones[BodyPart.HEAD]
val head = bones[bones.registry.root]
val pos = head?.headPosition ?: Vector3.ZERO
file.write("${pos.x * POSITION_SCALE} ${pos.y * POSITION_SCALE} ${pos.z * POSITION_SCALE}")
writeRotations(BodyPart.HEAD, bones)
writeRotations(bones.registry.root, bones)
file.write("\n")
frameCount++
}
@@ -97,43 +96,44 @@ class BvhStream(
// A joint's BVH OFFSET is the vector from the parent joint's origin to this joint's, in the
// parent's frame: the parent's own head->tail offset plus this bone's head displacement.
private fun getBvhOffset(childPart: BodyPart, parentPart: BodyPart, bones: ComputedSkeleton): Vector3 {
val parentOffset = bones[parentPart]?.offset ?: Vector3.ZERO
val childHeadOffset = bones[childPart]?.headOffset ?: Vector3.ZERO
private fun getBvhOffset(childId: BoneId, parentId: BoneId, bones: ComputedSkeleton): Vector3 {
val parentOffset = bones[parentId]?.offset ?: Vector3.ZERO
val childHeadOffset = bones[childId]?.headOffset ?: Vector3.ZERO
return (parentOffset + childHeadOffset) * OFFSET_SCALE
}
private suspend fun writeRotations(part: BodyPart, bones: ComputedSkeleton) {
val bone = bones[part]
private suspend fun writeRotations(boneId: BoneId, bones: ComputedSkeleton) {
val bone = bones[boneId]
val rot = bone?.localRotation ?: Quaternion.IDENTITY
val angles = rot.toEulerAngles(EulerOrder.ZXY)
file.write(" ${angles.z * FastMath.RAD_TO_DEG} ${angles.x * FastMath.RAD_TO_DEG} ${angles.y * FastMath.RAD_TO_DEG}")
BODY_PART_HIERARCHY_MAP[part]?.forEach { child -> writeRotations(child, bones) }
bones.registry.childrenOf(boneId).forEach { child -> writeRotations(child, bones) }
}
private suspend fun writeBone(part: BodyPart, parent: BodyPart?, bones: ComputedSkeleton, depth: Int) {
private suspend fun writeBone(boneId: BoneId, parentId: BoneId?, bones: ComputedSkeleton, depth: Int) {
val indent = "\t".repeat(depth)
val childIndent = "\t".repeat(depth + 1)
file.write("$indent${if (parent == null) "ROOT" else "JOINT"} $part\n")
val name = requireNotNull(bones.registry[boneId]) { "$boneId is missing from its own registry" }.key.uppercase()
file.write("$indent${if (parentId == null) "ROOT" else "JOINT"} $name\n")
file.write("$indent{\n")
if (parent == null) {
if (parentId == null) {
file.write("${childIndent}OFFSET 0.0 0.0 0.0\n")
file.write("${childIndent}CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n")
} else {
val offset = getBvhOffset(part, parent, bones)
val offset = getBvhOffset(boneId, parentId, bones)
file.write("${childIndent}OFFSET ${offset.x} ${offset.y} ${offset.z}\n")
file.write("${childIndent}CHANNELS 3 Zrotation Xrotation Yrotation\n")
}
val children = BODY_PART_HIERARCHY_MAP[part]
if (children.isNullOrEmpty()) {
val children = bones.registry.childrenOf(boneId)
if (children.isEmpty()) {
file.write("${childIndent}End Site\n")
file.write("$childIndent{\n")
file.write("${"\t".repeat(depth + 2)}OFFSET 0.0 0.0 0.0\n")
file.write("$childIndent}\n")
} else {
children.forEach { child -> writeBone(child, part, bones, depth + 1) }
children.forEach { child -> writeBone(child, boneId, bones, depth + 1) }
}
file.write("$indent}\n")
}
@@ -18,14 +18,25 @@ import kotlinx.serialization.json.Json
interface ConfigStorage {
suspend fun read(path: String): String?
suspend fun readBytes(path: String): ByteArray? = read(path)?.encodeToByteArray()
suspend fun write(path: String, content: String)
suspend fun backup(path: String)
suspend fun exists(path: String): Boolean
suspend fun ensureDirectory(path: String): Boolean
/** Lists direct children only. Implementations must not follow symbolic links. */
suspend fun list(path: String): List<StorageEntry> = emptyList()
suspend fun openTextFile(path: String): TextFileHandle
fun displayPath(path: String): String = path
}
enum class StorageEntryType { FILE, DIRECTORY, SYMLINK, OTHER }
data class StorageEntry(
val name: String,
val type: StorageEntryType,
)
interface TextFileHandle {
suspend fun write(text: String)
suspend fun flush()
Loaded 100 of 342 files, more files were not shown because too many files have changed in this diff. Show more