diff --git a/bindings-provider/src/main.cpp b/bindings-provider/src/main.cpp index 2ffa25b7f..70c29e343 100644 --- a/bindings-provider/src/main.cpp +++ b/bindings-provider/src/main.cpp @@ -29,77 +29,6 @@ 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(helloReply->data()); - if (serverHello->status() != HelloStatus::ACCEPTED) { - Logger::get().error("SolarXR server rejected our protocol version (status {})", - static_cast(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(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> 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; @@ -109,7 +38,7 @@ static void onYawReset(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); - FinishMessageBundleBuffer(fbb, bundle); + fbb.Finish(bundle); conn.sendMsg(fbb); } static void onFullReset(SolarXRConnection &conn) { @@ -121,7 +50,7 @@ static void onFullReset(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); - FinishMessageBundleBuffer(fbb, bundle); + fbb.Finish(bundle); conn.sendMsg(fbb); } static void onMountingCalibration(SolarXRConnection &conn) { @@ -133,22 +62,21 @@ static void onMountingCalibration(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); - FinishMessageBundleBuffer(fbb, bundle); + fbb.Finish(bundle); conn.sendMsg(fbb); } static void onFeetMountingCalibration(SolarXRConnection &conn) { flatbuffers::FlatBufferBuilder fbb; - auto boneIds = fbb.CreateVector( - { static_cast(datatypes::BodyPart::LEFT_FOOT), - static_cast(datatypes::BodyPart::RIGHT_FOOT) }); - auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::POSE_MOUNTING, boneIds, 0.f); + 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 msgHeader = rpc::CreateRpcMessageHeader( fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union()); auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); - FinishMessageBundleBuffer(fbb, bundle); + fbb.Finish(bundle); conn.sendMsg(fbb); } static void onToggleTracking(SolarXRConnection &conn) { @@ -163,7 +91,7 @@ static void onToggleTracking(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); - FinishMessageBundleBuffer(fbb, bundle); + fbb.Finish(bundle); conn.sendMsg(fbb); } @@ -208,11 +136,6 @@ int main() { try { SolarXRConnection conn; - if (!performSolarXRHandshake(conn)) { - logger.error("Failed to complete SolarXR connection initialization"); - return 1; - } - std::unique_ptr sys{ nullptr, shutdown_vr }; diff --git a/bindings-provider/src/solarxr.cpp b/bindings-provider/src/solarxr.cpp index 935a6f11d..2db669645 100644 --- a/bindings-provider/src/solarxr.cpp +++ b/bindings-provider/src/solarxr.cpp @@ -129,31 +129,3 @@ 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(len - done), 0); - if (n == SocketError || n == 0) return false; - done += static_cast(n); - } - return true; -} - -std::optional> SolarXRConnection::recvMsg() { - uint32_t size = 0; - if (!recvExact(reinterpret_cast(&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 buffer(size - sizeof(size)); - if (!buffer.empty() && !recvExact(reinterpret_cast(buffer.data()), buffer.size())) { - return std::nullopt; - } - return buffer; -} diff --git a/bindings-provider/src/solarxr.hpp b/bindings-provider/src/solarxr.hpp index 0d89d4d03..e22d3a3db 100644 --- a/bindings-provider/src/solarxr.hpp +++ b/bindings-provider/src/solarxr.hpp @@ -1,8 +1,6 @@ #pragma once #include -#include -#include #ifdef _WIN32 #define WIN32_MEAN_AND_LEAN @@ -48,9 +46,6 @@ 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); @@ -58,8 +53,4 @@ 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> recvMsg(); }; diff --git a/gui/app/src/components/Toolbar.tsx b/gui/app/src/components/Toolbar.tsx index 9cc3b135a..755706657 100644 --- a/gui/app/src/components/Toolbar.tsx +++ b/gui/app/src/components/Toolbar.tsx @@ -10,11 +10,7 @@ import { } from '@/hooks/reset'; import { Tooltip } from './commons/Tooltip'; import { useAtomValue } from 'jotai'; -import { - assignedTrackersAtom, - bodyPartOfBone, - boneRegistryAtom, -} from '@/store/app-store'; +import { assignedTrackersAtom } from '@/store/app-store'; import { useBreakpoint } from '@/hooks/breakpoint'; import { useMemo } from 'react'; import { ResetButtonIcon } from './home/ResetButton'; @@ -151,7 +147,6 @@ function BasicResetButton({ export function Toolbar() { const assignedTrackers = useAtomValue(assignedTrackersAtom); - const boneRegistry = useAtomValue(boneRegistryAtom); const { visibleGroups, groupVisibility } = useMemo(() => { const groupVisibility = Object.keys(BODY_PARTS_GROUPS) @@ -159,10 +154,11 @@ export function Toolbar() { .reduce( (curr, key) => { const group = key as MountingResetGroup; - curr[group] = assignedTrackers.some(({ tracker }) => { - const bodyPart = bodyPartOfBone(boneRegistry, tracker.info?.boneId); - return bodyPart && BODY_PARTS_GROUPS[group].includes(bodyPart); - }); + curr[group] = assignedTrackers.some( + ({ tracker }) => + tracker.info?.bodyPart && + BODY_PARTS_GROUPS[group].includes(tracker.info?.bodyPart) + ); return curr; }, @@ -173,7 +169,7 @@ export function Toolbar() { groupVisibility, visibleGroups: Object.values(groupVisibility).filter((v) => v).length, }; - }, [assignedTrackers, boneRegistry]); + }, [assignedTrackers]); return ( <> diff --git a/gui/app/src/components/commons/BodyDisplay.tsx b/gui/app/src/components/commons/BodyDisplay.tsx index 69d6bac42..e8d3f9f05 100644 --- a/gui/app/src/components/commons/BodyDisplay.tsx +++ b/gui/app/src/components/commons/BodyDisplay.tsx @@ -2,12 +2,7 @@ import classNames from 'classnames'; import { useEffect, useMemo, useRef, useState } from 'react'; import { BodyPart } from 'solarxr-protocol'; import { PersonFrontIcon } from './PersonFrontIcon'; -import { - boneRegistryAtom, - FlatDeviceTracker, - groupTrackerByBodyPart, -} from '@/store/app-store'; -import { useAtomValue } from 'jotai'; +import { FlatDeviceTracker, groupTrackerByBodyPart } from '@/store/app-store'; interface SlotDot { id: string; @@ -126,10 +121,9 @@ export function BodyDisplay({ }; }, []); - const boneRegistry = useAtomValue(boneRegistryAtom); const trackerByPart = useMemo( - () => groupTrackerByBodyPart(trackers, boneRegistry), - [trackers, boneRegistry] + () => groupTrackerByBodyPart(trackers), + [trackers] ); return ( diff --git a/gui/app/src/components/firmware-tool/steps/FlashingMethodStep.tsx b/gui/app/src/components/firmware-tool/steps/FlashingMethodStep.tsx index 1340c7f96..2c8a758fc 100644 --- a/gui/app/src/components/firmware-tool/steps/FlashingMethodStep.tsx +++ b/gui/app/src/components/firmware-tool/steps/FlashingMethodStep.tsx @@ -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 { boneRegistryAtom, devicesAtom } from '@/store/app-store'; +import { 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,7 +230,6 @@ function OTADevicesList({ const { l10n } = useLocalization(); const { selectDevices } = useFirmwareTool(); const allDevices = useAtomValue(devicesAtom); - const boneRegistry = useAtomValue(boneRegistryAtom); const devices = allDevices.filter(({ hardwareInfo, trackers }) => { @@ -249,7 +248,7 @@ function OTADevicesList({ const deviceNames = ({ trackers }: DeviceDataT) => trackers - .map(({ info }) => getLocalizedTrackerName(l10n, info, boneRegistry)) + .map(({ info }) => getLocalizedTrackerName(l10n, info)) .filter((i): i is string => !!i); const selectedDevices = watch('ota.selectedDevices'); diff --git a/gui/app/src/components/firmware-update/FirmwareUpdate.tsx b/gui/app/src/components/firmware-update/FirmwareUpdate.tsx index 62c935074..26754bfce 100644 --- a/gui/app/src/components/firmware-update/FirmwareUpdate.tsx +++ b/gui/app/src/components/firmware-update/FirmwareUpdate.tsx @@ -3,7 +3,6 @@ import { Typography } from '@/components/commons/Typography'; import { getLocalizedTrackerName } from '@/hooks/tracker'; import { ComponentProps, useEffect, useMemo, useRef, useState } from 'react'; import { - BodyPart, BoardType, DeviceDataT, FirmwareDeviceIdTableT, @@ -34,7 +33,7 @@ import { object } from 'yup'; import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon'; import { A } from '@/components/commons/A'; import { useAtomValue } from 'jotai'; -import { boneRegistryAtom, devicesAtom } from '@/store/app-store'; +import { devicesAtom } from '@/store/app-store'; import { checkForUpdate } from '@/hooks/firmware-update'; interface FirmwareUpdateForm { @@ -50,13 +49,9 @@ interface UpdateStatus { deviceNames: string[]; } -const deviceNames = ( - { trackers }: DeviceDataT, - l10n: ReactLocalization, - boneRegistry: Map -) => +const deviceNames = ({ trackers }: DeviceDataT, l10n: ReactLocalization) => trackers - .map(({ info }) => getLocalizedTrackerName(l10n, info, boneRegistry)) + .map(({ info }) => getLocalizedTrackerName(l10n, info)) .filter((i): i is string => !!i); const DeviceList = ({ @@ -67,14 +62,13 @@ const DeviceList = ({ devices: DeviceDataT[]; }) => { const { l10n } = useLocalization(); - const boneRegistry = useAtomValue(boneRegistryAtom); return devices.map((device, index) => ( )); }; @@ -117,7 +111,6 @@ export function FirmwareUpdate() { const [status, setStatus] = useState>({}); const allDevices = useAtomValue(devicesAtom); - const boneRegistry = useAtomValue(boneRegistryAtom); const devices = allDevices.filter( @@ -313,7 +306,7 @@ export function FirmwareUpdate() { type: FirmwareUpdateMethod.OTAFirmwareUpdate, deviceIdPort: id, board: device.hardwareInfo?.officialBoardType ?? BoardType.UNKNOWN, - deviceNames: deviceNames(device, l10n, boneRegistry), + deviceNames: deviceNames(device, l10n), }, ]; }, diff --git a/gui/app/src/components/home/Home.tsx b/gui/app/src/components/home/Home.tsx index 57182a7af..315f2f0a7 100644 --- a/gui/app/src/components/home/Home.tsx +++ b/gui/app/src/components/home/Home.tsx @@ -13,7 +13,6 @@ import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon'; import { useAtomValue } from 'jotai'; import { assignedTrackersAtom, - boneRegistryAtom, donglesAtom, flatTrackersAtom, groupTrackersByConnection, @@ -36,13 +35,12 @@ export function Home() { 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, boneRegistry), - [allTrackers, dongles, boneRegistry] + () => groupTrackersByConnection(allTrackers, dongles), + [allTrackers, dongles] ); const sendToSettings = (tracker: TrackerDataT) => { diff --git a/gui/app/src/components/onboarding/pages/body-proportions/ManualProportions.tsx b/gui/app/src/components/onboarding/pages/body-proportions/ManualProportions.tsx index c5989b305..8f9cbe6f9 100644 --- a/gui/app/src/components/onboarding/pages/body-proportions/ManualProportions.tsx +++ b/gui/app/src/components/onboarding/pages/body-proportions/ManualProportions.tsx @@ -318,7 +318,7 @@ function ButtonsControl({ control }: { control: ManualProportionControls }) { ); }; const beneathFloor = useMemo(() => { - const head = bones.get(BodyPart.HEAD); + const head = bones.find((bone) => bone.bodyPart === BodyPart.HEAD); return !(head?.headPosition && head.headPosition.y >= MIN_HEIGHT); }, [bones]); diff --git a/gui/app/src/components/onboarding/pages/trackers-assign/MobileTrackerAssign.tsx b/gui/app/src/components/onboarding/pages/trackers-assign/MobileTrackerAssign.tsx index b74b06a2a..58e3cdf64 100644 --- a/gui/app/src/components/onboarding/pages/trackers-assign/MobileTrackerAssign.tsx +++ b/gui/app/src/components/onboarding/pages/trackers-assign/MobileTrackerAssign.tsx @@ -19,12 +19,9 @@ import { velocityGlowStyle, } from '@/hooks/tracker'; import { - boneRegistryAtom, FlatDeviceTracker, groupTrackersByConnection, - unassignedTrackersAtom, } from '@/store/app-store'; -import { useAtomValue } from 'jotai'; import { BodyAssignmentPanel } from './BodyAssignmentPanel'; import { AssignmentEmptyState, @@ -158,12 +155,17 @@ export function MobileTrackerAssign() { selectTracker, } = assignment; - const boneRegistry = useAtomValue(boneRegistryAtom); const groups = useMemo( - () => groupTrackersByConnection(flatTrackers, dongles, boneRegistry), - [flatTrackers, dongles, boneRegistry] + () => groupTrackersByConnection(flatTrackers, dongles), + [flatTrackers, dongles] + ); + const unassignedTrackers = useMemo( + () => + flatTrackers.filter( + ({ tracker }) => tracker.info?.bodyPart === BodyPart.NONE + ), + [flatTrackers] ); - const unassignedTrackers = useAtomValue(unassignedTrackersAtom); const unassignedTrackerData = useMemo( () => unassignedTrackers.map(({ tracker }) => tracker), [unassignedTrackers] diff --git a/gui/app/src/components/onboarding/pages/trackers-assign/TrackerAssignmentList.tsx b/gui/app/src/components/onboarding/pages/trackers-assign/TrackerAssignmentList.tsx index 30b8ec842..0ddd8f050 100644 --- a/gui/app/src/components/onboarding/pages/trackers-assign/TrackerAssignmentList.tsx +++ b/gui/app/src/components/onboarding/pages/trackers-assign/TrackerAssignmentList.tsx @@ -21,8 +21,6 @@ import { useIsTrackerBeingDragged, } from '@/hooks/tracker-drag'; import { - bodyPartOfBone, - boneRegistryAtom, FlatDeviceTracker, groupTrackersByConnection, groupTrackersByDevice, @@ -30,7 +28,6 @@ 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(); @@ -45,10 +42,9 @@ export function TrackerAssignmentList() { pendingTrackerId, } = useAssignment(); const assignedCount = assignedTrackers.length; - const boneRegistry = useAtomValue(boneRegistryAtom); const groups = useMemo( - () => groupTrackersByConnection(trackers, dongles, boneRegistry), - [trackers, dongles, boneRegistry] + () => groupTrackersByConnection(trackers, dongles), + [trackers, dongles] ); const variant = state.alonePage ? 'primary' : 'tertiary'; @@ -299,7 +295,6 @@ export function SimpleTrackerRow({ }) { const { useVelocity } = useTracker(tracker); const velocity = useVelocity(); - const boneRegistry = useAtomValue(boneRegistryAtom); const row = (
>; -function toRouteMap( - routes: BoneRouteT[], - boneRegistry: Map -): RouteMap { +function toRouteMap(routes: BoneRouteT[]): RouteMap { return new Map( - routes.map((route) => [ - bodyPartOfBone(boneRegistry, route.boneId), - new Set(route.outputs ?? []), - ]) + routes.map((route) => [route.bone, new Set(route.outputs ?? [])]) ); } -function toBoneRoutes( - routes: RouteMap, - boneIdRegistry: Map -): BoneRouteT[] { +function toBoneRoutes(routes: RouteMap): BoneRouteT[] { return Array.from(routes.entries()) .filter(([, outputs]) => outputs.size > 0) - .flatMap(([bone, outputs]) => { - const boneId = boneIdOfBodyPart(boneIdRegistry, bone); - if (boneId == null) return []; + .map(([bone, outputs]) => { const route = new BoneRouteT(); - route.boneId = boneId; + route.bone = bone; route.outputs = Array.from(outputs); - return [route]; + return route; }); } @@ -335,8 +317,6 @@ 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); @@ -354,29 +334,17 @@ export function BoneRoutingSettings() { const accepts = useMemo( () => new Map( - outputs.map((status) => [ - status.output, - new Set( - (status.accepts ?? []).map((id) => bodyPartOfBone(boneRegistry, id)) - ), - ]) + outputs.map((status) => [status.output, new Set(status.accepts ?? [])]) ), - [outputs, boneRegistry] + [outputs] ); const requires = useMemo( () => new Map( - outputs.map((status) => [ - status.output, - new Set( - (status.requires ?? []).map((id) => - bodyPartOfBone(boneRegistry, id) - ) - ), - ]) + outputs.map((status) => [status.output, new Set(status.requires ?? [])]) ), - [outputs, boneRegistry] + [outputs] ); const overridable = useMemo( @@ -384,14 +352,10 @@ export function BoneRoutingSettings() { new Map( outputs.map((status) => [ status.output, - new Set( - (status.overridable ?? []).map((id) => - bodyPartOfBone(boneRegistry, id) - ) - ), + new Set(status.overridable ?? []), ]) ), - [outputs, boneRegistry] + [outputs] ); const conflicts = useMemo( @@ -471,15 +435,15 @@ export function BoneRoutingSettings() { useEffect(() => { setAutomatic(settings.automatic ?? true); - setRoutes(toRouteMap(settings.routes ?? [], boneRegistry)); + setRoutes(toRouteMap(settings.routes ?? [])); const handsAlreadyOnDriver = (settings.routes ?? []).some( (route) => - HAND_BODY_PARTS.includes(bodyPartOfBone(boneRegistry, route.boneId)) && + HAND_BODY_PARTS.includes(route.bone) && (route.outputs ?? []).includes(RoutingOutput.DRIVER) ); if (handsAlreadyOnDriver) setHandsWarningAccepted(true); - }, [settings, boneRegistry]); + }, [settings]); useRPCPacket( RpcMessage.BoneRoutingSettingsResponse, @@ -489,7 +453,7 @@ export function BoneRoutingSettings() { const submit = (nextAutomatic: boolean, nextRoutes: RouteMap) => { const req = new ChangeBoneRoutingSettingsRequestT(); req.automatic = nextAutomatic; - req.routes = toBoneRoutes(nextRoutes, boneIdRegistry); + req.routes = toBoneRoutes(nextRoutes); sendRPCPacket(RpcMessage.ChangeBoneRoutingSettingsRequest, req); }; diff --git a/gui/app/src/components/settings/pages/InterfaceSettings.tsx b/gui/app/src/components/settings/pages/InterfaceSettings.tsx index 48392468b..10e1ce07c 100644 --- a/gui/app/src/components/settings/pages/InterfaceSettings.tsx +++ b/gui/app/src/components/settings/pages/InterfaceSettings.tsx @@ -126,7 +126,7 @@ export function InterfaceSettings() { handleResetSounds(values.notifications.feedbackSoundVolume, { resetType: ResetType.FULL, status: ResetStatus.FINISHED, - boneIds: [], + bodyParts: [], progress: 0, duration: 0, }); diff --git a/gui/app/src/components/settings/pages/components/StayAlignedSettings.tsx b/gui/app/src/components/settings/pages/components/StayAlignedSettings.tsx index a9a6f4492..bb6014475 100644 --- a/gui/app/src/components/settings/pages/components/StayAlignedSettings.tsx +++ b/gui/app/src/components/settings/pages/components/StayAlignedSettings.tsx @@ -15,11 +15,7 @@ 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 { - bodyPartOfBone, - boneRegistryAtom, - connectedIMUTrackersAtom, -} from '@/store/app-store'; +import { connectedIMUTrackersAtom } from '@/store/app-store'; import { bodypartToString } from '@/utils/formatting'; import { useLocaleConfig } from '@/i18n/config'; import { useWebsocketAPI } from '@/hooks/websocket-api'; @@ -79,7 +75,6 @@ function CopySettingsButton({ values }: { values: StayAlignedSettingsForm }) { }); const trackers = useAtomValue(connectedIMUTrackersAtom); - const boneRegistry = useAtomValue(boneRegistryAtom); const copySettings = () => { const config = values; @@ -105,7 +100,7 @@ ${trackers const info = t.tracker.info; const stayAligned = t.tracker.stayAligned; if (info && stayAligned) { - return `${bodypartToString(bodyPartOfBone(boneRegistry, info.boneId))}: correction=${numberFormat.format(stayAligned.yawCorrectionInDeg)} locked=${stayAligned.locked}`; + return `${bodypartToString(info.bodyPart)}: correction=${numberFormat.format(stayAligned.yawCorrectionInDeg)} locked=${stayAligned.locked}`; } }) .join('\n')} diff --git a/gui/app/src/components/settings/pages/components/TapDetectionSettings.tsx b/gui/app/src/components/settings/pages/components/TapDetectionSettings.tsx index 1b06c72d5..14fb35055 100644 --- a/gui/app/src/components/settings/pages/components/TapDetectionSettings.tsx +++ b/gui/app/src/components/settings/pages/components/TapDetectionSettings.tsx @@ -18,12 +18,6 @@ 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; @@ -70,8 +64,6 @@ 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', @@ -103,13 +95,9 @@ export function TapDetectionSettings() { settingsReq.yawResetDelay = values.yawResetDelay; settingsReq.yawResetEnabled = values.yawResetEnabled; settingsReq.yawResetTaps = values.yawResetTaps; - settingsReq.yawResetBoneId = - boneIdOfBodyPart(boneIdRegistry, Number(values.yawResetTracker)) ?? null; - settingsReq.mountingResetBoneId = - boneIdOfBodyPart(boneIdRegistry, Number(values.mountingResetTracker)) ?? - null; - settingsReq.fullResetBoneId = - boneIdOfBodyPart(boneIdRegistry, Number(values.fullResetTracker)) ?? null; + settingsReq.yawResetTracker = Number(values.yawResetTracker); + settingsReq.mountingResetTracker = Number(values.mountingResetTracker); + settingsReq.fullResetTracker = Number(values.fullResetTracker); settingsReq.mountingResetEnabled = values.mountingResetEnabled; settingsReq.mountingResetDelay = values.mountingResetDelay; settingsReq.mountingResetTaps = values.mountingResetTaps; @@ -149,24 +137,21 @@ export function TapDetectionSettings() { fullResetTaps: settings.fullResetTaps ?? defaultValues.fullResetTaps, mountingResetTaps: settings.mountingResetTaps ?? defaultValues.mountingResetTaps, - 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, + yawResetTracker: String( + settings.yawResetTracker ?? defaultValues.yawResetTracker + ), + fullResetTracker: String( + settings.fullResetTracker ?? defaultValues.fullResetTracker + ), + mountingResetTracker: String( + settings.mountingResetTracker ?? defaultValues.mountingResetTracker + ), numberTrackersOverThreshold: settings.numberTrackersOverThreshold ?? defaultValues.numberTrackersOverThreshold, }; reset({ ...getValues(), ...formData }); - }, [settings, boneRegistry]); + }, [settings]); useRPCPacket( RpcMessage.TapDetectionSettingsResponse, diff --git a/gui/app/src/components/tracker/DongleSettings.tsx b/gui/app/src/components/tracker/DongleSettings.tsx index 4d615ea44..41ea4aa73 100644 --- a/gui/app/src/components/tracker/DongleSettings.tsx +++ b/gui/app/src/components/tracker/DongleSettings.tsx @@ -20,8 +20,6 @@ import { DongleTelemetry } from './DongleTelemetry'; import { TrackerStatus } from './TrackerStatus'; import { ConnectionGroupIcon } from './TrackerConnectionGroup'; import { - bodyPartOfBone, - boneRegistryAtom, donglesAtom, flatTrackersAtom, groupTrackersByConnection, @@ -71,15 +69,12 @@ export function DongleSettingsPage() { ); const flatTrackers = useAtomValue(flatTrackersAtom); - const boneRegistry = useAtomValue(boneRegistryAtom); const pairedTrackers = useMemo(() => { - const group = groupTrackersByConnection( - flatTrackers, - dongles, - boneRegistry - ).find((g) => g.kind === 'dongle' && g.dongleId === dongleId); + const group = groupTrackersByConnection(flatTrackers, dongles).find( + (g) => g.kind === 'dongle' && g.dongleId === dongleId + ); return group ? [...group.assigned, ...group.unassigned] : []; - }, [flatTrackers, dongles, dongleId, boneRegistry]); + }, [flatTrackers, dongles, dongleId]); const displayName = dongle?.displayName?.toString(); const customName = dongle?.customName?.toString(); @@ -239,10 +234,7 @@ export function DongleSettingsPage() { >
>(new Map()); const colorFor = (deviceId: number): string => { @@ -161,12 +159,10 @@ export function DongleTelemetry({ .filter((t) => t.device) .map((t) => ({ deviceId: t.device!.id, - name: String( - getLocalizedTrackerName(l10n, t.tracker.info, boneRegistry) - ), + name: String(getLocalizedTrackerName(l10n, t.tracker.info)), color: colorFor(t.device!.id), })), - [trackers, l10n, boneRegistry] + [trackers, l10n] ); const trackerKey = list diff --git a/gui/app/src/components/tracker/TrackerCard.tsx b/gui/app/src/components/tracker/TrackerCard.tsx index 9a33db7e5..418fec1f7 100644 --- a/gui/app/src/components/tracker/TrackerCard.tsx +++ b/gui/app/src/components/tracker/TrackerCard.tsx @@ -18,8 +18,6 @@ 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, @@ -29,7 +27,6 @@ function TrackerBig({ device?: DeviceDataT; }) { const { useName } = useTracker(tracker); - const boneRegistry = useAtomValue(boneRegistryAtom); const trackerName = useName(); @@ -37,7 +34,7 @@ function TrackerBig({
@@ -91,7 +88,6 @@ function TrackerSmol({ const { config } = useConfig(); const { useName } = useTracker(tracker); - const boneRegistry = useAtomValue(boneRegistryAtom); const trackerName = useName(); @@ -113,7 +109,7 @@ function TrackerSmol({ )} > (false); const [selectBodyPart, setSelectBodyPart] = useState(false); const { trackernum, deviceid } = useParams<{ @@ -77,7 +72,6 @@ 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); @@ -99,7 +93,7 @@ export function TrackerSettingsPage() { if (trackerName == tracker.tracker.info?.customName) return; const assignReq = new AssignTrackerRequestT(); - assignReq.boneId = tracker?.tracker.info?.boneId ?? 0; + assignReq.bodyPosition = tracker?.tracker.info?.bodyPart || BodyPart.NONE; assignReq.displayName = trackerName ?? null; assignReq.trackerId = tracker?.tracker.trackerId; sendRPCPacket(RpcMessage.AssignTrackerRequest, assignReq); @@ -166,10 +160,10 @@ export function TrackerSettingsPage() { isOpen={selectBodyPart} onClose={() => setSelectBodyPart(false)} onRoleSelected={onRoleSelected} - bodyPart={bodyPart} + bodyPart={tracker?.tracker.info?.bodyPart} /> setSelectRotation(false)} @@ -414,18 +408,22 @@ export function TrackerSettingsPage() {
- {bodyPart !== BodyPart.NONE && ( - + {tracker?.tracker.info?.bodyPart !== BodyPart.NONE && ( + )} - {bodyPart === BodyPart.NONE && ( + {tracker?.tracker.info?.bodyPart === BodyPart.NONE && ( )} - {l10n.getString('body_part-' + BodyPart[bodyPart])} + {l10n.getString( + 'body_part-' + + BodyPart[tracker?.tracker.info?.bodyPart || BodyPart.NONE] + )}
diff --git a/gui/app/src/components/tracker/TrackersTable.tsx b/gui/app/src/components/tracker/TrackersTable.tsx index d269f9aad..182a0bf97 100644 --- a/gui/app/src/components/tracker/TrackersTable.tsx +++ b/gui/app/src/components/tracker/TrackersTable.tsx @@ -20,13 +20,7 @@ import { formatVector3 } from '@/utils/formatting'; import { TrackerBattery } from './TrackerBattery'; import { TrackerStatus } from './TrackerStatus'; import { TrackerWifi } from './TrackerWifi'; -import { - bodyPartOfBone, - boneRegistryAtom, - FlatDeviceTracker, - TrackerConnectionGroup, -} from '@/store/app-store'; -import { useAtomValue } from 'jotai'; +import { FlatDeviceTracker, TrackerConnectionGroup } from '@/store/app-store'; import { ArrowDownIcon, ArrowUpIcon, @@ -41,7 +35,6 @@ import { Tooltip } from '@/components/commons/Tooltip'; import { WarningIcon } from '@/components/commons/icon/WarningIcon'; import { FirmwareIcon } from '@/components/commons/FirmwareIcon'; import { - BodyPart, DeviceDataT, TrackerDataT, TrackerStatus as TrackerStatusEnum, @@ -78,16 +71,11 @@ type SortState = { column: SortColumn; direction: SortDirection } | null; const trackerSortValue = ( { tracker, device }: FlatDeviceTracker, column: SortColumn, - l10n: ReactLocalization, - boneRegistry: Map + l10n: ReactLocalization ): string | number => { switch (column) { case 'name': - return getLocalizedTrackerName( - l10n, - tracker?.info ?? null, - boneRegistry - ).toString(); + return getLocalizedTrackerName(l10n, tracker?.info ?? null).toString(); case 'type': return device?.hardwareInfo?.manufacturer?.toString() || ''; case 'battery': @@ -105,12 +93,11 @@ function compareTrackers( a: FlatDeviceTracker, b: FlatDeviceTracker, sortState: SortState, - l10n: ReactLocalization, - boneRegistry: Map + l10n: ReactLocalization ) { if (!sortState) return 0; - const av = trackerSortValue(a, sortState.column, l10n, boneRegistry); - const bv = trackerSortValue(b, sortState.column, l10n, boneRegistry); + const av = trackerSortValue(a, sortState.column, l10n); + const bv = trackerSortValue(b, sortState.column, l10n); const result = typeof av === 'string' && typeof bv === 'string' ? av.localeCompare(bv) @@ -128,7 +115,6 @@ export function TrackerNameCell({ warning: TrackingChecklistStepT | boolean; }) { const { useName } = useTracker(tracker); - const boneRegistry = useAtomValue(boneRegistryAtom); const name = useName(); @@ -150,7 +136,7 @@ export function TrackerNameCell({ )} > @@ -426,7 +412,6 @@ export function TrackersTable({ const { config } = useConfig(); const { highlightedTrackers } = useTrackingChecklist(); const { l10n } = useLocalization(); - const boneRegistry = useAtomValue(boneRegistryAtom); const [sortState, setSortState] = useState(null); @@ -441,13 +426,13 @@ export function TrackersTable({ const sortedGroups = useMemo(() => { if (!sortState) return groups; const cmp = (a: FlatDeviceTracker, b: FlatDeviceTracker) => - compareTrackers(a, b, sortState, l10n, boneRegistry); + compareTrackers(a, b, sortState, l10n); return groups.map((group) => ({ ...group, assigned: group.assigned.toSorted(cmp), unassigned: group.unassigned.toSorted(cmp), })); - }, [groups, sortState, l10n, boneRegistry]); + }, [groups, sortState, l10n]); const columns = config?.trackersTableColumns ?? defaultTrackersTableColumns; const lastColumn = useMemo(() => lastVisibleColumn(columns), [columns]); diff --git a/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx b/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx index 5fd410839..33c18f2e9 100644 --- a/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx +++ b/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx @@ -41,8 +41,6 @@ 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 }, @@ -181,7 +179,6 @@ function SteamVRDisconnected({ function SteamVRHandsEnabled() { const { sendRPCPacket, useRPCPacket } = useWebsocketAPI(); - const boneRegistry = useAtomValue(boneRegistryAtom); const [routing, setRouting] = useState( null ); @@ -206,10 +203,10 @@ function SteamVRHandsEnabled() { req.routes = (routing.routes ?? []) .map((route) => { const next = new BoneRouteT(); - next.boneId = route.boneId; - const bodyPart = bodyPartOfBone(boneRegistry, route.boneId); + next.bone = route.bone; next.outputs = - bodyPart === BodyPart.LEFT_HAND || bodyPart === BodyPart.RIGHT_HAND + route.bone === BodyPart.LEFT_HAND || + route.bone === BodyPart.RIGHT_HAND ? (route.outputs ?? []).filter( (output) => output !== RoutingOutput.DRIVER ) diff --git a/gui/app/src/components/widgets/SkeletonVisualizerWidget.tsx b/gui/app/src/components/widgets/SkeletonVisualizerWidget.tsx index 995e5192a..a018a1da1 100644 --- a/gui/app/src/components/widgets/SkeletonVisualizerWidget.tsx +++ b/gui/app/src/components/widgets/SkeletonVisualizerWidget.tsx @@ -35,12 +35,7 @@ import { useLocalization } from '@fluent/react'; import { ErrorBoundary } from 'react-error-boundary'; import { Typography } from '@/components/commons/Typography'; import { useAtomValue } from 'jotai'; -import { - assignedTrackersAtom, - bodyPartOfBone, - boneRegistryAtom, - bonesAtom, -} from '@/store/app-store'; +import { assignedTrackersAtom, bonesAtom } from '@/store/app-store'; import { Config, useConfig } from '@/hooks/config'; import { Tween } from '@tweenjs/tween.js'; import { EyeIcon } from '@/components/commons/icon/EyeIcon'; @@ -430,15 +425,17 @@ function SkeletonVisualizer({ const canvasRef = useRef(null); const containerRef = useRef(null); const resizeObserver = useRef(new ResizeObserver(([e]) => onResize(e))); - const bones = useAtomValue(bonesAtom); + const bonesList = 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(); for (const { tracker } of assignedTrackers) { - const bodyPart = bodyPartOfBone(boneRegistry, tracker.info?.boneId); - if (bodyPart === BodyPart.NONE) continue; + const bodyPart = tracker.info?.bodyPart; + if (bodyPart == null || bodyPart === BodyPart.NONE) continue; trackers.set(bodyPart, { trackerId: tracker.trackerId, mountingOrientation: QuaternionFromQuatT( @@ -450,7 +447,7 @@ function SkeletonVisualizer({ }); } return trackers; - }, [assignedTrackers, boneRegistry]); + }, [assignedTrackers]); useEffect(() => { if (bones.size === 0) return; diff --git a/gui/app/src/hooks/app.ts b/gui/app/src/hooks/app.ts index dce2879ce..0009e5b7a 100644 --- a/gui/app/src/hooks/app.ts +++ b/gui/app/src/hooks/app.ts @@ -11,13 +11,7 @@ import { useConfig } from './config'; import { useBonesDataFeedConfig, useDataFeedConfig } from './datafeed-config'; import { useWebsocketAPI } from './websocket-api'; import { useAtomValue, useSetAtom } from 'jotai'; -import { - bodyPartOfBone, - bonesAtom, - boneRegistryAtom, - datafeedAtom, - devicesAtom, -} from '@/store/app-store'; +import { bonesAtom, 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'; @@ -38,7 +32,6 @@ export function useProvideAppContext(): AppContext { const setDatafeed = useSetAtom(datafeedAtom); const setBones = useSetAtom(bonesAtom); const devices = useAtomValue(devicesAtom); - const boneRegistry = useAtomValue(boneRegistryAtom); const [currentFirmwareRelease, setCurrentFirmwareRelease] = useState(null); @@ -55,11 +48,7 @@ export function useProvideAppContext(): AppContext { if (packet.index === 0) { setDatafeed(packet); } else if (packet.index === 1) { - setBones( - new Map( - packet.bones.map((bone) => [bodyPartOfBone(boneRegistry, bone.id), bone]) - ) - ); + setBones(packet.bones); } }); diff --git a/gui/app/src/hooks/datafeed-config.ts b/gui/app/src/hooks/datafeed-config.ts index 610c791fc..c606ef2f8 100644 --- a/gui/app/src/hooks/datafeed-config.ts +++ b/gui/app/src/hooks/datafeed-config.ts @@ -66,6 +66,7 @@ export function useBonesDataFeedConfig() { const dataFeedConfig = new DataFeedConfigT(); const boneMask = new BoneMaskT(); + boneMask.bodyPart = true; boneMask.boneLength = true; boneMask.rotation = false; boneMask.orientation = true; diff --git a/gui/app/src/hooks/reset.ts b/gui/app/src/hooks/reset.ts index 2014c2c55..97d899ac5 100644 --- a/gui/app/src/hooks/reset.ts +++ b/gui/app/src/hooks/reset.ts @@ -9,14 +9,7 @@ import { } from 'solarxr-protocol'; import { useWebsocketAPI } from './websocket-api'; import { useAtomValue } from 'jotai'; -import { - assignedTrackersAtom, - bodyPartOfBone, - boneIdOfBodyPart, - boneIdRegistryAtom, - boneRegistryAtom, - serverGuardsAtom, -} from '@/store/app-store'; +import { assignedTrackersAtom, 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'; @@ -47,8 +40,6 @@ 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(); const [status, setStatus] = useState('idle'); const [progress, setProgress] = useState(0); @@ -59,9 +50,7 @@ export function useReset( const triggerReset = () => { const req = new ResetRequestT(); req.resetType = options.type; - req.boneIds = parts - .map((part) => boneIdOfBodyPart(boneIdRegistry, part)) - .filter((id): id is number => id != null); + req.bodyParts = parts; switch (options.type) { case ResetType.YAW: req.delay = 0; @@ -113,14 +102,11 @@ export function useReset( useRPCPacket( RpcMessage.ResetResponse, - ({ status, resetType, progress, duration, boneIds }: ResetResponseT) => { - const responseBodyParts = (boneIds ?? []).map((id) => - bodyPartOfBone(boneRegistry, id) - ); + ({ status, resetType, progress, duration, bodyParts }: ResetResponseT) => { if ( resetType !== options.type || (resetType == ResetType.POSE_MOUNTING && - JSON.stringify(parts) !== JSON.stringify(responseBodyParts)) + JSON.stringify(parts) !== JSON.stringify(bodyParts)) ) { onResetCanceled(); return; @@ -160,13 +146,11 @@ export function useReset( error = 'reset-error-mounting-need_full_reset'; } else if (options.type === ResetType.POSE_MOUNTING && options.group !== 'default') { if ( - !assignedTrackers.some(({ tracker }) => { - const bodyPart = bodyPartOfBone(boneRegistry, tracker.info?.boneId); - return ( - bodyPart !== BodyPart.NONE && - BODY_PARTS_GROUPS[options.group].includes(bodyPart) - ); - }) + !assignedTrackers.some( + ({ tracker }) => + tracker.info?.bodyPart && + BODY_PARTS_GROUPS[options.group].includes(tracker.info?.bodyPart) + ) ) { disabled = true; error = `reset-error-no_${options.group}_tracker`; diff --git a/gui/app/src/hooks/tracker-assignment.ts b/gui/app/src/hooks/tracker-assignment.ts index 7f52cb7a0..64efaad26 100644 --- a/gui/app/src/hooks/tracker-assignment.ts +++ b/gui/app/src/hooks/tracker-assignment.ts @@ -13,7 +13,7 @@ import { useWebsocketAPI } from './websocket-api'; import { useConfig } from './config'; import { playTapSetupSound } from '@/sounds/sounds'; import { useAtomValue } from 'jotai'; -import { boneIdOfBodyPart, boneIdRegistryAtom, donglesAtom } from '@/store/app-store'; +import { donglesAtom } from '@/store/app-store'; import { hoveredBodyPartAtom } from './tracker-drag'; import { providePicker } from './tracker-picker'; @@ -26,7 +26,6 @@ export type Pending = export function useAssignTracker() { const { sendRPCPacket } = useWebsocketAPI(); - const boneIdRegistry = useAtomValue(boneIdRegistryAtom); return ( trackerId: number, @@ -35,7 +34,7 @@ export function useAssignTracker() { ) => { const request = new AssignTrackerRequestT(); request.trackerId = trackerId; - request.boneId = boneIdOfBodyPart(boneIdRegistry, bodyPart) ?? 0; + request.bodyPosition = bodyPart; request.mountingOrientation = mountingOrientation; sendRPCPacket(RpcMessage.AssignTrackerRequest, request); }; diff --git a/gui/app/src/hooks/tracker-mounting.ts b/gui/app/src/hooks/tracker-mounting.ts index d08bb1558..dfd0ddae9 100644 --- a/gui/app/src/hooks/tracker-mounting.ts +++ b/gui/app/src/hooks/tracker-mounting.ts @@ -6,14 +6,12 @@ import { MountingOrientationDegreesToQuatT, QuaternionFromQuatT, } from '@/maths/quaternion'; -import { bodyPartOfBone, boneRegistryAtom, FlatDeviceTracker } from '@/store/app-store'; +import { 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 @@ -23,7 +21,7 @@ export function useMountingOrientation(td: FlatDeviceTracker | undefined) { const setDirection = (mountingOrientationDegrees: Quaternion) => { if (!td) return; - const bodyPart = bodyPartOfBone(boneRegistry, td.tracker.info?.boneId); + const bodyPart = td.tracker.info?.bodyPart || BodyPart.NONE; const orientation = MountingOrientationDegreesToQuatT(mountingOrientationDegrees); assignTracker(td.tracker.trackerId, bodyPart, orientation); diff --git a/gui/app/src/hooks/tracker.ts b/gui/app/src/hooks/tracker.ts index d946d3f36..d85881e46 100644 --- a/gui/app/src/hooks/tracker.ts +++ b/gui/app/src/hooks/tracker.ts @@ -6,17 +6,14 @@ import { useDataFeedConfig } from './datafeed-config'; import { Quaternion, Vector3 } from 'three'; import { Vector3FromVec3fT } from '@/maths/vector3'; import { useAtomValue } from 'jotai'; -import { bodyPartOfBone, boneRegistryAtom, trackerFromIdAtom } from '@/store/app-store'; +import { trackerFromIdAtom } from '@/store/app-store'; export const getLocalizedTrackerName = ( l10n: ReactLocalization, - info: TrackerInfoT | null, - boneRegistry: Map + info: TrackerInfoT | null ) => { if (info?.customName) return info?.customName; - const bodyPart = bodyPartOfBone(boneRegistry, info?.boneId); - if (bodyPart !== BodyPart.NONE) - return l10n.getString('body_part-' + BodyPart[bodyPart]); + if (info?.bodyPart) return l10n.getString('body_part-' + BodyPart[info?.bodyPart]); return info?.displayName || 'NONE'; }; @@ -33,14 +30,10 @@ 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, boneRegistry), - [tracker.info, l10n, boneRegistry] - ), + useMemo(() => getLocalizedTrackerName(l10n, tracker.info), [tracker.info, l10n]), useRawRotationEulerDegrees: () => useMemo(() => QuaternionToEulerDegrees(tracker?.rotation), [tracker.rotation]), useRefAdjRotationEulerDegrees: () => diff --git a/gui/app/src/hooks/websocket-api.ts b/gui/app/src/hooks/websocket-api.ts index da3cf29ff..33cab72d8 100644 --- a/gui/app/src/hooks/websocket-api.ts +++ b/gui/app/src/hooks/websocket-api.ts @@ -1,32 +1,17 @@ import { createContext, useContext, useEffect, useRef, useState } from 'react'; import { - BodyPart, - BoneRegistryT, - ClientHello, - ConfigurationAcknowledgedT, - ConnectionMessage, - ConnectionMessageHeaderT, DataFeedMessage, DataFeedMessageHeaderT, - HelloStatus, MessageBundle, MessageBundleT, RpcMessage, RpcMessageHeaderT, - ServerHello, } 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'; - -// 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; @@ -45,12 +30,10 @@ export type RPCPacketType = RpcMessageHeaderT['message']; export type DataFeedPacketType = DataFeedMessageHeaderT['message']; export function useProvideWebsocketApi(): WebSocketApi { - const store = useStore(); const rpcPacketCounterRef = useRef(0); const webSocketRef = useRef(null); const rpclistenerRef = useRef(new EventTarget()); const datafeedlistenerRef = useRef(new EventTarget()); - const phaseRef = useRef('awaiting-hello'); const [isFirstConnection, setFirstConnection] = useState(true); const [timedOut, setTimedOut] = useState(false); const [isConnected, setConnected] = useState(false); @@ -68,89 +51,24 @@ export function useProvideWebsocketApi(): WebSocketApi { const onConnected = () => { if (!webSocketRef.current) return; + setFirstConnection(false); setTimedOut(false); - - const fbb = new Builder(64); - ClientHello.finishClientHelloBuffer( - fbb, - ClientHello.createClientHello(fbb, SOLARXR_PROTOCOL_VERSION) - ); - webSocketRef.current.send(fbb.asUint8Array()); + setConnected(true); }; const onConnectionClose = () => { - phaseRef.current = 'awaiting-hello'; - store.set(boneRegistryAtom, new Map()); setConnected(false); rpcPacketCounterRef.current = 0; }; - 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 onMessage = async (event: { data: Blob }) => { if (!event.data.arrayBuffer) return; const buffer = await event.data.arrayBuffer(); + const fbb = new ByteBuffer(new Uint8Array(buffer)); - if (phaseRef.current === 'awaiting-hello') { - if (!ServerHello.bufferHasIdentifier(fbb)) return; - const hello = ServerHello.getRootAsServerHello(fbb); - if (hello.status() !== HelloStatus.ACCEPTED) { - log(`SolarXR handshake rejected (status ${hello.status()}), reconnecting`); - reconnect(); - return; - } - phaseRef.current = 'configuring'; - return; - } - - if (!MessageBundle.bufferHasIdentifier(fbb)) return; const message = MessageBundle.getRootAsMessageBundle(fbb).unpack(); - message.connectionMsgs.forEach((connectionHeader) => { - switch (connectionHeader.messageType) { - case ConnectionMessage.BoneRegistry: { - const registry = connectionHeader.message as BoneRegistryT; - store.set( - boneRegistryAtom, - new Map( - registry.bones.map((bone) => [ - bone.id, - bone.standardBodyPart ?? BodyPart.NONE, - ]) - ) - ); - break; - } - case ConnectionMessage.FinishConfiguration: - sendConnectionMessage( - new ConfigurationAcknowledgedT(), - ConnectionMessage.ConfigurationAcknowledged - ); - 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], { @@ -179,7 +97,7 @@ export function useProvideWebsocketApi(): WebSocketApi { rpcHeader.message = data; message.rpcMsgs = [rpcHeader]; - MessageBundle.finishMessageBundleBuffer(fbb, message.pack(fbb)); + fbb.finish(message.pack(fbb)); webSocketRef.current.send(fbb.asUint8Array()); @@ -200,13 +118,12 @@ export function useProvideWebsocketApi(): WebSocketApi { datafeedHeader.message = data; message.dataFeedMsgs = [datafeedHeader]; - MessageBundle.finishMessageBundleBuffer(fbb, message.pack(fbb)); + fbb.finish(message.pack(fbb)); webSocketRef.current.send(fbb.asUint8Array()); }; const connect = () => { - phaseRef.current = 'awaiting-hello'; webSocketRef.current = new WebSocket(`ws://${targetIp}:${targetPort}`); // Connection opened @@ -223,7 +140,6 @@ export function useProvideWebsocketApi(): WebSocketApi { webSocketRef.current.removeEventListener('message', onMessage); webSocketRef.current.close(); webSocketRef.current = null; - phaseRef.current = 'awaiting-hello'; setConnected(false); }; diff --git a/gui/app/src/store/app-store.ts b/gui/app/src/store/app-store.ts index b4876dd76..2e11614ec 100644 --- a/gui/app/src/store/app-store.ts +++ b/gui/app/src/store/app-store.ts @@ -22,35 +22,7 @@ export const ignoredTrackersAtom = atom(new Set()); export const datafeedAtom = atom(new DataFeedUpdateT()); -// Keyed by BodyPart, resolved from each Bone's registry ID as it arrives (see useProvideAppContext). -export const bonesAtom = atom>(new Map()); -export const boneRegistryAtom = atom>(new Map()); - -export function bodyPartOfBone( - registry: Map, - 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(); - for (const [boneId, bodyPart] of registry) { - if (bodyPart === BodyPart.NONE) continue; - inverse.set(bodyPart, boneId); - } - return inverse; -}); - -export function boneIdOfBodyPart( - idRegistry: Map, - bodyPart: BodyPart -): number | undefined { - return idRegistry.get(bodyPart); -} +export const bonesAtom = atom([]); export const devicesAtom = selectAtom( datafeedAtom, @@ -87,8 +59,7 @@ export type TrackerConnectionGroup = { export function groupTrackersByConnection( trackers: FlatDeviceTracker[], - dongles: DongleDataT[], - boneRegistry: Map + dongles: DongleDataT[] ): TrackerConnectionGroup[] { const dongleByDeviceId = new Map( dongles.flatMap((dongle) => dongle.devicesIds.map((id) => [id, dongle])) @@ -146,8 +117,7 @@ export function groupTrackersByConnection( for (const flatTracker of trackers) { const group = getGroup(flatTracker); - const isUnassigned = - bodyPartOfBone(boneRegistry, flatTracker.tracker.info?.boneId) === BodyPart.NONE; + const isUnassigned = flatTracker.tracker.info?.bodyPart === BodyPart.NONE; const targetList = isUnassigned ? group.unassigned : group.assigned; targetList.push(flatTracker); @@ -192,12 +162,11 @@ export function groupTrackersByDevice( } export function groupTrackerByBodyPart( - trackers: FlatDeviceTracker[], - boneRegistry: Map + trackers: FlatDeviceTracker[] ): Partial> { const byPart: Partial> = {}; trackers.forEach((td) => { - byPart[bodyPartOfBone(boneRegistry, td.tracker.info?.boneId)] = td; + byPart[td.tracker.info?.bodyPart ?? BodyPart.NONE] = td; }); return byPart; } @@ -212,37 +181,22 @@ export const flatTrackersAtom = atom((get) => { export const assignedTrackersAtom = atom((get) => { const trackers = get(flatTrackersAtom); - const boneRegistry = get(boneRegistryAtom); - return trackers.filter( - ({ tracker }) => - bodyPartOfBone(boneRegistry, tracker.info?.boneId) !== BodyPart.NONE - ); + return trackers.filter(({ tracker }) => tracker.info?.bodyPart !== BodyPart.NONE); }); export const trackerByBodyPartAtom = atom((get) => - groupTrackerByBodyPart(get(assignedTrackersAtom), get(boneRegistryAtom)) + groupTrackerByBodyPart(get(assignedTrackersAtom)) ); -const assignedRolesRawAtom = atom((get) => { - const boneRegistry = get(boneRegistryAtom); - return get(assignedTrackersAtom).map(({ tracker }) => - bodyPartOfBone(boneRegistry, tracker.info?.boneId) - ); -}); - export const assignedRolesAtom = selectAtom( - assignedRolesRawAtom, - (parts) => parts, + assignedTrackersAtom, + (trackers) => trackers.map(({ tracker }) => tracker.info?.bodyPart ?? BodyPart.NONE), (a, b) => a.length === b.length && a.every((part, i) => part === b[i]) ); export const unassignedTrackersAtom = atom((get) => { const trackers = get(flatTrackersAtom); - const boneRegistry = get(boneRegistryAtom); - return trackers.filter( - ({ tracker }) => - bodyPartOfBone(boneRegistry, tracker.info?.boneId) === BodyPart.NONE - ); + return trackers.filter(({ tracker }) => tracker.info?.bodyPart === BodyPart.NONE); }); export const connectedTrackersAtom = atom((get) => { diff --git a/gui/app/src/utils/skeletonHelper.ts b/gui/app/src/utils/skeletonHelper.ts index 325f7a99d..346d37da0 100644 --- a/gui/app/src/utils/skeletonHelper.ts +++ b/gui/app/src/utils/skeletonHelper.ts @@ -66,7 +66,6 @@ export interface TrackerPreviewData { } export interface SkeletonRenderPart { - bodyPart: BodyPart; bone: BoneT; tracker?: TrackerPreviewData; } @@ -90,14 +89,14 @@ export class BasedSkeletonHelper extends LineSegments2 { } constructor(bones: Map) { - const parts = [...bones.entries()] - .filter(([bodyPart]) => bodyPart !== BodyPart.NONE) - .map(([bodyPart, bone]) => ({ bodyPart, bone })); + const parts = [...bones.values()] + .filter((bone) => bone.bodyPart !== BodyPart.NONE) + .map((bone) => ({ bone })); const geometry = new LineSegmentsGeometry(); geometry.setPositions(parts.flatMap(() => [0, 0, 0, 0, 0, 0])); geometry.setColors( - parts.flatMap(({ bodyPart }) => { - const color = getBoneColor(bodyPart); + parts.flatMap(({ bone }) => { + const color = getBoneColor(bone.bodyPart); return [color.r, color.g, color.b, color.r, color.g, color.b]; }) ); @@ -114,13 +113,13 @@ export class BasedSkeletonHelper extends LineSegments2 { setBones(bones: Map) { for (const part of this.parts) { - part.bone = bones.get(part.bodyPart) ?? part.bone; + part.bone = bones.get(part.bone.bodyPart) ?? part.bone; } } setTrackers(trackers: Map) { for (const part of this.parts) { - part.tracker = trackers.get(part.bodyPart); + part.tracker = trackers.get(part.bone.bodyPart); if (!part.tracker && part.marker) part.marker.visible = false; } } @@ -129,7 +128,7 @@ export class BasedSkeletonHelper extends LineSegments2 { const vertices: number[] = []; for (const part of this.parts) { - const { bodyPart, bone, tracker } = part; + const { bone, tracker } = part; boneHead.copy(Vector3FromVec3fT(bone.headPosition)); getBoneTail(bone, boneTail); vertices.push(boneHead.x, boneHead.y, boneHead.z); @@ -137,7 +136,7 @@ export class BasedSkeletonHelper extends LineSegments2 { if (!tracker) continue; if (!part.marker) { - const color = getBoneColor(bodyPart); + const color = getBoneColor(bone.bodyPart); part.marker = new Mesh( this.trackerMarkerGeometry, new MeshStandardMaterial({ @@ -154,7 +153,7 @@ export class BasedSkeletonHelper extends LineSegments2 { .normalize() .multiply(tracker.mountingOrientation); part.marker.visible = true; - part.marker.scale.setScalar(getTrackerMarkerScale(bodyPart)); + part.marker.scale.setScalar(getTrackerMarkerScale(bone.bodyPart)); part.marker.quaternion.copy(orientation); part.marker.position.lerpVectors(boneHead, boneTail, tracker.boneOffset); markerOffset.set(0, 0, 0.02).applyQuaternion(orientation); diff --git a/gui/app/src/utils/skeletonMeshHelper.ts b/gui/app/src/utils/skeletonMeshHelper.ts index 44f80e1c2..eca364352 100644 --- a/gui/app/src/utils/skeletonMeshHelper.ts +++ b/gui/app/src/utils/skeletonMeshHelper.ts @@ -94,13 +94,12 @@ export class BasedSkeletonMeshHelper extends Object3D { const m0 = getPartMaterial(new Color('#cccccc')); const m1 = getPartMaterial(new Color('#ad0ccc')); - for (const [bodyPart, bone] of bones.entries()) { - if (bodyPart === BodyPart.NONE) continue; - const config = SKELETON_PART_PRESETS[bodyPart]; + for (const bone of bones.values()) { + if (bone.bodyPart === BodyPart.NONE) continue; + const config = SKELETON_PART_PRESETS[bone.bodyPart]; if (!config.visible) continue; const part: BonePart = { - bodyPart, bone, shapes: [], surfaceDistance: 0, @@ -173,7 +172,7 @@ export class BasedSkeletonMeshHelper extends Object3D { setBones(bones: Map) { for (const part of this.parts) { - const bone = bones.get(part.bodyPart); + const bone = bones.get(part.bone.bodyPart); if (!bone) continue; if (bone.boneLength !== part.bone.boneLength) part.surfaceDirty = true; part.bone = bone; @@ -182,7 +181,7 @@ export class BasedSkeletonMeshHelper extends Object3D { setTrackers(trackers: Map) { for (const part of this.parts) { - const tracker = trackers.get(part.bodyPart); + const tracker = trackers.get(part.bone.bodyPart); if ( tracker?.trackerId !== part.tracker?.trackerId || tracker?.boneOffset !== part.tracker?.boneOffset || @@ -199,7 +198,7 @@ export class BasedSkeletonMeshHelper extends Object3D { updateMatrixWorld(force: boolean) { for (const part of this.parts) { - const { bodyPart, bone, shapes } = part; + const { bone, shapes } = part; position.copy(Vector3FromVec3fT(bone.headPosition)); quat.copy(QuaternionFromQuatT(bone.orientation)).normalize(); @@ -239,7 +238,7 @@ export class BasedSkeletonMeshHelper extends Object3D { } part.marker.visible = true; - part.marker.scale.setScalar(getTrackerMarkerScale(bodyPart)); + part.marker.scale.setScalar(getTrackerMarkerScale(bone.bodyPart)); part.marker.quaternion.copy(quat).multiply(part.tracker.mountingOrientation); part.marker.position.copy(position); localOffset diff --git a/server/android/src/main/java/dev/slimevr/android/ipc/ws-server.kt b/server/android/src/main/java/dev/slimevr/android/ipc/ws-server.kt index 75991d368..4452f69a2 100644 --- a/server/android/src/main/java/dev/slimevr/android/ipc/ws-server.kt +++ b/server/android/src/main/java/dev/slimevr/android/ipc/ws-server.kt @@ -6,9 +6,7 @@ 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.SOLARXR_PROTOCOL_VERSION import dev.slimevr.solarxr.SolarXRBridge -import dev.slimevr.solarxr.checkedSolarXRFrame import dev.slimevr.solarxr.onSolarXRMessage import io.ktor.server.application.install import io.ktor.server.cio.CIO @@ -19,18 +17,11 @@ 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.ClientHello -import solarxr_protocol.HelloStatus import solarxr_protocol.MessageBundle -import solarxr_protocol.ServerHello import java.nio.ByteBuffer -import kotlin.time.Duration.Companion.seconds const val SOLARXR_PORT = 21110 @@ -52,20 +43,13 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider) bridge.outbound.on { bundle -> val fbb = FlatBufferBuilder(256) - bundle.finish(JvmFlatBufferWriter(fbb)) + fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb))) send(Frame.Binary(fin = true, data = fbb.dataBuffer().moveToByteArray())) }.launchIn(this) - val initTimeout = launch { - delay(10.seconds) - if (!bridge.isReady) { - AppLogger.ipc.warn("SolarXR[${bridge.id}] initialization timed out (websocket)") - this@coroutineScope.cancel() - } - } + bridge.startObserving() try { - var awaitingHello = true flow { for (frame in incoming) { when (frame) { @@ -75,23 +59,8 @@ suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider) } } }.collect { bytes -> - val buffer = ByteBuffer.wrap(bytes) - if (awaitingHello) { - val reader = checkedSolarXRFrame(buffer, ClientHello.FILE_IDENTIFIER) - val hello = ClientHello.fromByteBuffer(reader) - val accepted = hello.protocolVersion == SOLARXR_PROTOCOL_VERSION - val fbb = FlatBufferBuilder(64) - ServerHello(if (accepted) HelloStatus.ACCEPTED else HelloStatus.REJECTED_UNSUPPORTED_VERSION, SOLARXR_PROTOCOL_VERSION) - .finish(JvmFlatBufferWriter(fbb)) - send(Frame.Binary(fin = true, data = fbb.dataBuffer().moveToByteArray())) - require(accepted) { "Unsupported SolarXR protocol version ${hello.protocolVersion}" } - awaitingHello = false - bridge.beginConfiguration() - } else { - val reader = checkedSolarXRFrame(buffer, MessageBundle.FILE_IDENTIFIER) - onSolarXRMessage(MessageBundle.fromByteBuffer(reader), bridge) - if (bridge.isReady) initTimeout.cancel() - } + val reader = JvmFlatBufferReader(ByteBuffer.wrap(bytes)) + onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge) } } finally { AppLogger.ipc.info("SolarXR[${bridge.id}] disconnected (websocket)") diff --git a/server/core/src/main/java/dev/slimevr/autobone/functions.kt b/server/core/src/main/java/dev/slimevr/autobone/functions.kt index 6d01621b2..8c5177808 100644 --- a/server/core/src/main/java/dev/slimevr/autobone/functions.kt +++ b/server/core/src/main/java/dev/slimevr/autobone/functions.kt @@ -1,7 +1,6 @@ package dev.slimevr.autobone import dev.slimevr.skeleton.ComputedSkeleton -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -25,7 +24,7 @@ val PLACEHOLDER_BODY_PARTS_TO_ADJUST = arrayOf( 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 @@ -37,9 +36,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 { boneId -> - val boneA = skeletonA[boneId] ?: return@map 0f - val boneB = skeletonB[boneId] ?: return@map 0f + val contributions = PLACEHOLDER_BODY_PARTS_TO_ADJUST.map { bodyPart -> + val boneA = skeletonA[bodyPart] ?: return@map 0f + val boneB = skeletonB[bodyPart] ?: return@map 0f slideContributionWeight( ankleA, diff --git a/server/core/src/main/java/dev/slimevr/bvh/stream.kt b/server/core/src/main/java/dev/slimevr/bvh/stream.kt index 33b9cbccb..5c946c970 100644 --- a/server/core/src/main/java/dev/slimevr/bvh/stream.kt +++ b/server/core/src/main/java/dev/slimevr/bvh/stream.kt @@ -2,13 +2,14 @@ package dev.slimevr.bvh import com.jme3.math.FastMath import dev.slimevr.config.TextFileHandle -import dev.slimevr.skeleton.BoneId +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 @@ -29,7 +30,7 @@ class BvhStream( mutex.withLock { check(!closed) { "BVH stream is closed" } file.write("HIERARCHY\n") - writeBone(bones.registry.root, null, bones, 0) + writeBone(BodyPart.HEAD, null, bones, 0) file.write("MOTION\n") file.write("Frames: ") file.flush() @@ -55,10 +56,10 @@ class BvhStream( } lastFrameTime = now - val head = bones[bones.registry.root] + val head = bones[BodyPart.HEAD] val pos = head?.headPosition ?: Vector3.ZERO file.write("${pos.x * POSITION_SCALE} ${pos.y * POSITION_SCALE} ${pos.z * POSITION_SCALE}") - writeRotations(bones.registry.root, bones) + writeRotations(BodyPart.HEAD, bones) file.write("\n") frameCount++ } @@ -96,44 +97,43 @@ 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(childId: BoneId, parentId: BoneId, bones: ComputedSkeleton): Vector3 { - val parentOffset = bones[parentId]?.offset ?: Vector3.ZERO - val childHeadOffset = bones[childId]?.headOffset ?: Vector3.ZERO + private fun getBvhOffset(childPart: BodyPart, parentPart: BodyPart, bones: ComputedSkeleton): Vector3 { + val parentOffset = bones[parentPart]?.offset ?: Vector3.ZERO + val childHeadOffset = bones[childPart]?.headOffset ?: Vector3.ZERO return (parentOffset + childHeadOffset) * OFFSET_SCALE } - private suspend fun writeRotations(boneId: BoneId, bones: ComputedSkeleton) { - val bone = bones[boneId] + private suspend fun writeRotations(part: BodyPart, bones: ComputedSkeleton) { + val bone = bones[part] 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}") - bones.registry.childrenOf(boneId).forEach { child -> writeRotations(child, bones) } + BODY_PART_HIERARCHY_MAP[part]?.forEach { child -> writeRotations(child, bones) } } - private suspend fun writeBone(boneId: BoneId, parentId: BoneId?, bones: ComputedSkeleton, depth: Int) { + private suspend fun writeBone(part: BodyPart, parent: BodyPart?, bones: ComputedSkeleton, depth: Int) { val indent = "\t".repeat(depth) val childIndent = "\t".repeat(depth + 1) - 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${if (parent == null) "ROOT" else "JOINT"} $part\n") file.write("$indent{\n") - if (parentId == null) { + if (parent == 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(boneId, parentId, bones) + val offset = getBvhOffset(part, parent, bones) file.write("${childIndent}OFFSET ${offset.x} ${offset.y} ${offset.z}\n") file.write("${childIndent}CHANNELS 3 Zrotation Xrotation Yrotation\n") } - val children = bones.registry.childrenOf(boneId) - if (children.isEmpty()) { + val children = BODY_PART_HIERARCHY_MAP[part] + if (children.isNullOrEmpty()) { 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, boneId, bones, depth + 1) } + children.forEach { child -> writeBone(child, part, bones, depth + 1) } } file.write("$indent}\n") } diff --git a/server/core/src/main/java/dev/slimevr/config/serializers.kt b/server/core/src/main/java/dev/slimevr/config/serializers.kt index 9ae5c0a7f..4cc77d94d 100644 --- a/server/core/src/main/java/dev/slimevr/config/serializers.kt +++ b/server/core/src/main/java/dev/slimevr/config/serializers.kt @@ -1,16 +1,21 @@ package dev.slimevr.config import io.github.axisangles.ktmath.Quaternion +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.nullable import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.JsonDecoder import kotlinx.serialization.json.JsonEncoder +import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonPrimitive +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.KeybindId object KeybindIdSerializer : KSerializer { @@ -28,6 +33,28 @@ object KeybindIdSerializer : KSerializer { } } +object BodyPartSerializer : KSerializer { + @OptIn(ExperimentalSerializationApi::class) + override val descriptor = PrimitiveSerialDescriptor("BodyPart", PrimitiveKind.STRING).nullable + + override fun serialize(encoder: Encoder, value: BodyPart?) { + val jsonEncoder = encoder as JsonEncoder + if (value == null) { + jsonEncoder.encodeJsonElement(JsonNull) + } else { + jsonEncoder.encodeJsonElement(JsonPrimitive(value.name)) + } + } + + override fun deserialize(decoder: Decoder): BodyPart? { + val element = (decoder as JsonDecoder).decodeJsonElement() + if (element is JsonNull) return null + return BodyPart.entries.firstOrNull { it.name == element.jsonPrimitive.content } + } +} + +object BodyPartListSerializer : KSerializer> by ListSerializer(BodyPartSerializer) + @Serializable private data class QuaternionSurrogate(val w: Float, val x: Float, val y: Float, val z: Float) diff --git a/server/core/src/main/java/dev/slimevr/config/settings.kt b/server/core/src/main/java/dev/slimevr/config/settings.kt index 6fc6e0bbd..bc673197a 100644 --- a/server/core/src/main/java/dev/slimevr/config/settings.kt +++ b/server/core/src/main/java/dev/slimevr/config/settings.kt @@ -3,7 +3,6 @@ package dev.slimevr.config import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import dev.slimevr.skeleton.inputprocessors.DEFAULT_SPINE_UPPER_LOWER -import dev.slimevr.skeleton.key import io.github.axisangles.ktmath.Quaternion import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -25,7 +24,8 @@ private const val SETTINGS_CONFIG_VERSION = 2 @Serializable data class TrackerConfig( - val bone: String? = null, + @Serializable(with = BodyPartSerializer::class) + val bodyPart: BodyPart? = null, val customName: String? = null, @Serializable(with = QuaternionSerializer::class) val mountingOrientation: Quaternion = Quaternion.IDENTITY, @@ -58,10 +58,8 @@ data class BoneRoutingConfig( /** * Explicit routes. Ignored while [automatic], apart from the overridable bones, which * the user owns in either mode. Do not read directly, use BoneRoutingManager. - * - * Keyed by [dev.slimevr.skeleton.BoneRegistry] key */ - val manualRoutes: Map>? = null, + val manualRoutes: Map>? = null, ) @Serializable @@ -78,9 +76,12 @@ data class TapDetectionConfig( var yawResetEnabled: Boolean = true, var fullResetEnabled: Boolean = true, var mountingResetEnabled: Boolean = true, - var yawResetBone: String? = BodyPart.UPPER_CHEST.key, - var mountingResetBone: String? = BodyPart.RIGHT_UPPER_LEG.key, - var fullResetBone: String? = BodyPart.LEFT_UPPER_LEG.key, + @Serializable(with = BodyPartSerializer::class) + var yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST, + @Serializable(with = BodyPartSerializer::class) + var mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG, + @Serializable(with = BodyPartSerializer::class) + var fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG, var yawResetTaps: Int = 2, var fullResetTaps: Int = 3, var mountingResetTaps: Int = 3, diff --git a/server/core/src/main/java/dev/slimevr/heightcalibration/behaviours.kt b/server/core/src/main/java/dev/slimevr/heightcalibration/behaviours.kt index de95fb0e7..372795dd8 100644 --- a/server/core/src/main/java/dev/slimevr/heightcalibration/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/heightcalibration/behaviours.kt @@ -4,7 +4,6 @@ package dev.slimevr.heightcalibration import dev.slimevr.config.UserConfig import dev.slimevr.config.UserConfigActions -import dev.slimevr.skeleton.boneId import dev.slimevr.skeleton.computeDefaultProportionsByBone import dev.slimevr.tracker.TrackerState import io.github.axisangles.ktmath.Vector3 @@ -65,9 +64,9 @@ private fun isHmdLeveled(snapshot: TrackerSnapshot): Boolean { class BaseCalibrationBehaviour : HeightCalibrationBehaviourType { fun canCalibrate(trackers: List): Boolean { - val hasHmd = trackers.any { it.boneId == BodyPart.HEAD.boneId && it.position != null } + val hasHmd = trackers.any { it.bodyPart == BodyPart.HEAD && it.position != null } val hasHand = trackers.any { - (it.boneId == BodyPart.LEFT_HAND.boneId || it.boneId == BodyPart.RIGHT_HAND.boneId) && it.position != null + (it.bodyPart == BodyPart.LEFT_HAND || it.bodyPart == BodyPart.RIGHT_HAND) && it.position != null } return hasHmd && hasHand } @@ -77,13 +76,13 @@ class BaseCalibrationBehaviour : HeightCalibrationBehaviourType { .flatMapLatest { state -> val trackers = state.trackers.values.toList() if (trackers.isEmpty()) return@flatMapLatest flowOf(false) - // React to per-tracker position/bone changes, not just tracker add/remove. canCalibrate - // only looks at the bone assigned and whether position is set, so dedup on that per - // tracker rather than letting every rotation packet resume the combine. + // React to per-tracker position/bodyPart changes, not just tracker add/remove. canCalibrate + // only looks at bodyPart and whether position is set, so dedup on that per tracker rather + // than letting every rotation packet resume the combine. combine( trackers.map { tracker -> tracker.context.state.distinctUntilChanged { a, b -> - a.boneId == b.boneId && (a.position == null) == (b.position == null) + a.bodyPart == b.bodyPart && (a.position == null) == (b.position == null) } }, ) { states -> canCalibrate(states.toList()) } diff --git a/server/core/src/main/java/dev/slimevr/heightcalibration/module.kt b/server/core/src/main/java/dev/slimevr/heightcalibration/module.kt index dc11c48ae..1f3a27734 100644 --- a/server/core/src/main/java/dev/slimevr/heightcalibration/module.kt +++ b/server/core/src/main/java/dev/slimevr/heightcalibration/module.kt @@ -7,7 +7,6 @@ import dev.slimevr.VRServer import dev.slimevr.config.UserConfig import dev.slimevr.context.Behaviour import dev.slimevr.context.Context -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope @@ -59,7 +58,7 @@ class HeightCalibrationManager( val hmd = state.trackers.values .find { val state = it.context.state.value - state.boneId == BodyPart.HEAD.boneId && state.status == TrackerStatus.OK && state.position != null + state.bodyPart == BodyPart.HEAD && state.status == TrackerStatus.OK && state.position != null } ?: return@flatMapLatest emptyFlow() hmd.context.state.map { s -> @@ -74,7 +73,8 @@ class HeightCalibrationManager( .flatMapLatest { state -> val controllers = state.trackers.values.filter { val state = it.context.state.value - (state.boneId == BodyPart.LEFT_HAND.boneId || state.boneId == BodyPart.RIGHT_HAND.boneId) && state.status == TrackerStatus.OK && state.position != null + val bodyPart = state.bodyPart + (bodyPart == BodyPart.LEFT_HAND || bodyPart == BodyPart.RIGHT_HAND) && state.status == TrackerStatus.OK && state.position != null } if (controllers.isEmpty()) return@flatMapLatest emptyFlow() combine( diff --git a/server/core/src/main/java/dev/slimevr/hid/behaviours/v3/sensor-info.kt b/server/core/src/main/java/dev/slimevr/hid/behaviours/v3/sensor-info.kt index 061c317b1..a81d8aa38 100644 --- a/server/core/src/main/java/dev/slimevr/hid/behaviours/v3/sensor-info.kt +++ b/server/core/src/main/java/dev/slimevr/hid/behaviours/v3/sensor-info.kt @@ -3,7 +3,6 @@ package dev.slimevr.hid.behaviours.v3 import dev.slimevr.hid.HIDReceiver import dev.slimevr.hid.HIDReceiverBehaviour import dev.slimevr.hid.HIDSensorInfo -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.TrackerActions import solarxr_protocol.datatypes.BodyPart @@ -13,14 +12,13 @@ class HIDSensorInfoBehaviour : HIDReceiverBehaviour { if (packet.sensorId != 0) return@on val tracker = receiver.getTracker(packet.hidId) ?: return@on val bodyPart = packet.defaultBodyPosition.takeIf { it != 0 }?.let { BodyPart.fromValue(it.toUByte()) } - val boneId = bodyPart?.boneId tracker.context.dispatch( TrackerActions.Update { copy( imuType = packet.imuType, magStatus = packet.magStatus, completedRestCalibration = true, - intendedBoneId = boneId ?: intendedBoneId, + intendedBodyPart = bodyPart ?: intendedBodyPart, ) }, ) diff --git a/server/core/src/main/java/dev/slimevr/keybind/module.kt b/server/core/src/main/java/dev/slimevr/keybind/module.kt index 6afe72c43..ce1e638ea 100644 --- a/server/core/src/main/java/dev/slimevr/keybind/module.kt +++ b/server/core/src/main/java/dev/slimevr/keybind/module.kt @@ -9,7 +9,6 @@ import dev.slimevr.context.Context import dev.slimevr.resets.ResetsManager import dev.slimevr.skeleton.Skeleton import dev.slimevr.skeleton.SkeletonActions -import dev.slimevr.skeleton.boneId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.delay @@ -24,7 +23,7 @@ import solarxr_protocol.rpc.ResetType private const val KEYBIND_SOURCE = "Keybind" -private val FEET_BONE_IDS = listOf(BodyPart.LEFT_FOOT.boneId, BodyPart.RIGHT_FOOT.boneId) +private val FEET_BODY_PARTS = listOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT) private const val BINDING_SETTLE_MS = 300L @@ -75,7 +74,7 @@ class KeybindTriggerBehaviour( KeybindId.MOUNTING_RESET -> resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.POSE_MOUNTING, delaySeconds) KeybindId.FEET_MOUNTING_RESET -> - resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.POSE_MOUNTING, delaySeconds, FEET_BONE_IDS) + resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.POSE_MOUNTING, delaySeconds, FEET_BODY_PARTS) KeybindId.PAUSE_TRACKING -> { if (delaySeconds > 0f) delay((delaySeconds * 1000).toLong()) diff --git a/server/core/src/main/java/dev/slimevr/resets/module.kt b/server/core/src/main/java/dev/slimevr/resets/module.kt index 9d60714a1..fc46f95ab 100644 --- a/server/core/src/main/java/dev/slimevr/resets/module.kt +++ b/server/core/src/main/java/dev/slimevr/resets/module.kt @@ -9,10 +9,8 @@ import dev.slimevr.config.SettingsActions import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import dev.slimevr.logging.AppLogger -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.Skeleton import dev.slimevr.skeleton.SkeletonActions -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.TrackerActions import dev.slimevr.tracker.getFirstActiveFor import io.github.axisangles.ktmath.Quaternion @@ -45,7 +43,7 @@ data class ResetsState( sealed interface ResetsActions { data class ClearResets(val resetTypes: List) : ResetsActions - data class EndReset(val resetType: ResetType, val boneIds: List? = null, val resetMountingFeet: Boolean = false) : ResetsActions + data class EndReset(val resetType: ResetType, val bodyParts: List? = null, val resetMountingFeet: Boolean = false) : ResetsActions data object ClearMountingCompleted : ResetsActions } @@ -56,25 +54,23 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin fun startObserving() = context.observeAll(this) private var resetJob: Job = Job() - private val registry get() = skeleton.registry /** * Schedules a reset according to the resetType. * resetSourceName is used for logging * If delay is null, the default delay from config will be used. - * If boneIds is null, resets all trackers. + * If bodyParts is null, resets all trackers. */ - suspend fun scheduleReset(resetSourceName: String, resetType: ResetType, delay: Float = 0f, boneIds: List? = null) { + suspend fun scheduleReset(resetSourceName: String, resetType: ResetType, delay: Float = 0f, bodyParts: List? = null) { resetJob.cancelAndJoin() resetJob = context.scope.launch { val delayMs = (delay * 1000).toInt() val fullSeconds = delayMs / 1000 val remainder = delayMs % 1000 - val wireBoneIds = boneIds?.map { it.value } // Tell the GUI we started a reset server.sendSolarxrRpc( - ResetResponse(resetType, ResetStatus.STARTED, wireBoneIds, 0, delayMs), + ResetResponse(resetType, ResetStatus.STARTED, bodyParts, 0, delayMs), ) // Wait for the reset delay while updating the GUI every second @@ -83,14 +79,14 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin // Skip final tick if at the same time as finish if (index != fullSeconds - 1 || remainder != 0) { server.sendSolarxrRpc( - ResetResponse(resetType, ResetStatus.STARTED, wireBoneIds, (index + 1) * 1000, delayMs), + ResetResponse(resetType, ResetStatus.STARTED, bodyParts, (index + 1) * 1000, delayMs), ) } } delay(remainder.toLong()) // Reset trackers - executeTrackerResets(resetType, boneIds, settings.context.state.value.data.resetsConfig) + executeTrackerResets(resetType, bodyParts, settings.context.state.value.data.resetsConfig) if (resetType == ResetType.FULL) { // Tell the skeleton to set the floor level and try resetting the head position (for mocap mode) @@ -101,7 +97,7 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin skeleton.resetProcessors(resetType) // Update state and config - context.dispatch(ResetsActions.EndReset(resetType, boneIds, settings.context.state.value.data.resetsConfig.resetMountingFeet)) + context.dispatch(ResetsActions.EndReset(resetType, bodyParts, settings.context.state.value.data.resetsConfig.resetMountingFeet)) settings.context.dispatch( SettingsActions.Update { copy( @@ -120,7 +116,7 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin // Tell the GUI we finished a reset server.sendSolarxrRpc( - ResetResponse(resetType, ResetStatus.FINISHED, wireBoneIds, delayMs, delayMs), + ResetResponse(resetType, ResetStatus.FINISHED, bodyParts, delayMs, delayMs), ) } } @@ -133,18 +129,18 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin AppLogger.resets.info("Clear Mounting Reset from $resetSourceName") } - private fun executeTrackerResets(resetType: ResetType, boneIds: List? = null, config: ResetsConfig) { + private fun executeTrackerResets(resetType: ResetType, bodyParts: List? = null, config: ResetsConfig) { val allTrackers = server.context.state.value.trackers.values // Filter out the trackers that we want to reset - val trackers = if (!boneIds.isNullOrEmpty()) { + val trackers = if (!bodyParts.isNullOrEmpty()) { allTrackers.filter { - boneIds.contains(it.context.state.value.boneId) + bodyParts.contains(it.context.state.value.bodyPart) } } else { // Exclude feet, fingers and toes from mounting reset except if forced allTrackers.filter { - val bodyPart = it.context.state.value.boneId?.let { id -> registry.bodyPartOf(id) } + val bodyPart = it.context.state.value.bodyPart resetType != ResetType.POSE_MOUNTING || ( (config.resetMountingFeet || bodyPart !in ResetBodyParts.FEET) && @@ -157,7 +153,7 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin val referenceRotation = allTrackers .map { it.context.state.value } .filter { it.position != null } - .getFirstActiveFor(BodyPart.HEAD.boneId) + .getFirstActiveFor(BodyPart.HEAD) ?.rawRotation?.twinNearest(Quaternion.IDENTITY) ?: Quaternion.IDENTITY // Dispatch the reset action to the trackers @@ -166,7 +162,7 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin when (resetType) { ResetType.YAW -> TrackerActions.YawReset(referenceRotation, config.yawResetSmoothTime.toDouble().seconds) ResetType.FULL -> TrackerActions.FullReset(referenceRotation, config.resetPositionalHeadAttitude) - ResetType.POSE_MOUNTING -> TrackerActions.PoseMountingReset(referenceRotation, getYawOffset(it.context.state.value.boneId?.let { id -> registry.bodyPartOf(id) }, config.armsResetMode)) + ResetType.POSE_MOUNTING -> TrackerActions.PoseMountingReset(referenceRotation, getYawOffset(it.context.state.value.bodyPart, config.armsResetMode)) }, ) } diff --git a/server/core/src/main/java/dev/slimevr/resets/reducer.kt b/server/core/src/main/java/dev/slimevr/resets/reducer.kt index 1c568543a..42900b096 100644 --- a/server/core/src/main/java/dev/slimevr/resets/reducer.kt +++ b/server/core/src/main/java/dev/slimevr/resets/reducer.kt @@ -1,11 +1,8 @@ package dev.slimevr.resets -import dev.slimevr.skeleton.boneId import dev.slimevr.util.timeSource import solarxr_protocol.rpc.ResetType -private val FEET_BONE_IDS = ResetBodyParts.FEET.mapTo(mutableSetOf()) { it.boneId } - fun reduce(state: ResetsState, action: ResetsActions): ResetsState = when (action) { // Clear the states of the `canDoXReset`s to false is ResetsActions.ClearResets -> { @@ -24,12 +21,12 @@ fun reduce(state: ResetsState, action: ResetsActions): ResetsState = when (actio ) ResetType.POSE_MOUNTING -> { - val boneIds = action.boneIds - val feetOnly = !boneIds.isNullOrEmpty() && boneIds.all { it in FEET_BONE_IDS } + val bodyParts = action.bodyParts + val feetOnly = !bodyParts.isNullOrEmpty() && bodyParts.all { it in ResetBodyParts.FEET } when { feetOnly -> state.copy(feetMountingResetCompleted = true) - boneIds.isNullOrEmpty() -> state.copy( + bodyParts.isNullOrEmpty() -> state.copy( mountingResetCompleted = true, feetMountingResetCompleted = action.resetMountingFeet || state.feetMountingResetCompleted, ) diff --git a/server/core/src/main/java/dev/slimevr/routing/behaviours.kt b/server/core/src/main/java/dev/slimevr/routing/behaviours.kt index 7ec03f853..7a2ba69bb 100644 --- a/server/core/src/main/java/dev/slimevr/routing/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/routing/behaviours.kt @@ -16,7 +16,6 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo override fun observe(receiver: BoneRoutingManager) { val server = appContext.server val settings = appContext.config.settings - val registry = appContext.skeleton.registry combine( settings.context.state.map { it.data.boneRoutingConfig }.distinctUntilChanged(), @@ -27,7 +26,7 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo if (!config.automatic) { receiver.context.dispatch( BoneRoutingActions.SetRoutes( - effectiveRoutes(manualRoutesAsBoneIds(config.manualRoutes, registry), outputStates, registry), + effectiveRoutes(config.manualRoutes.orEmpty(), outputStates), ), ) } @@ -40,14 +39,13 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo .flatMapLatest { trackers -> if (trackers.isEmpty()) return@flatMapLatest flowOf(emptySet()) - // Tracker state emits on every rotation packet, but only the assigned bone/status - // matter here. Dedup per tracker first, or combine gets resumed once per packet - // per tracker. + // Tracker state emits on every rotation packet, but only bodyPart/status matter here. + // Dedup per tracker first, or combine gets resumed once per packet per tracker. combine( trackers.map { tracker -> - tracker.context.state.distinctUntilChanged { a, b -> a.boneId == b.boneId && a.status == b.status } + tracker.context.state.distinctUntilChanged { a, b -> a.bodyPart == b.bodyPart && a.status == b.status } }, - ) { states -> trackedBodyParts(states.asList(), registry) } + ) { states -> trackedBodyParts(states.asList()) } .distinctUntilChanged() } .map { fineBodyParts -> Triple(config, outputStates, fineBodyParts) } @@ -57,9 +55,8 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo receiver.context.dispatch( BoneRoutingActions.SetRoutes( effectiveRoutes( - computeAutomaticRoutes(candidates, outputStates, registry) + overrideRoutes(config, registry), + computeAutomaticRoutes(candidates, outputStates) + overrideRoutes(config), outputStates, - registry, ), ), ) diff --git a/server/core/src/main/java/dev/slimevr/routing/routing.kt b/server/core/src/main/java/dev/slimevr/routing/routing.kt index 07b5c8219..53fbf216b 100644 --- a/server/core/src/main/java/dev/slimevr/routing/routing.kt +++ b/server/core/src/main/java/dev/slimevr/routing/routing.kt @@ -2,8 +2,6 @@ package dev.slimevr.routing import dev.slimevr.AppContextProvider import dev.slimevr.config.BoneRoutingConfig -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.solarxr.driver.DRIVER_SUPPORTED_BONES import dev.slimevr.tracker.TrackerState import dev.slimevr.util.isActive @@ -22,7 +20,7 @@ import solarxr_protocol.rpc.RoutingOutputState import solarxr_protocol.rpc.VRCOSCOutputState import kotlin.collections.map -typealias Routes = Map> +typealias Routes = Map> typealias OutputStates = Map /** Every output treated as on, for what the user asked for rather than what is sent. */ @@ -55,19 +53,7 @@ val OVERRIDABLE_BONES: Set = setOf(BodyPart.LEFT_HAND, BodyPart.RIGHT_ fun overridableBones(output: RoutingOutput): Set = OVERRIDABLE_BONES intersect acceptedBones(output) subtract requiredBones(output) -/** Resolves a static [BodyPart] set to the [BoneId]s a specific registry gives them. */ -private fun BoneRegistry.idsOf(bodyParts: Set): Set = bodyParts.mapNotNullTo(mutableSetOf()) { this[it] } - -private fun BoneRegistry.acceptedIds(output: RoutingOutput): Set = idsOf(acceptedBones(output)) -private fun BoneRegistry.requiredIds(output: RoutingOutput): Set = idsOf(requiredBones(output)) - -fun manualRoutesAsBoneIds(manualRoutes: Map>?, registry: BoneRegistry): Routes = manualRoutes.orEmpty().mapNotNull { (key, outputs) -> registry[key]?.let { it to outputs } }.toMap() -fun Routes.toManualRoutesConfig(registry: BoneRegistry): Map> = mapNotNull { (boneId, outputs) -> registry.keyOf(boneId)?.let { it to outputs } }.toMap() - -fun overrideRoutes(config: BoneRoutingConfig, registry: BoneRegistry): Routes { - val overridableIds = registry.idsOf(OVERRIDABLE_BONES) - return manualRoutesAsBoneIds(config.manualRoutes, registry).filterKeys { it in overridableIds } -} +fun overrideRoutes(config: BoneRoutingConfig): Routes = config.manualRoutes.orEmpty().filterKeys { it in OVERRIDABLE_BONES } fun isActive(states: OutputStates, output: RoutingOutput): Boolean = states[output] == RoutingOutputState.ACTIVE @@ -121,24 +107,25 @@ fun intendedRoutesFlow(appContext: AppContextProvider): Flow = combine( appContext.config.settings.context.state.map { it.data.boneRoutingConfig }.distinctUntilChanged(), appContext.boneRouting.context.state.map { it.routes }, ) { config, sent -> - val registry = appContext.skeleton.registry - val requested = if (config.automatic) sent else manualRoutesAsBoneIds(config.manualRoutes, registry) - effectiveRoutes(requested + overrideRoutes(config, registry), ALL_ACTIVE, registry) + val requested = if (config.automatic) sent else config.manualRoutes.orEmpty() + effectiveRoutes(requested + overrideRoutes(config), ALL_ACTIVE) }.distinctUntilChanged() /** * What actually gets sent: the requested routes plus whatever each output requires, * minus anything an output cannot accept or cannot currently send. */ -fun effectiveRoutes(routes: Routes, outputStates: OutputStates, registry: BoneRegistry): Routes { - val result = mutableMapOf>() +fun effectiveRoutes(routes: Routes, outputStates: OutputStates): Routes { + val result = mutableMapOf>() for ((bone, outputs) in routes) { - val kept = outputs.filterTo(mutableSetOf()) { isActive(outputStates, it) && bone in registry.acceptedIds(it) } + val kept = outputs.filterTo(mutableSetOf()) { + isActive(outputStates, it) && bone in acceptedBones(it) + } if (kept.isNotEmpty()) result[bone] = kept } for (output in RoutingOutput.entries) { if (!isActive(outputStates, output)) continue - for (bone in registry.requiredIds(output)) { + for (bone in requiredBones(output)) { result[bone] = result[bone].orEmpty() + output } } @@ -149,25 +136,23 @@ fun applyRoutingChange( config: BoneRoutingConfig, automatic: Boolean, routes: Routes, - registry: BoneRegistry, ): BoneRoutingConfig { // Switching modes only flips the switch: each mode keeps the picks left in it. if (automatic != config.automatic) return config.copy(automatic = automatic) val requested = routes - .mapValues { (bone, outputs) -> outputs.filterTo(mutableSetOf()) { bone in registry.acceptedIds(it) && bone !in registry.requiredIds(it) } } + .mapValues { (bone, outputs) -> + outputs.filterTo(mutableSetOf()) { bone in acceptedBones(it) && bone !in requiredBones(it) } + } .filterValues { it.isNotEmpty() } - val overridableIds = registry.idsOf(OVERRIDABLE_BONES) return config.copy( manualRoutes = if (automatic) { // Automatic owns every other bone, so only the overrides come from the request. - ( - manualRoutesAsBoneIds(config.manualRoutes, registry).filterKeys { it !in overridableIds } + - requested.filterKeys { it in overridableIds } - ).toManualRoutesConfig(registry) + config.manualRoutes.orEmpty().filterKeys { it !in OVERRIDABLE_BONES } + + requested.filterKeys { it in OVERRIDABLE_BONES } } else { - requested.toManualRoutesConfig(registry) + requested }, ) } @@ -184,14 +169,14 @@ private val candidateToFineBodyParts = mapOf( ) /** Tracker body parts that count as present. Loopback trackers never enable an output. */ -fun trackedBodyParts(trackers: Collection, registry: BoneRegistry): Set = trackers +fun trackedBodyParts(trackers: Collection): Set = trackers .filter { it.status.isActive() && it.origin != DeviceOrigin.DRIVER && it.origin != DeviceOrigin.VRC && it.origin != DeviceOrigin.VMC } - .map { it.boneId?.let { id -> registry.bodyPartOf(id) } } + .map { it.bodyPart } .toSet() fun determineCandidateBones(fineBodyParts: Set): Set = candidateToFineBodyParts @@ -199,9 +184,9 @@ fun determineCandidateBones(fineBodyParts: Set): Set = cand .keys /** Hands each bone to the best output that is on and can take it, so nothing is sent twice. */ -fun computeAutomaticRoutes(candidateBones: Set, outputStates: OutputStates, registry: BoneRegistry): Routes { +fun computeAutomaticRoutes(candidateBones: Set, outputStates: OutputStates): Routes { val chain = PRIORITY_CHAIN.filter { isActive(outputStates, it) } return candidateBones - .mapNotNull { bone -> chain.firstOrNull { bone in acceptedBones(it) }?.let { output -> registry[bone]?.let { it to setOf(output) } } } + .mapNotNull { bone -> chain.firstOrNull { bone in acceptedBones(it) }?.let { bone to setOf(it) } } .toMap() } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt index c8d8ea1c9..e5e329569 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt @@ -20,6 +20,7 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.ResetType +import java.util.EnumMap import java.util.concurrent.Executors import kotlin.math.cos import kotlin.math.sin @@ -28,15 +29,14 @@ import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.measureTime -class ProportionsBehaviour(private val userConfig: UserConfig, private val registry: BoneRegistry) : SkeletonBehaviour { +class ProportionsBehaviour(private val userConfig: UserConfig) : SkeletonBehaviour { override fun observe(receiver: Skeleton) { userConfig.context.state .distinctUntilChangedBy { it.data.proportions } .map { it.data.proportions } .onEach { proportions -> if (proportions.isNotEmpty()) { - val lengths = configToBoneValues(proportions) - receiver.context.dispatch(SkeletonActions.SetProportions(toBoneOffsets(lengths, registry), lengths.height())) + receiver.context.dispatch(SkeletonActions.SetProportions(configToBoneValues(proportions))) receiver.resetProcessors(ResetType.FULL) } } @@ -78,13 +78,13 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour receiver.context.dispatch( SkeletonActions.SetBoneRotation( - BodyPart.LOWER_CHEST.boneId, + BodyPart.LOWER_CHEST, Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)), ), ) receiver.context.dispatch( SkeletonActions.SetBoneRotation( - BodyPart.LEFT_LOWER_LEG.boneId, + BodyPart.LEFT_LOWER_LEG, Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)), ), ) @@ -95,7 +95,7 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour val jumpHeight = maxOf(0f, sin(elapsed * 3f) * 0.3f) receiver.context.dispatch( SkeletonActions.SetBonePosition( - BodyPart.HEAD.boneId, + BodyPart.HEAD, Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ), ), ) @@ -175,9 +175,6 @@ class ComputedSkeletonBehaviour( val waiter: PreciseWaiter, ) : SkeletonBehaviour { private val intervalDuration = (1.0 / hz).seconds - private val headId = BodyPart.HEAD.boneId - private val constraints = BODY_PART_CONSTRAINT_MAP.resolveToBoneIds() - private val ikChains = resolveIkChains() /** Shortest gap between two tick starts before the later one is pushed to the next slot */ private val minimumGap = intervalDuration * 0.75 @@ -203,7 +200,7 @@ class ComputedSkeletonBehaviour( * map, and the state it came from, untouched. */ private fun runInputProcessors(processors: List, boneInputs: InputSkeleton, skeletonHeight: Float): InputSkeleton { - val bones = boneInputs.copy() + val bones = EnumMap(boneInputs) for (processor in processors) processor.process(bones, skeletonHeight) return bones } @@ -218,8 +215,7 @@ class ComputedSkeletonBehaviour( receiver.context.scope.coroutineContext[Job]?.invokeOnCompletion { dispatcher.close() } var nextTick = timeSource.markNow() - // Sized to the registry this SkeletonState was built for, read once off the data. - val fkChangedParts = BoneSet.of(receiver.context.state.value.boneInputs.registry) + val fkChangedParts = mutableSetOf() val timings = TickTimings(hz, 10.seconds, intervalDuration) receiver.context.scope.launch(dispatcher) { @@ -235,8 +231,8 @@ class ComputedSkeletonBehaviour( // TODO improve pause tracking code // and also possibly head default position (HeadPositionFallbackProcessor) // Use already-processed paused tracking data except for the head - val headBone = requireNotNull(targetState.boneInputs[headId]) { "The registry must define BodyPart.HEAD" } - targetState.pausedProcessedBoneInputs.mutateCopy { it[headId] = headBone.copy(position = if (headBone.isPositionActive) headBone.position else it[headId]?.position) } + val headBone = targetState.boneInputs[BodyPart.HEAD] + targetState.pausedProcessedBoneInputs.mutateCopy { it[BodyPart.HEAD] = headBone?.copy(position = if (headBone.isPositionActive) headBone.position else it[BodyPart.HEAD]?.position) } } else { // Run pre-FK processors // TODO: Add a constrain processor (maybe not needed) @@ -244,7 +240,7 @@ class ComputedSkeletonBehaviour( if (targetState.paused) { // We just paused tracking and this is the last frame before we rely on paused bone inputs // The buffer keeps being written after this, so state gets a copy - receiver.context.dispatch(SkeletonActions.SetPausedBoneInputs(processedInputs.copy())) + receiver.context.dispatch(SkeletonActions.SetPausedBoneInputs(EnumMap(processedInputs))) } processedInputs } @@ -257,22 +253,22 @@ class ComputedSkeletonBehaviour( // Run FK processors. They write into boneInputs, and beforeFk allows figuring out // which bones changed. - val beforeFk = boneInputs.copy() + val beforeFk = BodyPartMap(boneInputs) for (processor in fkProcessors) { processor.process(boneInputs, fk, targetState.floorLevel) // Comparing and filtering the maps allocates an entry per bone each time, so // the changed set is collected in one walk instead fkChangedParts.clear() - for ((boneId, boneInput) in boneInputs) { - val previous = beforeFk[boneId] - if (boneInput == previous) continue - fkChangedParts.add(boneId) - beforeFk[boneId] = boneInput + boneInputs.forEachBone { bodyPart, boneInput -> + val previous = beforeFk[bodyPart] + if (boneInput == previous) return@forEachBone + fkChangedParts.add(bodyPart) + beforeFk[bodyPart] = boneInput // For changed bones with inactive positions, update their input's position in state (needed for Localizer) if (!boneInput.isPositionActive && boneInput.position != previous?.position) { - receiver.context.dispatch(SkeletonActions.SetBonePosition(boneId, boneInput.position, false)) + receiver.context.dispatch(SkeletonActions.SetBonePosition(bodyPart, boneInput.position, false)) } } // Inputs changed; re-run FK @@ -280,17 +276,20 @@ class ComputedSkeletonBehaviour( } // Run IK processors - val ikTargets = BoneMap.of(boneInputs.registry) + val ikTargets = bodyPartMap() for (processor in targetProcessors) processor.process(ikTargets, fk, targetState.floorLevel) // Run IK val ikOutput = ccdIk( boneInputs, fk, - ikTargets.map { (boneId, target) -> - IKChainGoal(ikChains[boneId] ?: listOf(boneId), target) + ikTargets.map { (bodyPart, target) -> + IKChainGoal( + BODY_PART_IK_CHAIN_MAP[bodyPart] ?: listOf(bodyPart), + target, + ) }, - constraints, + BODY_PART_CONSTRAINT_MAP, 0.01f, 100, ) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bodypart-constraints.kt b/server/core/src/main/java/dev/slimevr/skeleton/bodypart-constraints.kt index 1e92f919f..d0fa8499a 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/bodypart-constraints.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/bodypart-constraints.kt @@ -108,15 +108,14 @@ fun constrainOffset( } fun constrainOffsetWithSkeleton( - boneId: BoneId, + bodyPart: BodyPart, offset: Quaternion, bones: ComputedSkeleton, - constraints: Map, + constraints: BodyPartMap, ): Quaternion { - val registry = bones.registry - val constraint = constraints[boneId] ?: return offset - val boneRot = bones[boneId]?.rotation ?: return offset - val parentRot = registry.parentOf(boneId)?.let { parent -> + val constraint = constraints[bodyPart] ?: return offset + val boneRot = bones[bodyPart]?.rotation ?: return offset + val parentRot = parentOf(bodyPart)?.let { parent -> bones[parent]?.rotation } ?: Quaternion.IDENTITY @@ -130,15 +129,14 @@ fun constrainOffsetWithSkeleton( fun constrainSkeleton( bones: InputSkeleton, - constraints: Map, + constraints: BodyPartMap, ): InputSkeleton { - val registry = bones.registry - // Apply constraints top-down, from the root - for ((parentId, boneId) in registry.hierarchyFrom(registry.root)) { - val bone = bones[boneId] ?: continue - val constraint = constraints[boneId] ?: continue - val parentRotation = parentId?.let { bones[it]?.rotation } ?: Quaternion.IDENTITY - bones[boneId] = bone.copy( + // Apply constraints top-down + for ((parentBodyPart, bodyPart) in iterateBodyPartHierarchy()) { + val bone = bones[bodyPart] ?: continue + val constraint = constraints[bodyPart] ?: continue + val parentRotation = bones[parentBodyPart]?.rotation ?: Quaternion.IDENTITY + bones[bodyPart] = bone.copy( rotation = constraint.apply( parentRotation, bone.rotation, diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bodypart-ik-chains.kt b/server/core/src/main/java/dev/slimevr/skeleton/bodypart-ik-chains.kt index dd24e8c5f..04e98fe15 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/bodypart-ik-chains.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/bodypart-ik-chains.kt @@ -2,10 +2,8 @@ package dev.slimevr.skeleton import solarxr_protocol.datatypes.BodyPart -typealias BodyPartChain = List - // TODO Should this be generated from the BodyPart structure using start and end points? -val BODY_PART_IK_CHAIN_MAP: BodyPartMap = BodyPartMap( +val BODY_PART_IK_CHAIN_MAP: BodyPartMap = BodyPartMap( mapOf( BodyPart.HEAD to listOf( BodyPart.NECK, @@ -50,8 +48,3 @@ val BODY_PART_IK_CHAIN_MAP: BodyPartMap = BodyPartMap( ), ), ) - -/** Resolves [BODY_PART_IK_CHAIN_MAP] to [BoneId] once, for a bone that has a chain. */ -fun resolveIkChains(): Map = BODY_PART_IK_CHAIN_MAP.entries.associate { (bodyPart, chain) -> - bodyPart.boneId to chain.map { it.boneId } -} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bodypart-structure.kt b/server/core/src/main/java/dev/slimevr/skeleton/bodypart-structure.kt index d74bc4476..c6191d243 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/bodypart-structure.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/bodypart-structure.kt @@ -2,79 +2,137 @@ package dev.slimevr.skeleton import solarxr_protocol.datatypes.BodyPart -val BODY_PART_HIERARCHY_MAP: Map> = mapOf( - BodyPart.HEAD to arrayOf(BodyPart.NECK), - BodyPart.NECK to arrayOf(BodyPart.UPPER_CHEST, BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER), +val BODY_PART_HIERARCHY_MAP: BodyPartMap> = BodyPartMap( + 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_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.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_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.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.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.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.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.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, + 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, + ), ), ) + +private val BODY_PART_PARENTS: Array = arrayOfNulls(BodyPart.entries.size).also { parents -> + for ((parent, children) in BODY_PART_HIERARCHY_MAP) { + for (child in children) parents[child.ordinal] = parent + } +} + +fun parentOf(bodyPart: BodyPart): BodyPart? = BODY_PART_PARENTS[bodyPart.ordinal] + +inline fun BodyPart.findFirstParent(predicate: (BodyPart) -> Boolean): BodyPart? { + var current = parentOf(this) + while (current != null) { + if (predicate(current)) return current + current = parentOf(current) + } + return null +} + +val headPartSet = setOf(BodyPart.HEAD) +fun highestBodyParts(bodyParts: Set): Set { + if (BodyPart.HEAD in bodyParts) return headPartSet + val result = bodyParts.toMutableSet() + for (bodyPart in bodyParts) { + var parent = parentOf(bodyPart) + while (parent != null) { + if (parent in bodyParts) { + result.remove(bodyPart) + break + } + parent = parentOf(parent) + } + } + return result +} + +private fun buildHierarchy(root: BodyPart, onlyChildren: Boolean): List> { + val result = mutableListOf>() + fun visit(parentBone: BodyPart?, bone: BodyPart, skipSelf: Boolean) { + if (!skipSelf) result += parentBone to bone + val children = BODY_PART_HIERARCHY_MAP[bone] ?: return + for (child in children) visit(bone, child, false) + } + visit(null, root, onlyChildren) + return result +} + +// The hierarchy is constant, so every traversal of it is too. Derived once for the same reason +// BODY_PART_PARENTS is: walking it lazily per call cost a continuation and a Pair per bone, and +// BoneYawFallbackProcessor asks for one per active bone per frame. +private val BODY_PART_HIERARCHIES: Array>> = + Array(ALL_BODY_PARTS.size * 2) { index -> buildHierarchy(ALL_BODY_PARTS[index / 2], index % 2 == 1) } + +fun iterateBodyPartHierarchy( + root: BodyPart = BodyPart.HEAD, + onlyChildren: Boolean = false, +): List> = BODY_PART_HIERARCHIES[root.ordinal * 2 + if (onlyChildren) 1 else 0] diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bone-map.kt b/server/core/src/main/java/dev/slimevr/skeleton/bone-map.kt new file mode 100644 index 000000000..17514620d --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/skeleton/bone-map.kt @@ -0,0 +1,27 @@ +package dev.slimevr.skeleton + +import solarxr_protocol.datatypes.BodyPart +import java.util.EnumMap + +typealias BodyPartMap = EnumMap + +@PublishedApi +internal val ALL_BODY_PARTS: Array = BodyPart.entries.toTypedArray() + +fun bodyPartMap(): BodyPartMap = EnumMap(BodyPart::class.java) + +inline fun BodyPartMap.mutateCopy(block: (BodyPartMap) -> Unit): BodyPartMap = EnumMap(this).also(block) + +inline fun BodyPartMap.mapValues(transform: (BodyPart, V) -> R): BodyPartMap { + val result = bodyPartMap() + for (bodyPart in ALL_BODY_PARTS) { + result[bodyPart] = transform(bodyPart, this[bodyPart] ?: continue) + } + return result +} + +inline fun BodyPartMap.forEachBone(action: (BodyPart, V) -> Unit) { + for (bodyPart in ALL_BODY_PARTS) { + action(bodyPart, this[bodyPart] ?: continue) + } +} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bone-registry.kt b/server/core/src/main/java/dev/slimevr/skeleton/bone-registry.kt deleted file mode 100644 index 058e6f8dc..000000000 --- a/server/core/src/main/java/dev/slimevr/skeleton/bone-registry.kt +++ /dev/null @@ -1,149 +0,0 @@ -package dev.slimevr.skeleton - -import solarxr_protocol.connection.BoneDefinition -import solarxr_protocol.datatypes.BodyPart -import solarxr_protocol.connection.BoneRegistry as WireBoneRegistry - -/** - * 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, - private val byKey: Map, - private val standardIds: Array, - private val childIds: Array, -) { - 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? = standardIds[bodyPart.value.toInt()] - 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 not a standardized bone. */ - fun bodyPartOf(id: BoneId): BodyPart? = this[id]?.standardBodyPart - - /** 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 = (childIds.getOrNull(id.value.toInt()) ?: IntArray(0)).map { BoneId(it.toUShort()) } - - // Hierarchy is fixed for the registry's lifetime, so traversals are too. Memoized lazily - // since the bone set isn't known at compile time. - private val hierarchyCache = arrayOfNulls>>(2 * (maxId + 1)) - fun hierarchyFrom(root: BoneId, onlyChildren: Boolean = false): List> { - val cacheIndex = root.value.toInt() * 2 + if (onlyChildren) 1 else 0 - hierarchyCache[cacheIndex]?.let { return it } - val result = mutableListOf>() - 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) - hierarchyCache[cacheIndex] = result - return result - } - - /** 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(), - standardBodyPart = bodyPart, - ) - }, - ), - ) - } - - 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() - 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(n + 1) - val children = Array(n + 1) { mutableListOf() } - var root: BoneId? = null - val standardIds = arrayOfNulls(UByte.MAX_VALUE.toInt() + 1) - 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 - } - definition.standardBodyPart?.let { bodyPart -> - require(standardIds[bodyPart.value.toInt()] == null) { "Duplicate standard bone $bodyPart" } - standardIds[bodyPart.value.toInt()] = BoneId(definition.id) - } - } - return BoneRegistry( - value = registry, - maxId = n, - root = requireNotNull(root) { "Bone registry has no root" }, - byId = byId, - byKey = registry.bones.associateBy { it.key }, - standardIds = standardIds, - childIds = Array(children.size) { children[it].toIntArray() }, - ) - } - } -} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bones.kt b/server/core/src/main/java/dev/slimevr/skeleton/bones.kt deleted file mode 100644 index 1a92ff91a..000000000 --- a/server/core/src/main/java/dev/slimevr/skeleton/bones.kt +++ /dev/null @@ -1,166 +0,0 @@ -package dev.slimevr.skeleton - -import solarxr_protocol.datatypes.BodyPart -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 = EnumMap - -@PublishedApi -internal val ALL_BODY_PARTS: Array = BodyPart.entries.toTypedArray() - -fun bodyPartMap(): BodyPartMap = EnumMap(BodyPart::class.java) - -inline fun BodyPartMap.mutateCopy(block: (BodyPartMap) -> Unit): BodyPartMap = EnumMap(this).also(block) - -inline fun BodyPartMap.mapValues(transform: (BodyPart, V) -> R): BodyPartMap { - val result = bodyPartMap() - for (bodyPart in ALL_BODY_PARTS) { - result[bodyPart] = transform(bodyPart, this[bodyPart] ?: continue) - } - return result -} - -inline fun BodyPartMap.forEachBone(action: (BodyPart, V) -> Unit) { - for (bodyPart in ALL_BODY_PARTS) { - action(bodyPart, this[bodyPart] ?: continue) - } -} - -/** Converts a [BodyPartMap] to a plain [BoneId]-keyed [Map]; no registry needed since every key is standard. */ -fun BodyPartMap.resolveToBoneIds(): Map = mapKeys { it.key.boneId } - -/** - * 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 private constructor( - val registry: BoneRegistry, - private val array: Array, -) : AbstractMap() { - - 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? = array.getOrNull(key.value.toInt()) as V? - - operator fun set(key: BoneId, value: V) { - array[indexOf(key)] = value - } - - override val entries: Set> - 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 = BoneMap(registry, array.copyOf()) - - companion object { - fun of(registry: BoneRegistry): BoneMap = BoneMap(registry, arrayOfNulls(registry.maxId + 1)) - } -} - -/** Mutates a [copy][BoneMap.copy] of this map, leaving the receiver untouched. */ -inline fun BoneMap.mutateCopy(block: (BoneMap) -> Unit): BoneMap = copy().also(block) - -/** Like the stdlib `mapValues`, but keeps the result a [BoneMap] scoped to the same registry. */ -inline fun BoneMap.mapValues(transform: (BoneId, V) -> R): BoneMap { - val result = BoneMap.of(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` 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() { - 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): 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 = 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): BoneSet = of(registry).also { it.addAll(ids) } - } -} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/centre-of-mass.kt b/server/core/src/main/java/dev/slimevr/skeleton/centre-of-mass.kt index e212ba58a..62070f9f9 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/centre-of-mass.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/centre-of-mass.kt @@ -31,15 +31,9 @@ data class COMState( val acceleration: Vector3, ) -/** Resolves [BODY_PART_MASSES] to [BoneId] once. */ -fun resolveMasses(): Map = buildMap { - for ((bodyPart, mass) in BODY_PART_MASSES) put(bodyPart.boneId, mass) -} - fun centreOfMass( bones: ComputedSkeleton, - masses: Map, -): Vector3 = masses.entries.fold(Vector3.ZERO) { acc: Vector3, massEntry -> +): Vector3 = BODY_PART_MASSES.entries.fold(Vector3.ZERO) { acc: Vector3, massEntry -> val bone = bones[massEntry.key] ?: return@fold acc val boneCentre = (bone.headPosition + bone.tailPosition) / 2f return@fold acc + (boneCentre * massEntry.value) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt b/server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt index c1956174c..01a558740 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt @@ -1,11 +1,13 @@ package dev.slimevr.skeleton.computedprocessors -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.ResettableSkeletonProcessor import dev.slimevr.skeleton.SkeletonComputedProcessor import dev.slimevr.skeleton.Velocity import dev.slimevr.skeleton.ZERO_VELOCITY +import dev.slimevr.skeleton.bodyPartMap +import dev.slimevr.skeleton.forEachBone import dev.slimevr.util.inFloatingSeconds import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion @@ -45,8 +47,8 @@ private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, de class VelocityComputedProcessor : SkeletonComputedProcessor, ResettableSkeletonProcessor { - private val lastVelocities: MutableMap = mutableMapOf() - private val lastVelocityData: MutableMap = mutableMapOf() + private val lastVelocities: BodyPartMap = bodyPartMap() + private val lastVelocityData: BodyPartMap = bodyPartMap() private var lastProcessTime = timeSource.markNow() override fun process(mutableComputedSkeleton: ComputedSkeleton) { @@ -55,9 +57,9 @@ class VelocityComputedProcessor : val deltaTime = (now - lastProcessTime).inFloatingSeconds lastProcessTime = now - for ((boneId, bone) in mutableComputedSkeleton) { - val lastVelocityData = lastVelocityData[boneId] - val lastVelocity = lastVelocities[boneId] ?: ZERO_VELOCITY + mutableComputedSkeleton.forEachBone { part, bone -> + val lastVelocityData = lastVelocityData[part] + val lastVelocity = lastVelocities[part] ?: ZERO_VELOCITY // Compute current velocity val currentVelocityData = VelocityData(bone.rotation, bone.tailPosition) @@ -65,10 +67,10 @@ class VelocityComputedProcessor : // Smooth velocity before setting it val newVelocity = smoothVelocity(currentVelocity, lastVelocity, deltaTime) - mutableComputedSkeleton[boneId] = bone.copy(velocity = newVelocity) + mutableComputedSkeleton[part] = bone.copy(velocity = newVelocity) - this@VelocityComputedProcessor.lastVelocityData[boneId] = currentVelocityData - lastVelocities[boneId] = newVelocity + this@VelocityComputedProcessor.lastVelocityData[part] = currentVelocityData + lastVelocities[part] = newVelocity } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt index ae69e6775..dcef3f2c7 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt @@ -1,12 +1,9 @@ package dev.slimevr.skeleton.fkprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonFkProcessor -import dev.slimevr.skeleton.boneId -import dev.slimevr.tracker.eulerHeading import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -30,16 +27,16 @@ fun correctFootAttitude( ): Quaternion = rotation.interpQ(rotation.eulerHeading(), correctionRatio) class FootPlantFkProcessor(val settings: Settings) : SkeletonFkProcessor { - private val boneIds: Array = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT).map { it.boneId }.toTypedArray() + val bodyParts: Array = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT) override fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { if (!settings.context.state.value.data.skeletonConfig.toggles.footPlant) return - for (boneId in boneIds) { - val input = mutableInputSkeleton[boneId] ?: continue + for (bodyPart in bodyParts) { + val input = mutableInputSkeleton[bodyPart] ?: continue if (input.isRotationActive) continue - val output = fk[boneId] ?: continue - mutableInputSkeleton[boneId] = input.copy( + val output = fk[bodyPart] ?: continue + mutableInputSkeleton[bodyPart] = input.copy( rotation = correctFootAttitude( input.rotation, computeFootPlantRatio( diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt index 2995f207e..9e4bd3282 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt @@ -1,15 +1,12 @@ package dev.slimevr.skeleton.fkprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.ResettableSkeletonProcessor import dev.slimevr.skeleton.SkeletonFkProcessor -import dev.slimevr.skeleton.boneId import dev.slimevr.skeleton.centreOfMass -import dev.slimevr.skeleton.resolveMasses import dev.slimevr.skeleton.targetprocessors.FLOOR_CALIBRATION_OFFSET import dev.slimevr.skeleton.targetprocessors.SKATING_ACCELERATION_THRESHOLD import dev.slimevr.skeleton.targetprocessors.SKATING_LOCK_ENGAGE_PERCENT @@ -44,9 +41,9 @@ private fun isUserSitting(fk: ComputedSkeleton): Boolean { // based on the waist to knee vector decide if the user is sitting or // standing (ie, if the user is sitting the vector will be pointing off // to the side for both feet) - var leftKnee: Vector3 = fk[BodyPart.LEFT_UPPER_LEG.boneId]?.tailPosition ?: return false - var rightKnee: Vector3 = fk[BodyPart.RIGHT_UPPER_LEG.boneId]?.tailPosition ?: return false - val hip: Vector3 = fk[BodyPart.HIP.boneId]?.tailPosition ?: return false + var leftKnee: Vector3 = fk[BodyPart.LEFT_UPPER_LEG]?.tailPosition ?: return false + var rightKnee: Vector3 = fk[BodyPart.RIGHT_UPPER_LEG]?.tailPosition ?: return false + val hip: Vector3 = fk[BodyPart.HIP]?.tailPosition ?: return false leftKnee = hip - leftKnee rightKnee = hip - rightKnee @@ -59,8 +56,8 @@ private fun isUserSitting(fk: ComputedSkeleton): Boolean { // Returns true if either foot's position is below 0 private fun isFootOnGround(fk: ComputedSkeleton): Boolean { - val leftFoot = fk[BodyPart.LEFT_FOOT.boneId] ?: return false - val rightFoot = fk[BodyPart.RIGHT_FOOT.boneId] ?: return false + val leftFoot = fk[BodyPart.LEFT_FOOT] ?: return false + val rightFoot = fk[BodyPart.RIGHT_FOOT] ?: return false return leftFoot.tailPosition.y <= 0f || rightFoot.tailPosition.y <= 0f } @@ -110,8 +107,8 @@ object FootLocalizer { } fun getPlantedFoot(fk: ComputedSkeleton, lastPlantedFoot: PlantedFoot): PlantedFoot { - val leftFoot = fk[BodyPart.LEFT_FOOT.boneId] ?: return PlantedFoot.NONE - val rightFoot = fk[BodyPart.RIGHT_FOOT.boneId] ?: return PlantedFoot.NONE + val leftFoot = fk[BodyPart.LEFT_FOOT] ?: return PlantedFoot.NONE + val rightFoot = fk[BodyPart.RIGHT_FOOT] ?: return PlantedFoot.NONE // If foot is locked, use that if (isFootLocked(leftFoot, lastPlantedFoot)) return PlantedFoot.LEFT @@ -136,8 +133,8 @@ object FootLocalizer { } fun getCurrentFootPosition(fk: ComputedSkeleton, plantedFoot: PlantedFoot) = when (plantedFoot) { - PlantedFoot.LEFT -> fk[BodyPart.LEFT_FOOT.boneId] - PlantedFoot.RIGHT -> fk[BodyPart.RIGHT_FOOT.boneId] + PlantedFoot.LEFT -> fk[BodyPart.LEFT_FOOT] + PlantedFoot.RIGHT -> fk[BodyPart.RIGHT_FOOT] else -> null }?.tailPosition ?: Vector3.ZERO @@ -158,11 +155,13 @@ object HipLocalizer { } object COMLocalizer { + private val TORSO_TRACKERS = setOf(BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.UPPER_WAIST, BodyPart.LOWER_WAIST, BodyPart.HIP) + /** Get the average accel of the torso bones */ - fun getTorsoAccel(inputs: InputSkeleton, torsoBoneIds: Set): Vector3 { + fun getTorsoAccel(inputs: InputSkeleton): Vector3 { var i = 0f - return torsoBoneIds.fold(Vector3.ZERO) { acc, boneId -> - inputs[boneId]?.let { + return TORSO_TRACKERS.fold(Vector3.ZERO) { acc, part -> + inputs[part]?.let { if (it.isAccelerationActive) { i++ acc + it.acceleration @@ -209,10 +208,6 @@ object COMLocalizer { class LocalizerFkProcessor(val settings: Settings) : SkeletonFkProcessor, ResettableSkeletonProcessor { - private val torsoBoneIds: Set = setOf(BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.UPPER_WAIST, BodyPart.LOWER_WAIST, BodyPart.HIP) - .mapTo(mutableSetOf()) { it.boneId } - private val masses = resolveMasses() - private var plantedFoot = FootLocalizer.PlantedFoot.NONE private var targetFoot = Vector3.ZERO @@ -227,7 +222,7 @@ class LocalizerFkProcessor(val settings: Settings) : override fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { if (!settings.context.state.value.data.skeletonConfig.toggles.mocapMode) return - val headInput = mutableInputSkeleton[BodyPart.HEAD.boneId] ?: return + val headInput = mutableInputSkeleton[BodyPart.HEAD] ?: return if (headInput.isPositionActive) return val now = timeSource.markNow() @@ -250,14 +245,14 @@ class LocalizerFkProcessor(val settings: Settings) : } // Compute comVelocity and targetCom - val currentCom = centreOfMass(fk, masses) + val currentCom = centreOfMass(fk) if (followSource != FollowSource.COM) targetCOM = currentCom - val comAccel = COMLocalizer.getTorsoAccel(mutableInputSkeleton, torsoBoneIds) + val comAccel = COMLocalizer.getTorsoAccel(mutableInputSkeleton) comVelocity = COMLocalizer.getCOMVelocity(currentCom, previousCOMs, comVelocity, now, comAccel, deltaTime) targetCOM = COMLocalizer.getTargetCOM(mutableInputSkeleton, fk, targetCOM, comVelocity, deltaTime) - previousCOMs.add(now to centreOfMass(fk, masses)) + previousCOMs.add(now to centreOfMass(fk)) - val currentHip = fk[BodyPart.HIP.boneId]?.tailPosition ?: Vector3.ZERO + val currentHip = fk[BodyPart.HIP]?.tailPosition ?: Vector3.ZERO val travel = when (followSource) { FollowSource.FOOT -> { @@ -303,7 +298,7 @@ class LocalizerFkProcessor(val settings: Settings) : } val newHeadPosition = (headInput.position ?: Vector3.ZERO) + travel - mutableInputSkeleton[BodyPart.HEAD.boneId] = headInput.copy(position = newHeadPosition) + mutableInputSkeleton[BodyPart.HEAD] = headInput.copy(position = newHeadPosition) } override fun reset(resetType: ResetType) { diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt index b66e5dd4f..2aea86d0e 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt @@ -1,12 +1,9 @@ package dev.slimevr.skeleton.fkprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonFkProcessor -import dev.slimevr.skeleton.boneId -import dev.slimevr.tracker.eulerHeading import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart import kotlin.math.abs @@ -49,19 +46,19 @@ fun snapToes( } class ToeSnapFkProcessor(val settings: Settings) : SkeletonFkProcessor { - private val boneIds: Array = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT).map { it.boneId }.toTypedArray() + val bodyParts: Array = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT) override fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { if (!settings.context.state.value.data.skeletonConfig.toggles.toeSnap) return // TODO This loop format should be turned into a function - for (boneId in boneIds) { - val input = mutableInputSkeleton[boneId] ?: continue + for (bodyPart in bodyParts) { + val input = mutableInputSkeleton[bodyPart] ?: continue if (input.isRotationActive) continue val length = input.offset.len() if (length <= 0f) continue - val output = fk[boneId] ?: continue - mutableInputSkeleton[boneId] = input.copy( + val output = fk[bodyPart] ?: continue + mutableInputSkeleton[bodyPart] = input.copy( rotation = snapToes( input.rotation, computeToeSnapRatio( diff --git a/server/core/src/main/java/dev/slimevr/skeleton/ik.kt b/server/core/src/main/java/dev/slimevr/skeleton/ik.kt index 9ec9c018f..28fd166fc 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/ik.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/ik.kt @@ -3,9 +3,13 @@ package dev.slimevr.skeleton import com.jme3.math.FastMath import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 +import solarxr_protocol.datatypes.BodyPart +import java.util.EnumMap +import kotlin.collections.component1 +import kotlin.collections.component2 -fun requireBone(bones: ComputedSkeleton, boneId: BoneId) = requireNotNull(bones[boneId]) { - "The computed skeleton is missing \"${bones.registry[boneId]?.key ?: boneId}\" from the IK chain." +fun requireBone(bones: ComputedSkeleton, bodyPart: BodyPart) = requireNotNull(bones[bodyPart]) { + "The computed skeleton is missing \"${bodyPart}\" from the IK chain." } fun chainDistanceFromTarget( @@ -19,12 +23,12 @@ fun chainDistanceFromTarget( private val oppositeRotation = Quaternion.rotationAroundZAxis(FastMath.PI) fun fromChainToTarget( - boneId: BoneId, + bodyPart: BodyPart, bones: ComputedSkeleton, chain: IKChain, target: Vector3, ): Quaternion? { - val boneHead = requireBone(bones, boneId).headPosition + val boneHead = requireBone(bones, bodyPart).headPosition val chainTail = requireBone(bones, chain.last()).tailPosition val localChainTail = (chainTail - boneHead).unit() @@ -53,11 +57,14 @@ fun rotateChain( chain: IKChain, rotation: Quaternion, ) { - for (boneId in chain) { - val boneInput = requireNotNull(boneInputs[boneId]) { - "The provided bone inputs are missing \"${boneInputs.registry[boneId]?.key ?: boneId}\" from the IK chain." + for (bodyPart in chain) { + boneInputs.compute(bodyPart) { _, boneInput -> + requireNotNull(boneInput) { + "The provided bone inputs are missing \"${bodyPart}\" from the IK chain." + }.copy( + rotation = rotation * boneInput.rotation, + ) } - boneInputs[boneId] = boneInput.copy(rotation = rotation * boneInput.rotation) } } @@ -66,17 +73,17 @@ fun ccdIkIteration( bones: ComputedSkeleton, chain: IKChain, target: Vector3, - constraints: Map?, + constraints: BodyPartMap?, ): ComputedSkeleton { // TODO: Do we need annealing and/or dampening? // The first bone in the chain is the one we are adjusting in this iteration - val boneId = chain.first() - val offset = fromChainToTarget(boneId, bones, chain, target) ?: return bones + val bodyPart = chain.first() + val offset = fromChainToTarget(bodyPart, bones, chain, target) ?: return bones // We only need to constrain the bone that we are adjusting val constrainedOffset = constraints?.let { constrainOffsetWithSkeleton( - boneId, + bodyPart, offset, bones, it, @@ -87,10 +94,10 @@ fun ccdIkIteration( rotateChain(boneInputs, chain, constrainedOffset) // Only build bones for inputs that were changed - return buildBones(boneInputs, BoneSet.of(boneInputs.registry, chain), bones) + return buildBones(boneInputs, chain.toSet(), bones) } -typealias IKChain = List +typealias IKChain = List data class IKChainGoal( val chain: IKChain, val target: Vector3, @@ -105,14 +112,14 @@ fun ccdIk( boneInputs: InputSkeleton, bones: ComputedSkeleton, goals: List, - constraints: Map?, + constraints: BodyPartMap?, threshold: Float, maxIterations: Int, ): IKOutput { // No goals leaves every bone as the FK pass built it, so nothing below needs to run if (goals.isEmpty()) return IKOutput(bones, emptyMap()) - val workingBoneInputs = boneInputs.copy() + val workingBoneInputs = EnumMap(boneInputs) var boneOutputs = bones for (i in 0..maxIterations) { diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt index c0b66975f..1554036e1 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt @@ -1,9 +1,7 @@ package dev.slimevr.skeleton.inputprocessors -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import solarxr_protocol.datatypes.BodyPart /** @@ -11,11 +9,11 @@ import solarxr_protocol.datatypes.BodyPart */ class BoneDirectLinkInputProcessor : SkeletonInputProcessor { /** - * First element is the linked bone. + * First element is the linked BodyPart. * - * Second element is the bone the first element is linked to. + * Second element is the BodyPart the first element is linked to. */ - private val linkedToSource: Array> = arrayOf( + private val linkedToSource = arrayOf( BodyPart.HEAD to BodyPart.NECK, BodyPart.NECK to BodyPart.HEAD, @@ -33,17 +31,17 @@ class BoneDirectLinkInputProcessor : SkeletonInputProcessor { BodyPart.LEFT_HAND to BodyPart.LEFT_LOWER_ARM, BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM, - ).map { (bodyPart, source) -> bodyPart.boneId to source.boneId }.toTypedArray() + ) override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { - for ((boneId, sourceId) in linkedToSource) { - val bone = mutableInputSkeleton[boneId] ?: continue + for ((bodyPart, source) in linkedToSource) { + val bone = mutableInputSkeleton[bodyPart] ?: continue if (bone.isRotationActive) continue - val rotation = mutableInputSkeleton[sourceId]?.rotation ?: continue + val rotation = mutableInputSkeleton[source]?.rotation ?: continue if (rotation == bone.rotation) continue - mutableInputSkeleton[boneId] = bone.copy(rotation = rotation) + mutableInputSkeleton[bodyPart] = bone.copy(rotation = rotation) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt index 711395d95..6b8a615fa 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt @@ -2,7 +2,10 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor +import dev.slimevr.skeleton.forEachBone +import dev.slimevr.skeleton.iterateBodyPartHierarchy import io.github.axisangles.ktmath.Vector3 +import kotlin.collections.set /** * Handles replacing rotations of boneInputs that are not actively receiving data by @@ -10,17 +13,16 @@ import io.github.axisangles.ktmath.Vector3 */ class BoneYawFallbackInputProcessor : SkeletonInputProcessor { override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { - val registry = mutableInputSkeleton.registry - for ((parentId, parentBone) in mutableInputSkeleton) { - if (!parentBone.isRotationActive) continue // Parent needs to be active + mutableInputSkeleton.forEachBone { parentPart, parentBone -> + if (!parentBone.isRotationActive) return@forEachBone // Parent needs to be active val parentYaw = parentBone.rotation.project(Vector3.POS_Y).unit() - for ((_, childId) in registry.hierarchyFrom(parentId, onlyChildren = true)) { - val childBone = mutableInputSkeleton[childId] ?: continue + for (childPart in iterateBodyPartHierarchy(parentPart, true)) { + val childBone = mutableInputSkeleton[childPart.second] ?: continue if (childBone.isRotationActive) continue // Child needs to be inactive if (parentYaw == childBone.rotation) continue - mutableInputSkeleton[childId] = childBone.copy(rotation = parentYaw) + mutableInputSkeleton[childPart.second] = childBone.copy(rotation = parentYaw) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/constraint.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/constraint.kt index ab7f933e9..76440412d 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/constraint.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/constraint.kt @@ -2,18 +2,16 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings import dev.slimevr.skeleton.BODY_PART_CONSTRAINT_MAP -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.Constraint import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor import dev.slimevr.skeleton.constrainSkeleton -import dev.slimevr.skeleton.resolveToBoneIds class ConstraintInputProcessor( val settings: Settings, + val constraints: BodyPartMap = BODY_PART_CONSTRAINT_MAP, ) : SkeletonInputProcessor { - private val constraints: Map = BODY_PART_CONSTRAINT_MAP.resolveToBoneIds() - override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { val skeletonConfig = settings.context.state.value.data.skeletonConfig if (!skeletonConfig.toggles.enforceConstraints) return diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt index 3571d2cc9..6fc512c05 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt @@ -1,9 +1,7 @@ package dev.slimevr.skeleton.inputprocessors -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import solarxr_protocol.datatypes.BodyPart private const val INTERMEDIATE_FROM_PROXIMAL = 2.12f @@ -13,41 +11,27 @@ private const val DISTAL_FROM_PROXIMAL = 3.03f * Handles rotations of inactive finger bones. */ class FingerImputeInputProcessor : SkeletonInputProcessor { - private data class BodyPartFinger( + private data class Finger( val hand: BodyPart, val proximal: BodyPart, val intermediate: BodyPart, val distal: BodyPart, ) - private data class Finger( - val hand: BoneId, - val proximal: BoneId, - val intermediate: BoneId, - val distal: BoneId, + private val fingers = arrayOf( + Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL), + Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_INDEX_PROXIMAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_DISTAL), + Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_MIDDLE_PROXIMAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_DISTAL), + Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_RING_PROXIMAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_DISTAL), + Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_LITTLE_PROXIMAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_DISTAL), + + Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL), + Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL), + Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL), + Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL), + Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL), ) - private val fingers: Array = arrayOf( - BodyPartFinger(BodyPart.LEFT_HAND, BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL), - BodyPartFinger(BodyPart.LEFT_HAND, BodyPart.LEFT_INDEX_PROXIMAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_DISTAL), - BodyPartFinger(BodyPart.LEFT_HAND, BodyPart.LEFT_MIDDLE_PROXIMAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_DISTAL), - BodyPartFinger(BodyPart.LEFT_HAND, BodyPart.LEFT_RING_PROXIMAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_DISTAL), - BodyPartFinger(BodyPart.LEFT_HAND, BodyPart.LEFT_LITTLE_PROXIMAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_DISTAL), - - BodyPartFinger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL), - BodyPartFinger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL), - BodyPartFinger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL), - BodyPartFinger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL), - BodyPartFinger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL), - ).map { finger -> - Finger( - hand = finger.hand.boneId, - proximal = finger.proximal.boneId, - intermediate = finger.intermediate.boneId, - distal = finger.distal.boneId, - ) - }.toTypedArray() - override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { for (finger in fingers) { val handRotation = mutableInputSkeleton[finger.hand]?.rotation ?: continue diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt index c05c9cba1..6d342f851 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt @@ -3,7 +3,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -12,10 +11,10 @@ import solarxr_protocol.datatypes.BodyPart */ class HeadPositionFallbackProcessor(val settings: Settings) : SkeletonInputProcessor { override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { - val headBone = mutableInputSkeleton[BodyPart.HEAD.boneId] ?: return + val headBone = mutableInputSkeleton[BodyPart.HEAD] ?: return if (headBone.position != null) return // Set the head position to the be standing up at the origin - mutableInputSkeleton[BodyPart.HEAD.boneId] = headBone.copy(position = Vector3(0f, skeletonHeight, 0f)) + mutableInputSkeleton[BodyPart.HEAD] = headBone.copy(position = Vector3(0f, skeletonHeight, 0f)) } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt index c47e73708..64f07317b 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt @@ -3,7 +3,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -26,15 +25,15 @@ private fun alignYawRoll(from: Quaternion, to: Quaternion): Quaternion { */ class HipYawRollAlignInputProcessor(val settings: Settings) : SkeletonInputProcessor { override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { - val hipBone = mutableInputSkeleton[BodyPart.HIP.boneId] ?: return + val hipBone = mutableInputSkeleton[BodyPart.HIP] ?: return if (hipBone.isRotationActive) return - val leftUpperLegBone = mutableInputSkeleton[BodyPart.LEFT_UPPER_LEG.boneId] ?: return - val rightUpperLegBone = mutableInputSkeleton[BodyPart.RIGHT_UPPER_LEG.boneId] ?: return + val leftUpperLegBone = mutableInputSkeleton[BodyPart.LEFT_UPPER_LEG] ?: return + val rightUpperLegBone = mutableInputSkeleton[BodyPart.RIGHT_UPPER_LEG] ?: return if (!leftUpperLegBone.isRotationActive || !rightUpperLegBone.isRotationActive) return val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateHipWithUpperLegs val sourceRotation = leftUpperLegBone.rotation.lerpQ(rightUpperLegBone.rotation, 0.5f) val alignedRotation = alignYawRoll(hipBone.rotation, sourceRotation) - mutableInputSkeleton[BodyPart.HIP.boneId] = hipBone.copy(rotation = hipBone.rotation.interpQ(alignedRotation, ratio)) + mutableInputSkeleton[BodyPart.HIP] = hipBone.copy(rotation = hipBone.rotation.interpQ(alignedRotation, ratio)) } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/prediction.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/prediction.kt index bce0aec34..086d09ae3 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/prediction.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/prediction.kt @@ -1,11 +1,12 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.ResettableSkeletonProcessor import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId +import dev.slimevr.skeleton.bodyPartMap +import dev.slimevr.skeleton.forEachBone import dev.slimevr.util.MonotonicValueTimeMark import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion @@ -29,17 +30,17 @@ class PredictionInputProcessor(val settings: Settings) : val lastChange: MonotonicValueTimeMark, ) - private var deltas: MutableMap = mutableMapOf() + private var deltas: BodyPartMap = bodyPartMap() // Used to minimize latency even more for elbow tracking in VR where it is more noticeable. - private fun getMultiplier(boneId: BoneId) = when (boneId) { - BodyPart.LEFT_SHOULDER.boneId, - BodyPart.RIGHT_SHOULDER.boneId, - BodyPart.LEFT_UPPER_ARM.boneId, - BodyPart.RIGHT_UPPER_ARM.boneId, - BodyPart.LEFT_LOWER_ARM.boneId, - BodyPart.RIGHT_LOWER_ARM.boneId, - -> 1.4f + private fun getMultiplier(bodyPart: BodyPart) = when (bodyPart) { + BodyPart.LEFT_SHOULDER, + BodyPart.RIGHT_SHOULDER, + BodyPart.LEFT_UPPER_ARM, + BodyPart.RIGHT_UPPER_ARM, + BodyPart.LEFT_LOWER_ARM, + BodyPart.RIGHT_LOWER_ARM, + -> 1.4f else -> 1f } @@ -54,17 +55,17 @@ class PredictionInputProcessor(val settings: Settings) : } val now = timeSource.markNow() - val newVelocities = mutableMapOf() - for ((boneId, bone) in mutableInputSkeleton) { - if (!bone.isRotationActive) continue + val newVelocities = bodyPartMap() + mutableInputSkeleton.forEachBone { bodyPart, bone -> + if (!bone.isRotationActive) return@forEachBone - val prev = deltas[boneId] + val prev = deltas[bodyPart] if (prev == null) { - newVelocities[boneId] = BoneDelta(bone.rotation, Quaternion.IDENTITY, now) - continue + newVelocities[bodyPart] = BoneDelta(bone.rotation, Quaternion.IDENTITY, now) + return@forEachBone } - val bonePredictionAmount = filteringAmount * getMultiplier(boneId) + val bonePredictionAmount = filteringAmount * getMultiplier(bodyPart) val changed = bone.rotation !== prev.lastRotation val rotationDelta = if (changed) { @@ -74,10 +75,10 @@ class PredictionInputProcessor(val settings: Settings) : prev.rotationDelta } - newVelocities[boneId] = BoneDelta(bone.rotation, rotationDelta, if (changed) now else prev.lastChange) + newVelocities[bodyPart] = BoneDelta(bone.rotation, rotationDelta, if (changed) now else prev.lastChange) val scaledDelta = Quaternion.IDENTITY.lerpR(rotationDelta, bonePredictionAmount).unit() val predicted = (scaledDelta * bone.rotation).unit() - if (predicted != bone.rotation) mutableInputSkeleton[boneId] = bone.copy(rotation = predicted) + if (predicted != bone.rotation) mutableInputSkeleton[bodyPart] = bone.copy(rotation = predicted) } deltas = newVelocities } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/smoothing.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/smoothing.kt index f4e57a88e..eb4eecca7 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/smoothing.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/smoothing.kt @@ -1,10 +1,12 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.ResettableSkeletonProcessor import dev.slimevr.skeleton.SkeletonInputProcessor +import dev.slimevr.skeleton.bodyPartMap +import dev.slimevr.skeleton.forEachBone import dev.slimevr.util.inFloatingSeconds import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion @@ -21,7 +23,7 @@ private const val SMOOTH_MAX = 0.95f class SmoothingInputProcessor(val settings: Settings) : SkeletonInputProcessor, ResettableSkeletonProcessor { - private var smoothed: MutableMap = mutableMapOf() + private var smoothed: BodyPartMap = bodyPartMap() private var lastProcessTime = timeSource.markNow() // TODO this isn't linear. Do we want linear smoothing like in main? @@ -42,14 +44,14 @@ class SmoothingInputProcessor(val settings: Settings) : val smoothingAmount = SMOOTH_MIN + filteringAmount * (SMOOTH_MAX - SMOOTH_MIN) val alpha = ((1 - smoothingAmount) * lastFrameTimeSeconds * SMOOTHING_MULTIPLIER).coerceIn(0f, 1f) - val newSmoothed = mutableMapOf() - for ((boneId, bone) in mutableInputSkeleton) { - if (!bone.isRotationActive) continue + val newSmoothed = bodyPartMap() + mutableInputSkeleton.forEachBone { bodyPart, bone -> + if (!bone.isRotationActive) return@forEachBone - val prev = smoothed[boneId] ?: bone.rotation + val prev = smoothed[bodyPart] ?: bone.rotation val rotation = prev.lerpQ(bone.rotation, alpha).unit() - newSmoothed[boneId] = rotation - if (rotation != bone.rotation) mutableInputSkeleton[boneId] = bone.copy(rotation = rotation) + newSmoothed[bodyPart] = rotation + if (rotation != bone.rotation) mutableInputSkeleton[bodyPart] = bone.copy(rotation = rotation) } smoothed = newSmoothed } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine.kt index 3b417dc05..4c07b62bd 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine.kt @@ -2,10 +2,9 @@ package dev.slimevr.skeleton.inputprocessors import com.jme3.math.FastMath import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart import kotlin.enums.enumEntries @@ -129,6 +128,13 @@ private fun interpolateRatio(fromUpperToLower: Float, curvature: Float, fromReli } // TODO consider interpolating all axes with different ratios +private fun averageRotation(inputSkeleton: InputSkeleton, takeBodyParts: Array = arrayOf()): Quaternion { + val bonesToAverage = inputSkeleton.values.filter { it.bodyPart in takeBodyParts } + return bonesToAverage.map { it.rotation } + .reduceIndexedOrNull { index, acc, rotation -> + acc.lerpQ(rotation, 1f / (index + 1)) + } ?: Quaternion.IDENTITY +} /** * Interpolates between 2 quaternions but with the absolute of the ratio for the twist part. @@ -154,25 +160,10 @@ private fun interpolateAbsTwist(fromRotation: Quaternion, toRotation: Quaternion * of nearby bones. */ class SpineInputProcessor(val settings: Settings) : SkeletonInputProcessor { - private val spineIds: Map> = SPINE_SOURCES.associateWith { source -> - source.parts.map { it.boneId } - } - override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { val ratios = settings.context.state.value.data.skeletonConfig.ratios - - fun boneIdsFor(source: SpineSource) = spineIds.getValue(source) - fun averageRotation(boneIds: List): Quaternion { - val bonesToAverage = boneIds.mapNotNull { mutableInputSkeleton[it] } - return bonesToAverage.map { it.rotation } - .reduceIndexedOrNull { index, acc, rotation -> - acc.lerpQ(rotation, 1f / (index + 1)) - } ?: Quaternion.IDENTITY - } - - val sourceActive = SPINE_SOURCES.associateWith { source -> - boneIdsFor(source).let { it.isNotEmpty() && it.all { id -> mutableInputSkeleton[id]?.isRotationActive == true } } - } + val boneInputs = BodyPartMap(mutableInputSkeleton) + val sourceActive = SPINE_SOURCES.associateWith { it.parts.all { part -> boneInputs[part]?.isRotationActive == true } } val fromTo = SPINE_SOURCE_RELIABILITY.withIndex().associate { (selfIndex, source) -> source.first to getFromTo(selfIndex, sourceActive) } @@ -180,9 +171,9 @@ class SpineInputProcessor(val settings: Settings) : SkeletonInputProcessor { for ((spineIndex, spineSourceReliability) in SPINE_SOURCE_RELIABILITY.withIndex()) { val spineSource = spineSourceReliability.first - // For optimization's sake, assume only one bone per SpineSource we traverse. - val boneId = boneIdsFor(spineSource).firstOrNull() ?: continue - val bone = mutableInputSkeleton[boneId] ?: continue + // For optimization's sake, assume only one BodyPart per SpineSource we traverse. + val bodyPart = spineSource.parts.first() + val bone = boneInputs[bodyPart] ?: continue val isActive = bone.isRotationActive // Get reliabilities mapped to this spine bone @@ -201,24 +192,24 @@ class SpineInputProcessor(val settings: Settings) : SkeletonInputProcessor { } // We are interpolating as-if we were the To, but using self instead of to - val sourceActiveForRatio = isActive || fromIndex == null + val sourceActive = isActive || fromIndex == null // Get the interpolation ratio val interpolateRatio = interpolateRatio( ratios.imputeSpineFromUpperToLower, ratios.imputeSpineCurvature, reliabilities[fromSpineSource] ?: continue, reliabilities[toSpineSource] ?: continue, - sourceActiveForRatio, + sourceActive, ) // If from is null, use to as from and use to's to as to - val fromParts = if (fromIndex != null) boneIdsFor(fromSpineSource) else boneIdsFor(SPINE_SOURCES[toIndex]) - val toParts = boneIdsFor(toSpineSource) + val fromParts = if (fromIndex != null) fromSpineSource.parts else SPINE_SOURCES[toIndex].parts + val toParts = toSpineSource.parts // Interpolate between from and to using our interpolation ratio. - mutableInputSkeleton[boneId] = bone.copy( + mutableInputSkeleton[bodyPart] = bone.copy( rotation = interpolateAbsTwist( - averageRotation(fromParts), - averageRotation(toParts), + averageRotation(boneInputs, fromParts), + averageRotation(boneInputs, toParts), interpolateRatio, ), ) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-active-link.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-active-link.kt index 898f36c15..610a6f223 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-active-link.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-active-link.kt @@ -1,9 +1,7 @@ package dev.slimevr.skeleton.inputprocessors -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import solarxr_protocol.datatypes.BodyPart /** @@ -12,12 +10,12 @@ import solarxr_protocol.datatypes.BodyPart */ class ToeActiveLinkInputProcessor : SkeletonInputProcessor { /** - * First element is the bone whose BoneInput is not actively receiving data. + * First element is the BodyPart whose BoneInput is not actively receiving data. * - * Second element contains a list of bones whose rotation should be used as a fallback prioritized from first to last. + * Second element contains a set of BodyParts whose rotation should be used as a fallback prioritized from first to last. * First active bone will be prioritized. If none are active, the last bone is used. */ - private val toeToSources: Array>> = arrayOf( + private val toeToSources = arrayOf( BodyPart.LEFT_BIG_TOE to arrayOf(BodyPart.LEFT_INDEX_TOE, BodyPart.LEFT_MIDDLE_TOE, BodyPart.LEFT_RING_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_FOOT), BodyPart.LEFT_INDEX_TOE to arrayOf(BodyPart.LEFT_MIDDLE_TOE, BodyPart.LEFT_RING_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_BIG_TOE, BodyPart.LEFT_FOOT), BodyPart.LEFT_MIDDLE_TOE to arrayOf(BodyPart.LEFT_INDEX_TOE, BodyPart.LEFT_RING_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_BIG_TOE, BodyPart.LEFT_FOOT), @@ -29,20 +27,18 @@ class ToeActiveLinkInputProcessor : SkeletonInputProcessor { BodyPart.RIGHT_MIDDLE_TOE to arrayOf(BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_RING_TOE, BodyPart.RIGHT_LITTLE_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT), BodyPart.RIGHT_RING_TOE to arrayOf(BodyPart.RIGHT_MIDDLE_TOE, BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_LITTLE_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT), BodyPart.RIGHT_LITTLE_TOE to arrayOf(BodyPart.RIGHT_RING_TOE, BodyPart.RIGHT_MIDDLE_TOE, BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT), - ).map { (bodyPart, sources) -> - bodyPart.boneId to sources.map { it.boneId }.toTypedArray() - }.toTypedArray() + ) override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { - for ((boneId, sources) in toeToSources) { - val bone = mutableInputSkeleton[boneId] ?: continue + for ((bodyPart, sources) in toeToSources) { + val bone = mutableInputSkeleton[bodyPart] ?: continue if (bone.isRotationActive) continue - val closestActiveBoneOrLast = sources.firstNotNullOfOrNull { id -> - mutableInputSkeleton[id]?.takeIf { it.isRotationActive } - } ?: sources.lastOrNull()?.let { mutableInputSkeleton[it] } ?: continue + val closestActiveBoneOrLast = sources.firstNotNullOfOrNull { part -> + mutableInputSkeleton[part]?.takeIf { it.isRotationActive } + } ?: mutableInputSkeleton[sources.last()] ?: continue - mutableInputSkeleton[boneId] = bone.copy(rotation = closestActiveBoneOrLast.rotation) + mutableInputSkeleton[bodyPart] = bone.copy(rotation = closestActiveBoneOrLast.rotation) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt index 9e8beb9a2..e6d6ec3d4 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt @@ -1,10 +1,8 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -27,27 +25,27 @@ private fun alignRoll(from: Quaternion, to: Quaternion): Quaternion { */ class UpperLegsRollAlignInputProcessor(val settings: Settings) : SkeletonInputProcessor { /** - * First value is the bone to be aligned. + * First value is the BodyPart to be aligned. * - * Second value is a source bone. + * Second value is a source BodyPart */ - private val boneToSources: Array> = arrayOf( + private val bodyPartToSources = arrayOf( BodyPart.LEFT_UPPER_LEG to BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_LOWER_LEG, - ).map { (bodyPart, source) -> bodyPart.boneId to source.boneId }.toTypedArray() + ) override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) { val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs if (ratio == 0f) return // Upper legs are written, lower legs are read, so the two never overlap - for ((boneId, sourceId) in boneToSources) { - val bone = mutableInputSkeleton[boneId] ?: continue + for (bodyPartToSource in bodyPartToSources) { + val bone = mutableInputSkeleton[bodyPartToSource.first] ?: continue if (!bone.isRotationActive) continue - val sourceRotation = mutableInputSkeleton[sourceId]?.rotation ?: continue + val sourceRotation = mutableInputSkeleton[bodyPartToSource.second]?.rotation ?: continue val alignedRotation = alignRoll(bone.rotation, sourceRotation) - mutableInputSkeleton[boneId] = bone.copy(rotation = bone.rotation.interpR(alignedRotation, ratio)) + mutableInputSkeleton[bodyPartToSource.first] = bone.copy(rotation = bone.rotation.interpR(alignedRotation, ratio)) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/module.kt b/server/core/src/main/java/dev/slimevr/skeleton/module.kt index 39717629b..095119417 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/module.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/module.kt @@ -26,7 +26,9 @@ import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.ResetType +import solarxr_protocol.rpc.SkeletonBone data class Velocity( /** In meters/s */ @@ -39,7 +41,7 @@ val ZERO_VELOCITY = Velocity(Vector3.ZERO, Vector3.ZERO) /** Pre-FK */ data class BoneInput( - val boneId: BoneId, + val bodyPart: BodyPart, val headOffset: Vector3, val offset: Vector3, val rotation: Quaternion, @@ -53,7 +55,7 @@ data class BoneInput( /** Post-FK */ data class BoneState( val parentBone: BoneState?, - val boneId: BoneId, + val bodyPart: BodyPart, val headOffset: Vector3, val offset: Vector3, val rotation: Quaternion, @@ -81,8 +83,8 @@ data class BoneState( get() = tailPosition - headPosition } -typealias InputSkeleton = BoneMap -typealias ComputedSkeleton = BoneMap +typealias InputSkeleton = BodyPartMap +typealias ComputedSkeleton = BodyPartMap data class SkeletonState( val boneInputs: InputSkeleton, @@ -93,7 +95,7 @@ data class SkeletonState( ) val DEFAULT_BONE_INPUT = BoneInput( - boneId = BoneId(0u), + bodyPart = BodyPart.NONE, headOffset = Vector3.ZERO, offset = Vector3.ZERO, rotation = Quaternion.IDENTITY, @@ -104,13 +106,13 @@ val DEFAULT_BONE_INPUT = BoneInput( isPositionActive = false, ) -fun defaultSkeletonState(registry: BoneRegistry): SkeletonState { - val offsets = toBoneOffsets(DEFAULT_PROPORTIONS, registry) - return SkeletonState( - boneInputs = offsets.tail.mapValues { boneId, tailOffset -> +val DEFAULT_SKELETON_STATE = run { + val offsets = toBoneOffsets(DEFAULT_PROPORTIONS) + SkeletonState( + boneInputs = offsets.tail.mapValues { bodyPart, tailOffset -> DEFAULT_BONE_INPUT.copy( - boneId = boneId, - headOffset = offsets.head[boneId] ?: Vector3.ZERO, + bodyPart = bodyPart, + headOffset = offsets.head[bodyPart] ?: Vector3.ZERO, offset = tailOffset, ) }, @@ -122,12 +124,12 @@ fun defaultSkeletonState(registry: BoneRegistry): SkeletonState { } fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO_VELOCITY): BoneState { - // Raw position of the bone input is used for a root bone since it has no parent + // Raw position of the bone input is used for BodyPart.HEAD since it has no parent val headPosition = parentBone?.let { it.tailPosition + it.rotation.sandwich(bone.headOffset) } ?: bone.position ?: Vector3.ZERO return BoneState( parentBone = parentBone, - boneId = bone.boneId, + bodyPart = bone.bodyPart, headOffset = bone.headOffset, offset = bone.offset, rotation = bone.rotation, @@ -143,30 +145,25 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO * * If changedParts is used, pass lastResult to fill in the gaps that won't be re-computed. */ -fun buildBones( - boneInputs: InputSkeleton, - changedParts: BoneSet = boneInputs.registry.rootSet, - lastResult: ComputedSkeleton = BoneMap.of(boneInputs.registry), -): ComputedSkeleton { - val registry = boneInputs.registry +fun buildBones(boneInputs: InputSkeleton, changedParts: Set = headPartSet, lastResult: BodyPartMap = bodyPartMap()): ComputedSkeleton { return lastResult.mutateCopy { result -> - for (boneId in registry.highest(changedParts)) { - val parent = registry.parentOf(boneId) - registry.hierarchyFrom(parent ?: boneId, onlyChildren = parent != null).forEach { (parentId, childId) -> - val rawBone = boneInputs[childId] ?: return@forEach - val parentBone = parentId?.let { result[it] } - result[childId] = buildBone(rawBone, parentBone, result[childId]?.velocity ?: ZERO_VELOCITY) + for (bodyPart in highestBodyParts(changedParts)) { + iterateBodyPartHierarchy(parentOf(bodyPart) ?: bodyPart, bodyPart != BodyPart.HEAD).forEach { (parentPart, childPart) -> + val rawBone = boneInputs[childPart] ?: return@forEach + val parentBone = parentPart?.let { result[it] } + // Velocity is written directly during the skeleton loop computed bones; keep it. + result[childPart] = buildBone(rawBone, parentBone, result[childPart]?.velocity ?: ZERO_VELOCITY) } } } } sealed interface SkeletonActions { - data class SetBoneRotation(val boneId: BoneId, val rotation: Quaternion, val setActive: Boolean = true) : SkeletonActions - data class SetBoneAcceleration(val boneId: BoneId, val acceleration: Vector3, val setActive: Boolean = true) : SkeletonActions - data class SetBonePosition(val boneId: BoneId, val position: Vector3?, val setActive: Boolean = true) : SkeletonActions - data class DisableBone(val boneId: BoneId) : SkeletonActions - data class SetProportions(val boneOffsets: BoneOffsets, val skeletonHeight: Float) : SkeletonActions + data class SetBoneRotation(val bodyPart: BodyPart, val rotation: Quaternion, val setActive: Boolean = true) : SkeletonActions + data class SetBoneAcceleration(val bodyPart: BodyPart, val acceleration: Vector3, val setActive: Boolean = true) : SkeletonActions + data class SetBonePosition(val bodyPart: BodyPart, val position: Vector3?, val setActive: Boolean = true) : SkeletonActions + data class DisableBone(val bodyPart: BodyPart) : SkeletonActions + data class SetProportions(val lengths: Map) : SkeletonActions data class PauseTracking(val pause: Boolean) : SkeletonActions data class SetPausedBoneInputs(val pausedBoneInputs: InputSkeleton) : SkeletonActions data object ResetHeadPosition : SkeletonActions @@ -188,7 +185,7 @@ interface SkeletonFkProcessor { interface SkeletonComputedProcessor { fun process(mutableComputedSkeleton: ComputedSkeleton) } -typealias IKTargets = BoneMap +typealias IKTargets = BodyPartMap interface SkeletonTargetProcessor { fun process(mutableIkTargets: IKTargets, fk: ComputedSkeleton, floorLevel: Float) } @@ -200,10 +197,6 @@ class Skeleton( ) { val currentComputed: ComputedSkeleton get() = computed.replayCache.first() - // Reads off boneInputs so registry and state always agree, even if a future registry - // swap is added later - val registry: BoneRegistry get() = context.state.value.boneInputs.registry - fun startObserving() = context.observeAll(this) fun resetProcessors(resetType: ResetType) { @@ -215,11 +208,10 @@ class Skeleton( fun create(scope: CoroutineScope, ctx: Phase1ContextProvider, waiter: PreciseWaiter, hz: Int = DEFAULT_HZ): Skeleton { val settings = ctx.config.settings - val registry = BoneRegistry.standard() val resettableSkeletonProcessors = mutableSetOf() val behaviours = listOf( - ProportionsBehaviour(ctx.config.userConfig, registry), + ProportionsBehaviour(ctx.config.userConfig), HeightLogBehaviour(), LocalizerResetBehaviour(settings), // YouSpinMeRightRoundBehaviour(inputHz = 50f), @@ -258,16 +250,17 @@ class Skeleton( ) val context = Context.create( - initialState = defaultSkeletonState(registry), + initialState = DEFAULT_SKELETON_STATE, scope = scope, reducer = ::reduce, behaviours = behaviours, name = "Skeleton", ) - // Replay one sample for late subscribers. Non-blocking: a slow driver misses a - // pose instead of stalling this thread, which has nothing else to do. - val computed = MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) + val computed = MutableSharedFlow( + replay = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) computed.tryEmit(buildBones(context.state.value.boneInputs)) return Skeleton(context, computed, resettableSkeletonProcessors) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt b/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt index 527abecfa..f558ff6f1 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt @@ -112,34 +112,24 @@ fun computeAllDefaultProportionsByBone(height: Float): Map { // Resolved bone geometry for a set of proportions. tail is the head->tail vector in the bone's own // frame; head is the parent-tail->head vector in the parent's frame (Vector3.ZERO for most bones). data class BoneOffsets( - val tail: BoneMap, - val head: BoneMap, + val tail: BodyPartMap, + val head: BodyPartMap, ) -fun toBoneOffsets(lengths: Map, registry: BoneRegistry): BoneOffsets { - val tail = BoneMap.of(registry) - val head = BoneMap.of(registry) +fun toBoneOffsets(lengths: Map): BoneOffsets { + val tail = bodyPartMap() + val head = bodyPartMap() for ((cfg, length) in lengths) { - BONE_VALUE_TO_OFFSETS[cfg]?.let { - for ((bodyPart, vec) in it) { - val id = bodyPart.boneId - tail[id] = (tail[id] ?: Vector3.ZERO) + length * vec - } - } - BONE_VALUE_TO_HEAD_OFFSETS[cfg]?.let { - for ((bodyPart, vec) in it) { - val id = bodyPart.boneId - head[id] = (head[id] ?: Vector3.ZERO) + length * vec - } - } + BONE_VALUE_TO_OFFSETS[cfg]?.let { for ((bone, vec) in it) tail[bone] = (tail[bone] ?: Vector3.ZERO) + length * vec } + BONE_VALUE_TO_HEAD_OFFSETS[cfg]?.let { for ((bone, vec) in it) head[bone] = (head[bone] ?: Vector3.ZERO) + length * vec } } - lengths[SkeletonBone.HAND_Y]?.let { handY -> - for ((bodyPart, vec) in getFingerOffsets(handY)) tail[bodyPart.boneId] = vec - for ((bodyPart, vec) in getFingerHeadOffsets(handY)) head[bodyPart.boneId] = vec + lengths[SkeletonBone.HAND_Y]?.let { + tail.putAll(getFingerOffsets(it)) + head.putAll(getFingerHeadOffsets(it)) } - lengths[SkeletonBone.FOOT_LENGTH]?.let { footLength -> - for ((bodyPart, vec) in getToeOffsets(footLength)) tail[bodyPart.boneId] = vec - for ((bodyPart, vec) in getToeHeadOffsets(footLength)) head[bodyPart.boneId] = vec + lengths[SkeletonBone.FOOT_LENGTH]?.let { + tail.putAll(getToeOffsets(it)) + head.putAll(getToeHeadOffsets(it)) } return BoneOffsets(tail, head) } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/reducer.kt b/server/core/src/main/java/dev/slimevr/skeleton/reducer.kt index 0ab88b20a..f0a825bf7 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/reducer.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/reducer.kt @@ -6,25 +6,25 @@ import solarxr_protocol.datatypes.BodyPart fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) { is SkeletonActions.SetBoneRotation -> { - val bone = state.boneInputs[action.boneId] ?: return state - state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.boneId] = bone.copy(rotation = action.rotation, isRotationActive = action.setActive) }) + val bone = state.boneInputs[action.bodyPart] ?: return state + state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.bodyPart] = bone.copy(rotation = action.rotation, isRotationActive = action.setActive) }) } is SkeletonActions.SetBoneAcceleration -> { - val bone = state.boneInputs[action.boneId] ?: return state - state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.boneId] = bone.copy(acceleration = action.acceleration, isAccelerationActive = action.setActive) }) + val bone = state.boneInputs[action.bodyPart] ?: return state + state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.bodyPart] = bone.copy(acceleration = action.acceleration, isAccelerationActive = action.setActive) }) } is SkeletonActions.SetBonePosition -> { - val bone = state.boneInputs[action.boneId] ?: return state - state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.boneId] = bone.copy(position = action.position, isPositionActive = action.setActive) }) + val bone = state.boneInputs[action.bodyPart] ?: return state + state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.bodyPart] = bone.copy(position = action.position, isPositionActive = action.setActive) }) } is SkeletonActions.DisableBone -> { - val bone = state.boneInputs[action.boneId] ?: return state + val bone = state.boneInputs[action.bodyPart] ?: return state state.copy( boneInputs = state.boneInputs.mutateCopy { - it[action.boneId] = bone.copy( + it[action.bodyPart] = bone.copy( rotation = Quaternion.IDENTITY, acceleration = Vector3.ZERO, position = null, @@ -37,13 +37,14 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when } is SkeletonActions.SetProportions -> { - val newBones = state.boneInputs.mapValues { boneId, bone -> + val offsets = toBoneOffsets(action.lengths) + val newBones = state.boneInputs.mapValues { bodyPart, bone -> bone.copy( - headOffset = action.boneOffsets.head[boneId] ?: bone.headOffset, - offset = action.boneOffsets.tail[boneId] ?: bone.offset, + headOffset = offsets.head[bodyPart] ?: bone.headOffset, + offset = offsets.tail[bodyPart] ?: bone.offset, ) } - state.copy(boneInputs = newBones, skeletonHeight = action.skeletonHeight) + state.copy(boneInputs = newBones, skeletonHeight = action.lengths.height()) } is SkeletonActions.PauseTracking -> state.copy(paused = action.pause, pausedProcessedBoneInputs = null) @@ -52,14 +53,14 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when is SkeletonActions.ResetHeadPosition -> { val boneInputs = state.boneInputs - val headBone = boneInputs[BodyPart.HEAD.boneId] ?: return state + val headBone = boneInputs[BodyPart.HEAD] ?: return state if (headBone.isPositionActive) return state - state.copy(boneInputs = boneInputs.mutateCopy { it[BodyPart.HEAD.boneId] = headBone.copy(position = null) }) + state.copy(boneInputs = boneInputs.mutateCopy { it[BodyPart.HEAD] = headBone.copy(position = null) }) } is SkeletonActions.ComputeFloorLevel -> { val skeletonHeight = state.skeletonHeight - val headHeight = state.boneInputs[BodyPart.HEAD.boneId]?.position?.y ?: skeletonHeight + val headHeight = state.boneInputs[BodyPart.HEAD]?.position?.y ?: skeletonHeight state.copy(floorLevel = headHeight - skeletonHeight) } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/floor-clip.kt b/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/floor-clip.kt index 080405d14..8cf8c62e1 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/floor-clip.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/floor-clip.kt @@ -1,28 +1,25 @@ package dev.slimevr.skeleton.targetprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.IKTargets import dev.slimevr.skeleton.SkeletonTargetProcessor -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart +import kotlin.collections.set class FloorClipTargetProcessor( val settings: Settings, - bodyParts: Array = arrayOf(BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG), + val bodyParts: Array = arrayOf(BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG), ) : SkeletonTargetProcessor { - private val boneIds: Array = bodyParts.map { it.boneId }.toTypedArray() - override fun process(mutableIkTargets: IKTargets, fk: ComputedSkeleton, floorLevel: Float) { if (!settings.context.state.value.data.skeletonConfig.toggles.floorClip) return - for (boneId in boneIds) { + for (bodyPart in bodyParts) { // Get existing target or make a new one at the current bone position - val target = mutableIkTargets[boneId] ?: fk[boneId]?.tailPosition ?: continue + val target = mutableIkTargets[bodyPart] ?: fk[bodyPart]?.tailPosition ?: continue // Snap the target up to the floor if it's under - mutableIkTargets[boneId] = Vector3(target.x, target.y.coerceAtLeast(floorLevel), target.z) + mutableIkTargets[bodyPart] = Vector3(target.x, target.y.coerceAtLeast(floorLevel), target.z) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt b/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt index 7c3d82516..630d4381f 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt @@ -1,17 +1,16 @@ package dev.slimevr.skeleton.targetprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.COMState import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.IKTargets import dev.slimevr.skeleton.ResettableSkeletonProcessor import dev.slimevr.skeleton.SkeletonTargetProcessor import dev.slimevr.skeleton.Velocity -import dev.slimevr.skeleton.boneId +import dev.slimevr.skeleton.bodyPartMap import dev.slimevr.skeleton.centreOfMass import dev.slimevr.skeleton.computeComState -import dev.slimevr.skeleton.resolveMasses import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -79,11 +78,8 @@ class SkatingCorrectionTargetProcessor(val settings: Settings) : // Centre of mass var comState: COMState? = null - val lastLockedPositions: MutableMap = mutableMapOf() - val lockState: MutableMap = mutableMapOf() - - private val masses = resolveMasses() - private val velocityBoneIds: Array = VELOCITY_BODY_PARTS.map { it.boneId }.toTypedArray() + val lastLockedPositions: BodyPartMap = bodyPartMap() + val lockState: BodyPartMap = bodyPartMap() override fun process(mutableIkTargets: IKTargets, fk: ComputedSkeleton, floorLevel: Float) { val skeletonConfig = settings.context.state.value.data.skeletonConfig @@ -96,21 +92,21 @@ class SkatingCorrectionTargetProcessor(val settings: Settings) : comState = computeComState( curTime, comState, - centreOfMass(fk, masses), + centreOfMass(fk), ) val correctionStrength = skeletonConfig.ratios.skatingCorrectionStrength // TODO - for (boneId in velocityBoneIds) { - val curBone = fk[boneId] ?: continue + for (bodyPart in VELOCITY_BODY_PARTS) { + val curBone = fk[bodyPart] ?: continue val curPosition = curBone.tailPosition // Consider locking BodyPart - val lastState = lockState[boneId] + val lastState = lockState[bodyPart] val wasLocked = lastState?.locked == true val isLocked = shouldLock( curPosition, - lastLockedPositions[boneId] ?: curPosition, + lastLockedPositions[bodyPart] ?: curPosition, curBone.acceleration, curBone.velocity, if (wasLocked) SKATING_LOCK_ENGAGE_PERCENT else 1f, @@ -123,13 +119,13 @@ class SkatingCorrectionTargetProcessor(val settings: Settings) : curPosition, )?.also { // Track lock state changes - lockState[boneId] = it + lockState[bodyPart] = it // Otherwise pull the last state } ?: lastState ?: continue if (activeState.locked) { - mutableIkTargets[boneId] = activeState.position - lastLockedPositions[boneId] = activeState.position + mutableIkTargets[bodyPart] = activeState.position + lastLockedPositions[bodyPart] = activeState.position } } } diff --git a/server/core/src/main/java/dev/slimevr/solarxr/common.kt b/server/core/src/main/java/dev/slimevr/solarxr/common.kt index c03ee8f8b..f859bed32 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/common.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/common.kt @@ -1,13 +1,13 @@ package dev.slimevr.solarxr -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.BoneState +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.BoneMask import solarxr_protocol.datatypes.math.Quat import solarxr_protocol.datatypes.math.Vec3f -fun createBone(bone: BoneState, id: BoneId, mask: BoneMask): solarxr_protocol.datatypes.Bone = solarxr_protocol.datatypes.Bone( - id = id.value, +fun createBone(bone: BoneState, mask: BoneMask): solarxr_protocol.datatypes.Bone = solarxr_protocol.datatypes.Bone( + bodyPart = if (mask.bodyPart) bone.bodyPart else BodyPart.NONE, boneLength = if (mask.boneLength) bone.offset.len() else 0f, rotation = if (mask.rotation) bone.rotation.let { Quat(it.x, it.y, it.z, it.w) } else null, orientation = if (mask.orientation) bone.orientation.let { Quat(it.x, it.y, it.z, it.w) } else null, diff --git a/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt b/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt index bdd6ced18..8aedf29df 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt @@ -33,6 +33,7 @@ import solarxr_protocol.data_feed.tracker_data.StayAlignedTracker import solarxr_protocol.data_feed.tracker_data.TrackerData import solarxr_protocol.data_feed.tracker_data.TrackerDataMask import solarxr_protocol.data_feed.tracker_data.TrackerInfo +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.MagnetometerStatus import solarxr_protocol.datatypes.TrackerStatus import solarxr_protocol.datatypes.hardware_info.HardwareInfo @@ -63,7 +64,7 @@ private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMas TrackerInfo( isImu = tracker.imuType != null, imuType = tracker.imuType ?: ImuType.UNKNOWN, - boneId = tracker.boneId?.value ?: 0u, + bodyPart = tracker.bodyPart ?: BodyPart.NONE, mountingOrientation = tracker.mountingOrientation.let { Quat(it.x, it.y, it.z, it.w) }, mountingResetOrientation = tracker.sessionCalibration.headingAlignment.let { Quat(it.x, it.y, it.z, it.w) }, displayName = tracker.name, @@ -177,7 +178,7 @@ fun createDatafeedFrame( null } val bones = datafeedConfig.boneMask?.let { mask -> - skeleton.currentComputed.entries.map { (id, bone) -> createBone(bone, id, mask) } + skeleton.currentComputed.values.map { createBone(it, mask) } } val serverGuards = if (datafeedConfig.serverGuardsMask) { createServerGuards(resetsManager, heightCalibrationManager) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/driver/handshake.kt b/server/core/src/main/java/dev/slimevr/solarxr/driver/handshake.kt index a54a88a0e..51ce5decd 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/driver/handshake.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/driver/handshake.kt @@ -9,12 +9,12 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach -import solarxr_protocol.driver_protocol.DriverRegistrationResponse -import solarxr_protocol.driver_protocol.RegisterDriver -import solarxr_protocol.driver_protocol.RegistrationAvailable -import solarxr_protocol.driver_protocol.RegistrationStatus +import solarxr_protocol.driver_protocol.HandshakeAvailable +import solarxr_protocol.driver_protocol.HandshakeRequest +import solarxr_protocol.driver_protocol.HandshakeResponse +import solarxr_protocol.driver_protocol.HandshakeStatus -class DriverRegistrationBehaviour( +class DriverHandshakeBehaviour( private val appContext: AppContextProvider, ) : SolarXRBridgeBehaviour { override fun observe(receiver: SolarXRBridge) { @@ -25,21 +25,21 @@ class DriverRegistrationBehaviour( .distinctUntilChanged() .onEach { enabled -> if (enabled) { - receiver.sendDriverMessage(RegistrationAvailable()) + receiver.sendDriverMessage(HandshakeAvailable()) } else { val driverName = receiver.context.state.value.driverName ?: return@onEach AppLogger.solarxr.info("Disconnecting driver \"$driverName\"") receiver.disconnectDriverTrackers() receiver.context.dispatch(SolarXRBridgeActions.SetDriverInfo(null, null)) - receiver.sendDriverMessage(DriverRegistrationResponse(status = RegistrationStatus.REJECTED_DISABLED)) + receiver.sendDriverMessage(HandshakeResponse(status = HandshakeStatus.REJECTED_DISABLED)) } }.launchIn(receiver.context.scope) - receiver.onDriverMessage { req, replyTo -> + receiver.onDriverMessage { req, replyTo -> val name = req.driverName.takeIf { it.isNotEmpty() } ?: run { AppLogger.solarxr.info("Rejecting driver handshake because it's unnamed") - receiver.sendDriverMessage(DriverRegistrationResponse(status = RegistrationStatus.REJECTED_UNNAMED), replyTo = replyTo) + receiver.sendDriverMessage(HandshakeResponse(status = HandshakeStatus.REJECTED_UNNAMED), replyTo = replyTo) return@onDriverMessage } @@ -50,7 +50,7 @@ class DriverRegistrationBehaviour( if (duplicate) { AppLogger.solarxr.info("Rejecting handshake from \"$name\" because it's a duplicate") receiver.sendDriverMessage( - DriverRegistrationResponse(status = RegistrationStatus.REJECTED_DUPLICATE), + HandshakeResponse(status = HandshakeStatus.REJECTED_DUPLICATE), replyTo = replyTo, ) receiver.context.dispatch(SolarXRBridgeActions.SetDriverInfo(null, null)) @@ -60,7 +60,7 @@ class DriverRegistrationBehaviour( AppLogger.solarxr.info("Shook hands with \"$name\"") receiver.context.dispatch(SolarXRBridgeActions.SetDriverInfo(name, req.boneMask)) receiver.sendDriverMessage( - DriverRegistrationResponse(status = RegistrationStatus.ACCEPTED), + HandshakeResponse(status = HandshakeStatus.ACCEPTED), replyTo = replyTo, ) }.launchIn(receiver.context.scope) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/driver/incoming.kt b/server/core/src/main/java/dev/slimevr/solarxr/driver/incoming.kt index 23cbef162..1bd94ea2d 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/driver/incoming.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/driver/incoming.kt @@ -4,7 +4,6 @@ import dev.slimevr.AppContextProvider import dev.slimevr.VRServerActions import dev.slimevr.device.Device import dev.slimevr.device.DeviceActions -import dev.slimevr.skeleton.BoneId import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import dev.slimevr.tracker.Tracker @@ -32,19 +31,6 @@ class DriverIncomingTrackersBehaviour( } val hardwareId = req.hardwareIdentifier - // 0 means unassigned; any other ID must resolve in the registry. The tracker keeps the - // BoneId as its identity even when the bone has no standardized BodyPart, so extension - // bones can be assigned like any other. - val requestedBoneId = BoneId(req.boneId) - val boneId = if (requestedBoneId.value == 0.toUShort()) { - null - } else if (receiver.registry[requestedBoneId] != null) { - requestedBoneId - } else { - receiver.sendDriverMessage(AddTrackerResponse(status = AddTrackerStatus.ERROR), replyTo = replyTo) - return@onDriverMessage - } - val existing = server.context.state.value.trackers.values .find { it.context.state.value.hardwareId == hardwareId } if (existing != null) { @@ -55,7 +41,7 @@ class DriverIncomingTrackersBehaviour( return@onDriverMessage } - existing.context.dispatchAll(listOf(TrackerActions.SetDriverName(driverName), TrackerActions.Update { copy(intendedBoneId = boneId) })) + existing.context.dispatchAll(listOf(TrackerActions.SetDriverName(driverName), TrackerActions.Update { copy(intendedBodyPart = req.bodyPart) })) receiver.sendDriverMessage( AddTrackerResponse( status = AddTrackerStatus.ALREADY_EXISTS, @@ -87,8 +73,8 @@ class DriverIncomingTrackersBehaviour( scope = scope, id = trackerId, name = req.displayName ?: "Tracker #$trackerId", - boneId = boneId, - intendedBoneId = boneId, + bodyPart = req.bodyPart, + intendedBodyPart = req.bodyPart, deviceId = deviceId, hardwareId = hardwareId, origin = DeviceOrigin.DRIVER, diff --git a/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt b/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt index 09138c158..ab24f761d 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt @@ -3,9 +3,7 @@ package dev.slimevr.solarxr.driver import dev.slimevr.AppContextProvider import dev.slimevr.logging.AppLogger import dev.slimevr.skeleton.BodyPartMap -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.boneId -import dev.slimevr.skeleton.forEachBone +import dev.slimevr.skeleton.bodyPartMap import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import dev.slimevr.solarxr.createBone @@ -13,12 +11,14 @@ import dev.slimevr.tracker.TrackerState import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.datatypes.BoneMask import solarxr_protocol.datatypes.DeviceOrigin import solarxr_protocol.driver_protocol.BoneBatteryUpdate import solarxr_protocol.driver_protocol.SkeletonUpdate @@ -58,18 +58,12 @@ class DriverOutgoingTrackersBehaviour( ), ) - private val nearestBoneIds: Map> = buildMap { - bodyPartToNearest.forEachBone { bodyPart, fallbacks -> - put(bodyPart.boneId, fallbacks.mapTo(mutableSetOf()) { it.boneId }) - } - } - @OptIn(ExperimentalCoroutinesApi::class) override fun observe(receiver: SolarXRBridge) { val server = appContext.server val settings = appContext.config.settings - val boneBatteries = mutableMapOf() + val boneBatteries = bodyPartMap() combine(settings.context.state.map { it.data.driverConfig }, receiver.context.state) { driverConfig, state -> Triple( @@ -81,34 +75,34 @@ class DriverOutgoingTrackersBehaviour( .distinctUntilChanged() .flatMapLatest { (enabled, driverName, boneMask) -> if (!enabled || driverName == null || boneMask == null) return@flatMapLatest emptyFlow() - // Map the nearest trackers to their bone - val trackerStateByBoneId = mutableMapOf() + // Map the nearest trackers to their body parts + val trackerStateByBodyPart = bodyPartMap() for (tracker in server.context.state.value.trackers.values) { val trackerState = tracker.context.state.value if (trackerState.origin == DeviceOrigin.DRIVER) continue - val boneId = trackerState.boneId ?: continue - trackerStateByBoneId.putIfAbsent(boneId, trackerState) + val bodyPart = trackerState.bodyPart ?: continue + trackerStateByBodyPart.putIfAbsent(bodyPart, trackerState) } appContext.skeleton.computed.onEach { computedSkeleton -> - val bones = computedSkeleton.entries.map { (id, bone) -> createBone(bone, id, boneMask) } + val bones = computedSkeleton.values.map { createBone(it, boneMask) } receiver.sendDriverMessage(SkeletonUpdate(bones = bones)) - for (boneId in computedSkeleton.keys) { - val closestTracker = nearestBoneIds[boneId].orEmpty() - .firstNotNullOfOrNull { trackerStateByBoneId[it] } + computedSkeleton.keys.forEach { bodyPart -> + val closestTracker = bodyPartToNearest[bodyPart].orEmpty() + .firstNotNullOfOrNull { fallbackPart -> trackerStateByBodyPart[fallbackPart] } val closestDevice = server.context.state.value.devices[closestTracker?.deviceId]?.context?.state?.value if (closestDevice?.batteryLevel != null) { val battery = BoneBatteryUpdate( - boneId = boneId.value, + bone = bodyPart, batteryLevel = (closestDevice.batteryLevel * 100).toUInt().toUByte(), charging = closestDevice.batteryVoltage != null && closestDevice.batteryVoltage >= 4.3f, ) - if (boneBatteries.put(boneId, battery) != battery) { - AppLogger.solarxr.debug("Sending BoneBatteryUpdate for ${computedSkeleton.registry[boneId]?.key ?: boneId}") + if (boneBatteries.put(bodyPart, battery) != battery) { + AppLogger.solarxr.debug("Sending BoneBatteryUpdate for $bodyPart") receiver.sendDriverMessage(battery) } } diff --git a/server/core/src/main/java/dev/slimevr/solarxr/module.kt b/server/core/src/main/java/dev/slimevr/solarxr/module.kt index 58d0a3352..8b068d90b 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/module.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/module.kt @@ -8,9 +8,9 @@ import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import dev.slimevr.context.ManagedContext import dev.slimevr.solarxr.datafeed.DataFeedInitBehaviour +import dev.slimevr.solarxr.driver.DriverHandshakeBehaviour import dev.slimevr.solarxr.driver.DriverIncomingTrackersBehaviour import dev.slimevr.solarxr.driver.DriverOutgoingTrackersBehaviour -import dev.slimevr.solarxr.driver.DriverRegistrationBehaviour import dev.slimevr.solarxr.rpc.AssignTrackerBehaviour import dev.slimevr.solarxr.rpc.BoneRoutingBehaviour import dev.slimevr.solarxr.rpc.BvhBehaviour @@ -43,12 +43,6 @@ import dev.slimevr.util.timeSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import solarxr_protocol.MessageBundle -import solarxr_protocol.connection.ConfigurationAcknowledged -import solarxr_protocol.connection.ConnectionError -import solarxr_protocol.connection.ConnectionErrorCode -import solarxr_protocol.connection.ConnectionMessage -import solarxr_protocol.connection.ConnectionMessageHeader -import solarxr_protocol.connection.FinishConfiguration import solarxr_protocol.data_feed.DataFeedConfig import solarxr_protocol.data_feed.DataFeedMessage import solarxr_protocol.data_feed.DataFeedMessageHeader @@ -61,42 +55,22 @@ import solarxr_protocol.rpc.RpcMessage import solarxr_protocol.rpc.RpcMessageHeader import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds -import dev.slimevr.skeleton.BoneRegistry as SkeletonBoneRegistry data class SolarXRBridgeState( val dataFeedConfigs: List = emptyList(), val driverName: String? = null, val boneMask: BoneMask? = null, - val isReady: Boolean = false, - val observing: Boolean = false, ) sealed interface SolarXRBridgeActions { data class SetConfig(val configs: List) : SolarXRBridgeActions data class SetDriverInfo(val name: String?, val boneMask: BoneMask?) : SolarXRBridgeActions - data object SetReady : SolarXRBridgeActions - data object SetObserving : SolarXRBridgeActions } typealias SolarXRBridgeContext = Context typealias SolarXRBridgeBehaviour = Behaviour suspend fun onSolarXRMessage(message: MessageBundle, context: SolarXRBridge) { - // Connection messages are a barrier: configuration must be consumed before - // any application bundle is dispatched. - val wasReady = context.isReady - message.connectionMsgs?.forEach { header -> - when (header.message) { - is ConfigurationAcknowledged -> context.completeConfiguration() - else -> Unit - } - } - if (!wasReady) { - if (message.dataFeedMsgs != null || message.rpcMsgs != null || message.driverMsgs != null) { - context.sendConnectionMessage(ConnectionError(ConnectionErrorCode.INITIALIZATION_REQUIRED, "Configuration has not completed")) - } - return - } message.dataFeedMsgs?.forEach { val msg = it.message ?: return context.dataFeedDispatcher.emit(msg) @@ -135,9 +109,6 @@ class SolarXRBridge( val outbound: EventDispatcher = EventDispatcher("SolarXR[$id].outbound", context.scope, capacity = 64), private val managedContext: ManagedContext? = null, ) { - val isReady: Boolean get() = context.state.value.isReady - val registry: SkeletonBoneRegistry get() = appContext.skeleton.registry - // Jobs are mutable handles with no meaningful equality; storing them in state // would break distinctUntilChanged and data class copy semantics. internal var datafeedTimers: List = emptyList() @@ -169,21 +140,6 @@ class SolarXRBridge( suspend inline fun requestDriverMessage(message: DriverMessage, timeout: Duration = 10.seconds): R = driverRequests.request(timeout, message) { msg, newTxId -> sendDriverMessage(msg, txId = newTxId) } suspend fun sendDataFeed(frame: DataFeedMessageHeader) = outbound.emit(MessageBundle(dataFeedMsgs = listOf(frame))) - suspend fun sendConnectionMessage(message: ConnectionMessage) = outbound.emit(MessageBundle(connectionMsgs = listOf(ConnectionMessageHeader(message)))) - - suspend fun beginConfiguration() { - sendConnectionMessage(registry.value) - sendConnectionMessage(FinishConfiguration()) - } - - fun completeConfiguration() { - if (context.state.value.isReady) return - context.dispatch(SolarXRBridgeActions.SetReady) - if (!context.state.value.observing) { - context.dispatch(SolarXRBridgeActions.SetObserving) - startObserving() - } - } fun disconnectDriverTrackers() { val driverName = context.state.value.driverName ?: return @@ -241,7 +197,7 @@ class SolarXRBridge( add(AssignTrackerBehaviour(appContext.server)) add(DongleSettingsBehaviour(appContext.server)) add(TelemetryBehaviour(appContext.server)) - add(DriverRegistrationBehaviour(appContext)) + add(DriverHandshakeBehaviour(appContext)) add(DriverOutgoingTrackersBehaviour(appContext)) add(DriverIncomingTrackersBehaviour(appContext)) add(MagBehaviour(appContext)) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/protocol.kt b/server/core/src/main/java/dev/slimevr/solarxr/protocol.kt deleted file mode 100644 index 086219438..000000000 --- a/server/core/src/main/java/dev/slimevr/solarxr/protocol.kt +++ /dev/null @@ -1,17 +0,0 @@ -package dev.slimevr.solarxr - -import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader -import java.nio.ByteBuffer - -const val SOLARXR_PROTOCOL_VERSION: UInt = 2u -const val SOLARXR_MAX_FRAME_SIZE = 256 * 1024 - -/** Checks framing before generated code reads a FlatBuffer root. */ -fun checkedSolarXRFrame(bytes: ByteBuffer, identifier: String): JvmFlatBufferReader { - require(bytes.remaining() in 8..SOLARXR_MAX_FRAME_SIZE) { "Invalid SolarXR frame length" } - val position = bytes.position() - require((0 until 4).all { bytes.get(position + 4 + it).toInt().toChar() == identifier[it] }) { - "Unexpected SolarXR file identifier" - } - return JvmFlatBufferReader(bytes) -} diff --git a/server/core/src/main/java/dev/slimevr/solarxr/reducer.kt b/server/core/src/main/java/dev/slimevr/solarxr/reducer.kt index 19ff851fc..41284195b 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/reducer.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/reducer.kt @@ -3,6 +3,4 @@ package dev.slimevr.solarxr fun reduce(state: SolarXRBridgeState, action: SolarXRBridgeActions): SolarXRBridgeState = when (action) { is SolarXRBridgeActions.SetConfig -> state.copy(dataFeedConfigs = action.configs) is SolarXRBridgeActions.SetDriverInfo -> state.copy(driverName = action.name, boneMask = action.boneMask) - is SolarXRBridgeActions.SetReady -> state.copy(isReady = true) - is SolarXRBridgeActions.SetObserving -> state.copy(observing = true) } diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/bone-routing.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/bone-routing.kt index 29241bac8..675277818 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/bone-routing.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/bone-routing.kt @@ -11,8 +11,6 @@ import dev.slimevr.routing.intendedRoutesFlow import dev.slimevr.routing.outputStatesFlow import dev.slimevr.routing.overridableBones import dev.slimevr.routing.requiredBones -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import kotlinx.coroutines.flow.combine @@ -22,6 +20,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.BoneRoute import solarxr_protocol.rpc.BoneRoutingSettingsRequest import solarxr_protocol.rpc.BoneRoutingSettingsResponse @@ -38,18 +37,17 @@ private fun buildResponse( automatic: Boolean, routes: Routes, outputStates: OutputStates, - registry: BoneRegistry, ) = BoneRoutingSettingsResponse( automatic = automatic, - routes = ROUTABLE_BONES.mapNotNull { bone -> registry[bone] }.map { boneId -> - BoneRoute(boneId = boneId.value, outputs = routes[boneId].orEmpty().toList()) + routes = ROUTABLE_BONES.map { bone -> + BoneRoute(bone = bone, outputs = routes[bone].orEmpty().toList()) }, outputs = RoutingOutput.entries.map { output -> RoutingOutputStatus( output = output, - accepts = acceptedBones(output).mapNotNull { registry[it]?.value }, - requires = requiredBones(output).mapNotNull { registry[it]?.value }, - overridable = overridableBones(output).mapNotNull { registry[it]?.value }, + accepts = acceptedBones(output).toList(), + requires = requiredBones(output).toList(), + overridable = overridableBones(output).toList(), conflicts = conflictingOutputs(output).toList(), state = outputStates[output] ?: RoutingOutputState.UNSUPPORTED, ) @@ -62,13 +60,12 @@ class BoneRoutingBehaviour( private val settings = appContext.config.settings override fun observe(receiver: SolarXRBridge) { - val registry = appContext.skeleton.registry val responses = combine( settings.context.state.map { it.data.boneRoutingConfig.automatic }.distinctUntilChanged(), intendedRoutesFlow(appContext), outputStatesFlow(appContext), - ) { automatic, routes, outputStates -> buildResponse(automatic, routes, outputStates, registry) } - .distinctUntilChanged() + ::buildResponse, + ).distinctUntilChanged() receiver.rpcDispatcher.on { receiver.sendRpc(responses.first()) @@ -82,7 +79,8 @@ class BoneRoutingBehaviour( receiver.rpcDispatcher.on { req -> val requested = req.routes.orEmpty() .mapNotNull { route -> - val bone = BoneId(route.boneId) + val bone = route.bone + if (bone == BodyPart.NONE) return@mapNotNull null val outputs = route.outputs.orEmpty().toSet().ifEmpty { return@mapNotNull null } bone to outputs } @@ -95,7 +93,6 @@ class BoneRoutingBehaviour( config = boneRoutingConfig, automatic = req.automatic, routes = requested, - registry = registry, ), ) }, diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/session-calibration.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/session-calibration.kt index 6e4d845e7..368c6dc34 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/session-calibration.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/session-calibration.kt @@ -1,7 +1,6 @@ package dev.slimevr.solarxr.rpc import dev.slimevr.resets.ResetsManager -import dev.slimevr.skeleton.BoneId import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import solarxr_protocol.rpc.ClearMountingResetRequest @@ -13,8 +12,7 @@ class SessionCalibrationBehaviour( override fun observe(receiver: SolarXRBridge) { // Reset request receiver.rpcDispatcher.on { req -> - val boneIds = req.boneIds?.map { BoneId(it) } - resetsManager.scheduleReset("SolarXRBridge", req.resetType, req.delay ?: 0f, boneIds) + resetsManager.scheduleReset("SolarXRBridge", req.resetType, req.delay ?: 0f, req.bodyParts) }.launchIn(receiver.context.scope) // Clear mounting reset request diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/skeleton-proportions.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/skeleton-proportions.kt index bd4053387..ece5203fd 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/skeleton-proportions.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/skeleton-proportions.kt @@ -3,17 +3,15 @@ package dev.slimevr.solarxr.rpc import dev.slimevr.config.UserConfig import dev.slimevr.config.UserConfigActions import dev.slimevr.skeleton.ALL_BODY_PARTS +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.Skeleton -import dev.slimevr.skeleton.bodyPartMap -import dev.slimevr.skeleton.boneId import dev.slimevr.skeleton.computeAllDefaultProportionsByBone import dev.slimevr.skeleton.computeDefaultProportionsByBone import dev.slimevr.skeleton.height import dev.slimevr.skeleton.toBoneValues import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour -import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn @@ -37,14 +35,8 @@ class SkeletonProportionsBehaviour( private val skeleton: Skeleton, ) : SolarXRBridgeBehaviour { private fun buildConfigResponse(boneInputs: InputSkeleton): SkeletonProportionsResponse { - val registry = boneInputs.registry - val tailOffsets = bodyPartMap() - val headOffsets = bodyPartMap() - for ((boneId, input) in boneInputs) { - val bodyPart = registry.bodyPartOf(boneId) ?: continue - tailOffsets[bodyPart] = input.offset - headOffsets[bodyPart] = input.headOffset - } + val tailOffsets = BodyPartMap(boneInputs.mapValues { it.value.offset }) + val headOffsets = BodyPartMap(boneInputs.mapValues { it.value.headOffset }) val boneValues = toBoneValues(tailOffsets, headOffsets) val skeletonParts = boneValues.map { (offset, bone) -> SkeletonPart(offset, bone) } return SkeletonProportionsResponse(skeletonParts = skeletonParts, skeletonHeight = boneValues.height()) @@ -55,8 +47,7 @@ class SkeletonProportionsBehaviour( .map { it.boneInputs } .distinctUntilChanged { old, new -> ALL_BODY_PARTS.all { part -> - val id = part.boneId - old[id]?.offset == new[id]?.offset && old[id]?.headOffset == new[id]?.headOffset + old[part]?.offset == new[part]?.offset && old[part]?.headOffset == new[part]?.headOffset } } .drop(1) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/tap-detection.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/tap-detection.kt index 58f4c0835..40fad9750 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/tap-detection.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/tap-detection.kt @@ -3,7 +3,6 @@ package dev.slimevr.solarxr.rpc import dev.slimevr.config.Settings import dev.slimevr.config.SettingsActions import dev.slimevr.config.TapDetectionConfig -import dev.slimevr.skeleton.BoneId import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import dev.slimevr.tapdetection.TapDetectionActions @@ -21,7 +20,6 @@ class TapDetectionBehaviour( // Send config receiver.rpcDispatcher.on { val config = settings.context.state.value.data.tapDetectionConfig - val registry = receiver.registry receiver.sendRpc( TapDetectionSettingsResponse( yawResetDelay = config.yawResetDelay, @@ -33,9 +31,9 @@ class TapDetectionBehaviour( yawResetTaps = config.yawResetTaps.toUByte(), fullResetTaps = config.fullResetTaps.toUByte(), mountingResetTaps = config.mountingResetTaps.toUByte(), - yawResetBoneId = config.yawResetBone?.let { registry.byKey(it)?.id }, - fullResetBoneId = config.fullResetBone?.let { registry.byKey(it)?.id }, - mountingResetBoneId = config.mountingResetBone?.let { registry.byKey(it)?.id }, + yawResetTracker = config.yawResetBodyPart, + fullResetTracker = config.fullResetBodyPart, + mountingResetTracker = config.mountingResetBodyPart, numberTrackersOverThreshold = config.numberTrackersOverThreshold.toUByte(), ), ) @@ -43,7 +41,6 @@ class TapDetectionBehaviour( // Receive config receiver.rpcDispatcher.on { req -> - val registry = receiver.registry settings.context.dispatch( SettingsActions.Update { copy( @@ -57,9 +54,9 @@ class TapDetectionBehaviour( yawResetTaps = req.yawResetTaps?.toInt() ?: 2, fullResetTaps = req.fullResetTaps?.toInt() ?: 2, mountingResetTaps = req.mountingResetTaps?.toInt() ?: 2, - yawResetBone = req.yawResetBoneId?.let { registry[BoneId(it)]?.key }, - fullResetBone = req.fullResetBoneId?.let { registry[BoneId(it)]?.key }, - mountingResetBone = req.mountingResetBoneId?.let { registry[BoneId(it)]?.key }, + yawResetBodyPart = req.yawResetTracker, + fullResetBodyPart = req.fullResetTracker, + mountingResetBodyPart = req.mountingResetTracker, numberTrackersOverThreshold = req.numberTrackersOverThreshold?.toInt() ?: 1, ), ) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/tracker-assignment.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/tracker-assignment.kt index 25e539758..91dd01217 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/tracker-assignment.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/tracker-assignment.kt @@ -1,13 +1,14 @@ package dev.slimevr.solarxr.rpc import dev.slimevr.VRServer -import dev.slimevr.skeleton.BoneId +import dev.slimevr.skeleton.bodyPartMap import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import dev.slimevr.util.isActive import io.github.axisangles.ktmath.Quaternion +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.AssignTrackerRequest import solarxr_protocol.rpc.ResetTrackerAssignments @@ -20,29 +21,29 @@ class AssignTrackerBehaviour( val tracker = server.getTracker(id.toInt()) ?: return@on - val boneId = BoneId(req.boneId).takeIf { receiver.registry[it] != null } - if (boneId != null) { + val bodyPart = req.bodyPosition.takeIf { it != BodyPart.NONE } + if (bodyPart != null) { server.context.state.value.trackers.values.filter { val state = it.context.state.value state.id != id.toInt() && - state.boneId == boneId && + state.bodyPart == bodyPart && state.status.isActive() }.forEach { it.context.dispatch( - TrackerActions.Update { copy(boneId = null) }, + TrackerActions.Update { copy(bodyPart = null) }, ) } } tracker.context.dispatch( TrackerActions.Update { copy( - boneId = boneId, + bodyPart = bodyPart, customName = req.displayName ?: customName, ) }, ) - // Override default mounting orientation set from changing the assigned bone + // Override default mounting orientation set from changing the bodyPart val mountingOrientation = req.mountingOrientation?.let { Quaternion(it.w, it.x, it.y, it.z) } if (mountingOrientation != null) { tracker.context.dispatch( @@ -53,29 +54,29 @@ class AssignTrackerBehaviour( receiver.rpcDispatcher.on { val trackers = server.context.state.value.trackers.values - val intendedBoneIds = mutableMapOf() + val intendedBodyParts = bodyPartMap() // First unassign all trackers so that we don't have conflicts. trackers.forEach { tracker -> - val intendedBoneId = tracker.context.state.value.intendedBoneId - if (intendedBoneId != null) { - intendedBoneIds.putIfAbsent(intendedBoneId, tracker) + val intendedBodyPart = tracker.context.state.value.intendedBodyPart + if (intendedBodyPart != null) { + intendedBodyParts.putIfAbsent(intendedBodyPart, tracker) } tracker.context.dispatch( TrackerActions.Update { - copy(boneId = null) + copy(bodyPart = null) }, ) } - // Then re-assign trackers with intended bones, using the map to ensure - // we don't try to assign two trackers to the same bone if there were - // multiple with the same intended bone. - intendedBoneIds.forEach { (boneId, tracker) -> + // Then re-assign trackers with intended body parts, using the map to ensure + // we don't try to assign two trackers to the same body part if there were + // multiple with the same intended body part. + intendedBodyParts.forEach { (bodyPart, tracker) -> tracker.context.dispatch( TrackerActions.Update { - copy(boneId = boneId) + copy(bodyPart = bodyPart) }, ) } diff --git a/server/core/src/main/java/dev/slimevr/tapdetection/behaviours.kt b/server/core/src/main/java/dev/slimevr/tapdetection/behaviours.kt index 113306237..25e0f4b97 100644 --- a/server/core/src/main/java/dev/slimevr/tapdetection/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/tapdetection/behaviours.kt @@ -1,8 +1,6 @@ package dev.slimevr.tapdetection import dev.slimevr.config.TapDetectionConfig -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.Motion import dev.slimevr.tracker.TrackerState import dev.slimevr.util.timeSource @@ -36,7 +34,7 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour { ) // This + the assigned tap body parts are used. - private val falsePositiveBoneIds = setOf( + private val falsePositiveBodyParts = setOf( BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.UPPER_WAIST, @@ -46,7 +44,7 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour { BodyPart.RIGHT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG, - ).mapTo(mutableSetOf()) { it.boneId } + ) @OptIn(ExperimentalCoroutinesApi::class) override fun observe(receiver: TapDetectionManager) { @@ -59,21 +57,20 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour { val okTrackersFlow = receiver.server.context.state .map { it.trackers.values } .flatMapLatest { trackers -> - // Tracker state emits on every rotation packet, but only the assigned bone/status - // matter here. Dedup per tracker first, or combine gets resumed once per packet - // per tracker. + // Tracker state emits on every rotation packet, but only bodyPart/status matter here. + // Dedup per tracker first, or combine gets resumed once per packet per tracker. combine( trackers.map { tracker -> - tracker.context.state.distinctUntilChanged { a, b -> a.boneId == b.boneId && a.status == b.status } + tracker.context.state.distinctUntilChanged { a, b -> a.bodyPart == b.bodyPart && a.status == b.status } }, ) { states -> - states.map { it.boneId to it.status } + states.map { it.bodyPart to it.status } } .distinctUntilChanged() .map { trackers.filter { it.context.state.value.status == TrackerStatus.OK } } } - // Outer flow is refreshed whenever TapDetection config, setupMode, or a tracker's bone or status changes + // Outer flow is refreshed whenever TapDetection config, setupMode, or a tracker's bodyPart or status changes combine( tapConfigFlow, setupModeFlow, @@ -82,18 +79,17 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour { ) .flatMapLatest { (tapDetectionConfig, setupMode, trackers) -> // Computed once per outer-flow refresh for all trackers - val registry = receiver.skeleton.registry - val trackersBoneIds = trackers.map { it.context.state.value.boneId }.toSet() - val yawResetBoneId = arrayOf(tapDetectionConfig.yawResetBone?.let { registry.byKey(it) }?.let { BoneId(it.id) }, BodyPart.UPPER_CHEST.boneId, BodyPart.LOWER_CHEST.boneId, BodyPart.HIP.boneId, BodyPart.LOWER_WAIST.boneId, BodyPart.UPPER_WAIST.boneId) - .firstOrNull { it in trackersBoneIds } ?: BodyPart.UPPER_CHEST.boneId - val fullResetBoneId = arrayOf(tapDetectionConfig.fullResetBone?.let { registry.byKey(it) }?.let { BoneId(it.id) }, BodyPart.LEFT_UPPER_LEG.boneId, BodyPart.LEFT_LOWER_LEG.boneId) - .firstOrNull { it in trackersBoneIds } ?: BodyPart.LEFT_UPPER_LEG.boneId - val mountingResetBoneId = arrayOf(tapDetectionConfig.mountingResetBone?.let { registry.byKey(it) }?.let { BoneId(it.id) }, BodyPart.RIGHT_UPPER_LEG.boneId, BodyPart.RIGHT_LOWER_LEG.boneId) - .firstOrNull { it in trackersBoneIds } ?: BodyPart.RIGHT_UPPER_LEG.boneId + val trackersBodyParts = trackers.map { it.context.state.value.bodyPart }.toSet() + val yawResetBodyPart = arrayOf(tapDetectionConfig.yawResetBodyPart, BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.HIP, BodyPart.LOWER_WAIST, BodyPart.UPPER_WAIST) + .firstOrNull { it in trackersBodyParts } ?: BodyPart.UPPER_CHEST + val fullResetBodyPart = arrayOf(tapDetectionConfig.fullResetBodyPart, BodyPart.LEFT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG) + .firstOrNull { it in trackersBodyParts } ?: BodyPart.LEFT_UPPER_LEG + val mountingResetBodyPart = arrayOf(tapDetectionConfig.mountingResetBodyPart, BodyPart.RIGHT_UPPER_LEG, BodyPart.RIGHT_LOWER_LEG) + .firstOrNull { it in trackersBodyParts } ?: BodyPart.RIGHT_UPPER_LEG // To keep track of which trackers are moving val numberTrackersOverThreshold = tapDetectionConfig.numberTrackersOverThreshold - val boneIdsToCheck = falsePositiveBoneIds + listOfNotNull(yawResetBoneId, fullResetBoneId, mountingResetBoneId) + val bodyPartsToCheck = falsePositiveBodyParts + yawResetBodyPart + fullResetBodyPart + mountingResetBodyPart val trackersOverThreshold = mutableSetOf() trackers.map { tracker -> @@ -101,14 +97,14 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour { tapDetectionConfig, setupMode, tracker.context.state.value, - yawResetBoneId, - fullResetBoneId, - mountingResetBoneId, + yawResetBodyPart, + fullResetBodyPart, + mountingResetBodyPart, ) // Inner flow emits whenever a tracker's rawAcceleration is updated tracker.context.state - .filter { it.boneId in boneIdsToCheck || setupMode } + .filter { it.bodyPart in bodyPartsToCheck || setupMode } .map { it.rawAcceleration to it.motion } .distinctUntilChanged() .onEach { (rawAcceleration, motionState) -> @@ -165,29 +161,29 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour { tapDetectionConfig: TapDetectionConfig, setupMode: Boolean, trackerState: TrackerState, - yawResetBoneId: BoneId?, - fullResetBoneId: BoneId?, - mountingResetBoneId: BoneId?, + yawResetBodyPart: BodyPart, + fullResetBodyPart: BodyPart, + mountingResetBodyPart: BodyPart, ): TrackerTapDetectionState { // This holds a tracker's config and state for tap detection val trackerTapDetectionState = TrackerTapDetectionState(trackerState.id) // setupMode uses defaults if (!setupMode) { - when (trackerState.boneId) { - yawResetBoneId if tapDetectionConfig.yawResetEnabled -> { + when (trackerState.bodyPart) { + yawResetBodyPart if tapDetectionConfig.yawResetEnabled -> { trackerTapDetectionState.resetType = ResetType.YAW trackerTapDetectionState.tapsNeeded = tapDetectionConfig.yawResetTaps trackerTapDetectionState.actionDelay = tapDetectionConfig.yawResetDelay } - fullResetBoneId if tapDetectionConfig.fullResetEnabled -> { + fullResetBodyPart if tapDetectionConfig.fullResetEnabled -> { trackerTapDetectionState.resetType = ResetType.FULL trackerTapDetectionState.tapsNeeded = tapDetectionConfig.fullResetTaps trackerTapDetectionState.actionDelay = tapDetectionConfig.fullResetDelay } - mountingResetBoneId if tapDetectionConfig.mountingResetEnabled -> { + mountingResetBodyPart if tapDetectionConfig.mountingResetEnabled -> { trackerTapDetectionState.resetType = ResetType.POSE_MOUNTING trackerTapDetectionState.tapsNeeded = tapDetectionConfig.mountingResetTaps trackerTapDetectionState.actionDelay = tapDetectionConfig.mountingResetDelay diff --git a/server/core/src/main/java/dev/slimevr/tapdetection/module.kt b/server/core/src/main/java/dev/slimevr/tapdetection/module.kt index 122ab30e8..4415ebb2d 100644 --- a/server/core/src/main/java/dev/slimevr/tapdetection/module.kt +++ b/server/core/src/main/java/dev/slimevr/tapdetection/module.kt @@ -6,7 +6,6 @@ import dev.slimevr.config.Settings import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import dev.slimevr.resets.ResetsManager -import dev.slimevr.skeleton.Skeleton import kotlinx.coroutines.CoroutineScope import kotlin.collections.listOf @@ -22,8 +21,6 @@ typealias TapDetectionContext = Context typealias TapDetectionBehaviour = Behaviour class TapDetectionManager(val context: TapDetectionContext, val server: VRServer, val resetsManager: ResetsManager, val settings: Settings) { - val skeleton: Skeleton get() = resetsManager.skeleton - fun startObserving() = context.observeAll(this) companion object { diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/assignment-conflict.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/assignment-conflict.kt index b413670d7..6e88a83d4 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/assignment-conflict.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/assignment-conflict.kt @@ -19,14 +19,14 @@ class TrackerAssignmentConflictBehaviour : TrackerBehaviour { .filter { active -> active } .onEach { val state = receiver.context.state.value - val boneId = state.boneId ?: return@onEach + val bodyPart = state.bodyPart ?: return@onEach - val boneTaken = receiver.appContext.server.context.state.value.trackers.values.any { other -> + val bodyPartTaken = receiver.appContext.server.context.state.value.trackers.values.any { other -> val otherState = other.context.state.value - otherState.id != state.id && otherState.boneId == boneId && otherState.status.isActive() + otherState.id != state.id && otherState.bodyPart == bodyPart && otherState.status.isActive() } - if (boneTaken) { - receiver.context.dispatch(TrackerActions.Update { copy(boneId = null) }) + if (bodyPartTaken) { + receiver.context.dispatch(TrackerActions.Update { copy(bodyPart = null) }) } } .launchIn(receiver.context.scope) diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/config.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/config.kt index b20654251..a069ff96e 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/config.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/config.kt @@ -3,8 +3,7 @@ package dev.slimevr.tracker.behaviours import dev.slimevr.config.Settings import dev.slimevr.config.SettingsActions import dev.slimevr.config.TrackerConfig -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.BoneRegistry +import dev.slimevr.tracker.SessionCalibration import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerBehaviour import dev.slimevr.tracker.TrackerState @@ -12,31 +11,31 @@ import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.MagnetometerStatus import solarxr_protocol.datatypes.MountingMethod class TrackerConfigBehaviour( private val settings: Settings, private val hardwareId: String, - private val registry: BoneRegistry, ) : TrackerBehaviour { override fun observe(receiver: Tracker) { receiver.context.state .distinctUntilChangedBy { val saveMountingReset = receiver.settings.context.state.value.data.resetsConfig.saveMountingReset val headingAlignment = if (saveMountingReset) it.sessionCalibration.headingAlignment else null - it.boneId to it.customName to it.mountingOrientation to it.magStatus to headingAlignment + it.bodyPart to it.customName to it.mountingOrientation to it.magStatus to headingAlignment } .drop(1) .onEach { state -> - settings.context.dispatch(SettingsActions.UpdateTracker(hardwareId) { applyStateToConfig(this, state, receiver.settings.context.state.value.data.resetsConfig.saveMountingReset, registry) }) + settings.context.dispatch(SettingsActions.UpdateTracker(hardwareId) { applyStateToConfig(this, state, receiver.settings.context.state.value.data.resetsConfig.saveMountingReset) }) } .launchIn(receiver.context.scope) } companion object { - fun restoreFromConfig(state: TrackerState, config: TrackerConfig, saveMountingReset: Boolean, registry: BoneRegistry): TrackerState = state.copy( - boneId = config.bone?.let { registry.byKey(it) }?.let { BoneId(it.id) }, + fun restoreFromConfig(state: TrackerState, config: TrackerConfig, saveMountingReset: Boolean): TrackerState = state.copy( + bodyPart = config.bodyPart, customName = config.customName ?: state.customName, lastMountingMethod = if (saveMountingReset && config.mountingResetOrientation != null) MountingMethod.POSE else MountingMethod.MANUAL, mountingOrientation = config.mountingOrientation, @@ -54,8 +53,8 @@ class TrackerConfigBehaviour( }, ) - private fun applyStateToConfig(config: TrackerConfig, state: TrackerState, saveMountingReset: Boolean, registry: BoneRegistry) = config.copy( - bone = state.boneId?.let { registry[it]?.key }, + private fun applyStateToConfig(config: TrackerConfig, state: TrackerState, saveMountingReset: Boolean) = config.copy( + bodyPart = state.bodyPart, customName = state.customName, mountingOrientation = state.mountingOrientation, mountingResetOrientation = if (saveMountingReset) state.sessionCalibration.headingAlignment else null, diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/default-mounting-orientation.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/default-mounting-orientation.kt index 8119c5457..02bd093b1 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/default-mounting-orientation.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/default-mounting-orientation.kt @@ -1,6 +1,5 @@ package dev.slimevr.tracker.behaviours -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import dev.slimevr.tracker.TrackerBehaviour @@ -13,7 +12,7 @@ import kotlinx.coroutines.flow.onEach import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.MountingMethod -class TrackerDefaultMountingOrientationBehaviour(private val registry: BoneRegistry) : TrackerBehaviour { +class TrackerDefaultMountingOrientationBehaviour : TrackerBehaviour { /** * Returns the default mounting orientation for the body part */ @@ -47,13 +46,12 @@ class TrackerDefaultMountingOrientationBehaviour(private val registry: BoneRegis override fun observe(receiver: Tracker) { receiver.context.state - .map { it.boneId } + .map { it.bodyPart } .distinctUntilChanged() .drop(1) - .onEach { boneId -> + .onEach { if (receiver.context.state.value.lastMountingMethod == MountingMethod.MANUAL) { - val bodyPart = boneId?.let { registry.bodyPartOf(it) } - receiver.context.dispatch(TrackerActions.SetMountingOrientation(defaultMountingForBodyPart(bodyPart))) + receiver.context.dispatch(TrackerActions.SetMountingOrientation(defaultMountingForBodyPart(it))) } }.launchIn(receiver.context.scope) } diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/rest-orientation.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/rest-orientation.kt index 4a3eb8d8a..60bb24e29 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/rest-orientation.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/rest-orientation.kt @@ -3,7 +3,6 @@ package dev.slimevr.tracker.behaviours import com.jme3.math.FastMath import dev.slimevr.config.Settings import dev.slimevr.resets.ResetBodyParts -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import dev.slimevr.tracker.TrackerBehaviour @@ -24,14 +23,12 @@ import solarxr_protocol.rpc.ArmsResetMode */ class TrackerRestOrientationBehaviour( private val settings: Settings, - private val registry: BoneRegistry, ) : TrackerBehaviour { override fun observe(receiver: Tracker) { val armsResetModeFlow = settings.context.state.map { it.data.resetsConfig.armsResetMode } - val boneIdFlow = receiver.context.state.map { it.boneId }.distinctUntilChanged() + val bodyPartFlow = receiver.context.state.map { it.bodyPart }.distinctUntilChanged() - combine(armsResetModeFlow, boneIdFlow) { armsResetMode, boneId -> - val bodyPart = boneId?.let { registry.bodyPartOf(it) } + combine(armsResetModeFlow, bodyPartFlow) { armsResetMode, bodyPart -> getRestOrientation(bodyPart, armsResetMode) } .distinctUntilChanged() diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt index 38e8e66a0..3a664b51f 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt @@ -2,7 +2,6 @@ package dev.slimevr.tracker.behaviours import dev.slimevr.config.Settings import dev.slimevr.math.angle.Angle -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import dev.slimevr.tracker.TrackerBehaviour @@ -25,7 +24,6 @@ import solarxr_protocol.datatypes.MagnetometerStatus class TrackerStayAlignedBehaviour( private val settings: Settings, - private val registry: BoneRegistry, ) : TrackerBehaviour { override fun observe(receiver: Tracker) { @@ -93,7 +91,6 @@ class TrackerStayAlignedBehaviour( serverFlow.value.trackers.values.map { it.context.state.value }, applyYawCorrection, stayAlignedConfig, - registry, ) if (yawCorrectionResult != null) { receiver.context.dispatch(TrackerActions.SetYawCorrection(yawCorrectionResult)) diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/to-skeleton.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/to-skeleton.kt index cc6d9d279..9af88675e 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/to-skeleton.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/to-skeleton.kt @@ -1,6 +1,5 @@ package dev.slimevr.tracker.behaviours -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.SkeletonActions import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerBehaviour @@ -12,44 +11,45 @@ import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.TrackerStatus class TrackerToSkeletonBehaviour : TrackerBehaviour { - var lastBoneIdSent: BoneId? = null + var lastBodyPartSent: BodyPart? = null @OptIn(ExperimentalCoroutinesApi::class) override fun observe(receiver: Tracker) { receiver.context.state - .distinctUntilChanged { old, new -> old.status == new.status && old.boneId == new.boneId } + .distinctUntilChanged { old, new -> old.status == new.status && old.bodyPart == new.bodyPart } .onEach { _ -> // Tell the skeleton the tracker has stopped sending data to the last bone it was sending data to. - lastBoneIdSent?.let { + lastBodyPartSent?.let { val trackerState = receiver.context.state.value - if ((!trackerState.status.isActive() && trackerState.status != TrackerStatus.OCCLUDED) || trackerState.boneId != lastBoneIdSent) { + if ((!trackerState.status.isActive() && trackerState.status != TrackerStatus.OCCLUDED) || trackerState.bodyPart != lastBodyPartSent) { receiver.appContext.skeleton.context.dispatch( SkeletonActions.DisableBone(it), ) - lastBoneIdSent = null + lastBodyPartSent = null } } } .flatMapLatest { _ -> - // We only want trackers that are assigned to a bone and are active + // We only want trackers that are assigned to a BodyPart and are active val activeState = receiver.context.state - .filter { it.boneId != null && it.status.isActive() } + .filter { it.bodyPart != null && it.status.isActive() } activeState .distinctUntilChangedBy { it.rotation to it.position } .onEach { trackerState -> - trackerState.boneId?.let { boneId -> + trackerState.bodyPart?.let { bodyPart -> receiver.appContext.skeleton.context.dispatchAll( listOfNotNull( - SkeletonActions.SetBoneRotation(boneId, trackerState.rotation), - SkeletonActions.SetBoneAcceleration(boneId, trackerState.acceleration), - if (trackerState.position != null) SkeletonActions.SetBonePosition(boneId, trackerState.position) else null, + SkeletonActions.SetBoneRotation(bodyPart, trackerState.rotation), + SkeletonActions.SetBoneAcceleration(bodyPart, trackerState.acceleration), + if (trackerState.position != null) SkeletonActions.SetBonePosition(bodyPart, trackerState.position) else null, ), ) - lastBoneIdSent = trackerState.boneId + lastBodyPartSent = trackerState.bodyPart } } } diff --git a/server/core/src/main/java/dev/slimevr/tracker/module.kt b/server/core/src/main/java/dev/slimevr/tracker/module.kt index 35d72df6c..28a49f360 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/module.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/module.kt @@ -7,7 +7,6 @@ import dev.slimevr.context.Context import dev.slimevr.context.debug.DiffStyle import dev.slimevr.context.debug.LoggingMiddleware import dev.slimevr.math.angle.Angle -import dev.slimevr.skeleton.BoneId import dev.slimevr.tracker.behaviours.TrackerAssignmentConflictBehaviour import dev.slimevr.tracker.behaviours.TrackerCalibrationRefreshBehaviour import dev.slimevr.tracker.behaviours.TrackerConfigBehaviour @@ -22,6 +21,7 @@ import dev.slimevr.util.isActive import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope +import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.DeviceOrigin import solarxr_protocol.datatypes.MagnetometerStatus import solarxr_protocol.datatypes.MountingMethod @@ -60,9 +60,9 @@ data class TrackerState( val hardwareId: String, val name: String, val imuType: ImuType?, - val boneId: BoneId?, - /** The default bone given by e.g. driver, VMC, etc. */ - val intendedBoneId: BoneId?, + val bodyPart: BodyPart?, + /** The default body part given by e.g. driver, VMC, etc. */ + val intendedBodyPart: BodyPart?, val customName: String?, val trackerDataType: TrackerDataType, // TODO val lastMountingMethod: MountingMethod, @@ -86,9 +86,9 @@ data class TrackerState( val stayAlignedData: StayAlignedData, ) -fun List.getFirstActiveFor(boneId: BoneId): TrackerState? = this.firstOrNull { it.boneId == boneId && it.status.isActive() } +fun List.getFirstActiveFor(bodyPart: BodyPart): TrackerState? = this.firstOrNull { it.bodyPart == bodyPart && it.status.isActive() } -fun List.getAllActiveFor(boneIds: List): List = this.filter { it.boneId in boneIds && it.status.isActive() } +fun List.getAllActiveFor(bodyParts: List): List = this.filter { it.bodyPart in bodyParts && it.status.isActive() } sealed interface TrackerActions { data class Update(val transform: TrackerState.() -> TrackerState) : TrackerActions @@ -123,8 +123,8 @@ class Tracker( scope: CoroutineScope, id: Int, name: String = "Tracker #$id", - boneId: BoneId? = null, - intendedBoneId: BoneId? = null, + bodyPart: BodyPart? = null, + intendedBodyPart: BodyPart? = null, deviceId: Int, imuType: ImuType? = null, hardwareId: String, @@ -133,7 +133,6 @@ class Tracker( appContext: AppContextProvider, ): Tracker { val settings = appContext.config.settings - val registry = appContext.skeleton.registry val trackerConfigs = settings.context.state.value.data.trackers val savedConfig = trackerConfigs[hardwareId] val baseState = DEFAULT_STATE.copy( @@ -144,12 +143,12 @@ class Tracker( hardwareId = hardwareId, name = name, imuType = imuType, - boneId = boneId, - intendedBoneId = intendedBoneId, + bodyPart = bodyPart, + intendedBodyPart = intendedBodyPart, stayAlignedData = DEFAULT_STATE.stayAlignedData.copy(enabled = settings.context.state.value.data.stayAlignedConfig.enabled), ) val trackerState = if (savedConfig != null) { - TrackerConfigBehaviour.restoreFromConfig(baseState, savedConfig, settings.context.state.value.data.resetsConfig.saveMountingReset, registry) + TrackerConfigBehaviour.restoreFromConfig(baseState, savedConfig, settings.context.state.value.data.resetsConfig.saveMountingReset) } else { baseState } @@ -159,12 +158,12 @@ class Tracker( TrackerTpsBehaviour(), TrackerAssignmentConflictBehaviour(), TrackerYawResetSmoothingBehaviour(), - TrackerDefaultMountingOrientationBehaviour(registry), - TrackerConfigBehaviour(settings, hardwareId, registry), + TrackerDefaultMountingOrientationBehaviour(), + TrackerConfigBehaviour(settings, hardwareId), TrackerMotionDetectionBehaviour(), TrackerToSkeletonBehaviour(), - TrackerRestOrientationBehaviour(settings, registry), - TrackerStayAlignedBehaviour(settings, registry), + TrackerRestOrientationBehaviour(settings), + TrackerStayAlignedBehaviour(settings), ) val context = Context.create( initialState = trackerState, @@ -187,8 +186,8 @@ class Tracker( hardwareId = "defaultHardwareId", name = "defaultTracker", imuType = ImuType.BNO085, - boneId = null, - intendedBoneId = null, + bodyPart = null, + intendedBodyPart = null, customName = null, trackerDataType = TrackerDataType.ROTATION, lastMountingMethod = MountingMethod.MANUAL, diff --git a/server/core/src/main/java/dev/slimevr/tracker/reducer.kt b/server/core/src/main/java/dev/slimevr/tracker/reducer.kt index 8cb2a2f0b..3a069b334 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/reducer.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/reducer.kt @@ -1,6 +1,5 @@ package dev.slimevr.tracker -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.MountingMethod @@ -82,7 +81,7 @@ fun reduce( is TrackerActions.FullReset -> { val isPositional = state.position != null - val isHead = state.boneId == BodyPart.HEAD.boneId + val isHead = state.bodyPart == BodyPart.HEAD val shouldAlignAttitude = !isHead || !isPositional || action.resetPositionalHeadAttitude val shouldAlignHeadingWithReference = !isHead && isPositional diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt index 31a0f3719..d39ad5d2b 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt @@ -1,7 +1,5 @@ package dev.slimevr.tracker.stayaligned.poses -import dev.slimevr.skeleton.BoneRegistry -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.TrackerState import dev.slimevr.tracker.getAllActiveFor import dev.slimevr.tracker.getFirstActiveFor @@ -21,16 +19,14 @@ enum class PlayerPose { companion object { - fun of(trackerStates: List, registry: BoneRegistry): PlayerPose { + fun of(trackerStates: List): PlayerPose { val poses = TrackerPoses( - trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup.map { it.boneId }) - .sortedBy { it.boneId?.let { id -> registry.bodyPartOf(id) }?.let { part -> StayAlignedBodyParts.upperBodyOrder[part] } } - .map(TrackerPose.Companion::ofTracker), - TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg.boneId)), - TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg.boneId)), - TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg.boneId)), - TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg.boneId)), + trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup).sortedBy { StayAlignedBodyParts.upperBodyOrder[it.bodyPart] }.map(TrackerPose.Companion::ofTracker), + TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg)), + TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg)), + TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg)), + TrackerPose.ofTracker(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg)), ) return ( diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt index 7ee4c4d40..13de96e10 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt @@ -2,13 +2,11 @@ package dev.slimevr.tracker.stayaligned.poses import dev.slimevr.config.StayAlignedConfig import dev.slimevr.math.angle.Angle -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.TrackerState import dev.slimevr.tracker.getFirstActiveFor import dev.slimevr.tracker.stayaligned.StayAlignedBodyParts import dev.slimevr.tracker.stayaligned.StayAlignedDefaults import dev.slimevr.tracker.stayaligned.YawUtils.trackerYaw -import solarxr_protocol.datatypes.BodyPart class RelaxedPose( val upperLeg: Angle, @@ -85,22 +83,20 @@ class RelaxedPose( (trackerYaw(left.rotation) - trackerYaw(right.rotation)) * 0.5f } - fun firstActiveFor(bodyPart: BodyPart) = trackerStates.getFirstActiveFor(bodyPart.boneId) - - val upperLegAngle: Angle = firstActiveFor(StayAlignedBodyParts.leftUpperLeg)?.let { left -> - firstActiveFor(StayAlignedBodyParts.rightUpperLeg)?.let { right -> + val upperLegAngle: Angle = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg)?.let { left -> + trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg)?.let { right -> halfAngleBetween(left, right) } } ?: Angle.ZERO - val lowerLegAngle: Angle = firstActiveFor(StayAlignedBodyParts.leftLowerLeg)?.let { left -> - firstActiveFor(StayAlignedBodyParts.rightLowerLeg)?.let { right -> + val lowerLegAngle: Angle = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg)?.let { left -> + trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg)?.let { right -> halfAngleBetween(left, right) } } ?: Angle.ZERO - val footAngle: Angle = firstActiveFor(StayAlignedBodyParts.leftFoot)?.let { left -> - firstActiveFor(StayAlignedBodyParts.rightFoot)?.let { right -> + val footAngle: Angle = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftFoot)?.let { left -> + trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightFoot)?.let { right -> halfAngleBetween(left, right) } } ?: Angle.ZERO diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt index 19ecd13f8..470c2a409 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt @@ -3,8 +3,6 @@ package dev.slimevr.tracker.stayaligned import dev.slimevr.config.StayAlignedConfig import dev.slimevr.math.angle.Angle import dev.slimevr.math.angle.AngleErrors -import dev.slimevr.skeleton.BoneRegistry -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.Motion import dev.slimevr.tracker.TrackerState import dev.slimevr.tracker.applyCalibration @@ -17,7 +15,6 @@ import dev.slimevr.tracker.stayaligned.poses.RelaxedPose import dev.slimevr.util.Side import dev.slimevr.util.side import io.github.axisangles.ktmath.Quaternion -import solarxr_protocol.datatypes.BodyPart /** * Entry point for Stay Aligned. More specifically, computeYawCorrection is. @@ -41,9 +38,8 @@ object TrackerYawCorrection { trackerStates: List, applyYawCorrection: Angle, config: StayAlignedConfig, - registry: BoneRegistry, ): Angle? = when (trackerState.motion) { - Motion.ROTATING -> adjustMovingTracker(trackerState, trackerStates, applyYawCorrection, config, registry) + Motion.ROTATING -> adjustMovingTracker(trackerState, trackerStates, applyYawCorrection, config) Motion.RESTING -> adjustLockedTracker(trackerState, applyYawCorrection) @@ -102,16 +98,15 @@ object TrackerYawCorrection { trackerStates: List, applyYawCorrection: Angle, config: StayAlignedConfig, - registry: BoneRegistry, ): Angle? { val centreYaw = YawUtils.centreYawOfTrackers(trackerStates) ?: return null - val relaxedPose = RelaxedPose.forPose(PlayerPose.of(trackerStates, registry), config) ?: return null + val relaxedPose = RelaxedPose.forPose(PlayerPose.of(trackerStates), config) ?: return null return adjustByError(trackerState, applyYawCorrection) { yawCorrection -> YawErrors().also { val yawCorrectedRotation = computeYawCorrectedRotation(yawCorrection, trackerState) - it.centreError.add(getCentreError(yawCorrectedRotation, trackerState, centreYaw, relaxedPose, registry)) - it.neighbourError.add(getNeighbourError(yawCorrectedRotation, trackerState, relaxedPose, trackerStates, registry)) + it.centreError.add(getCentreError(yawCorrectedRotation, trackerState, centreYaw, relaxedPose)) + it.neighbourError.add(getNeighbourError(yawCorrectedRotation, trackerState, relaxedPose, trackerStates)) } } } @@ -119,8 +114,8 @@ object TrackerYawCorrection { /** * Returns an error based off the yaw difference from a tracker and the centre yaw. */ - private fun getCentreError(yawCorrectedRotation: Quaternion, trackerState: TrackerState, centreYaw: Angle, relaxedPose: RelaxedPose, registry: BoneRegistry): Angle { - val bodyPart = trackerState.boneId?.let { registry.bodyPartOf(it) } + private fun getCentreError(yawCorrectedRotation: Quaternion, trackerState: TrackerState, centreYaw: Angle, relaxedPose: RelaxedPose): Angle { + val bodyPart = trackerState.bodyPart val side = bodyPart?.side ?: Side.LEFT val poseYaw = when (bodyPart) { @@ -150,12 +145,10 @@ object TrackerYawCorrection { /** * Returns an error based off the yaw difference from a tracker and the next upper and lower trackers (neighbours). */ - private fun getNeighbourError(yawCorrectedRotation: Quaternion, trackerState: TrackerState, relaxedPose: RelaxedPose, trackerStates: List, registry: BoneRegistry): Angle { + private fun getNeighbourError(yawCorrectedRotation: Quaternion, trackerState: TrackerState, relaxedPose: RelaxedPose, trackerStates: List): Angle { fun neighbourError(rotation: Quaternion) = trackerYaw(rotation) - trackerYaw(yawCorrectedRotation) - fun firstActiveFor(bodyPart: BodyPart) = trackerStates.getFirstActiveFor(bodyPart.boneId) - val upperBodyTrackers = trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup.map { it.boneId }) - .sortedBy { it.boneId?.let { id -> registry.bodyPartOf(id) }?.let { part -> StayAlignedBodyParts.upperBodyOrder[part] } } - val bodyPart = trackerState.boneId?.let { registry.bodyPartOf(it) } + val upperBodyTrackers = trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup).sortedBy { StayAlignedBodyParts.upperBodyOrder[it.bodyPart] } + val bodyPart = trackerState.bodyPart val side = bodyPart?.side ?: Side.LEFT return when (bodyPart) { @@ -163,11 +156,11 @@ object TrackerYawCorrection { in StayAlignedBodyParts.upperBodyGroup -> { // Index of this tracker in upperBodyTrackers. 0 = highest on body. - val trackerUpperBodyIndex = upperBodyTrackers.map { it.boneId?.let { id -> registry.bodyPartOf(id) } }.indexOf(bodyPart) + val trackerUpperBodyIndex = upperBodyTrackers.map { it.bodyPart }.indexOf(trackerState.bodyPart) // Compute upper legs error - val leftUpperLeg = firstActiveFor(StayAlignedBodyParts.leftUpperLeg) - val rightUpperLeg = firstActiveFor(StayAlignedBodyParts.rightUpperLeg) + val leftUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg) + val rightUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg) val upperLegsError = if (leftUpperLeg != null && rightUpperLeg != null) { neighbourError(leftUpperLeg.rotation) - sideYaw(Side.LEFT, relaxedPose.upperLeg) + @@ -203,7 +196,7 @@ object TrackerYawCorrection { Angle.ZERO } - val lowerLeg = firstActiveFor(StayAlignedBodyParts.lowerLeg(side)) + val lowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.lowerLeg(side)) val lowerLegError = if (lowerLeg != null) { neighbourError(lowerLeg.rotation) - sideYaw(side, relaxedPose.lowerLeg) + sideYaw(side, relaxedPose.upperLeg) } else { @@ -216,14 +209,14 @@ object TrackerYawCorrection { StayAlignedBodyParts.leftLowerLeg, StayAlignedBodyParts.rightLowerLeg, -> { - val upperLeg = firstActiveFor(StayAlignedBodyParts.upperLeg(side)) + val upperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.upperLeg(side)) val upperLegError = if (upperLeg != null) { neighbourError(upperLeg.rotation) - sideYaw(side, relaxedPose.upperLeg) + sideYaw(side, relaxedPose.lowerLeg) } else { Angle.ZERO } - val foot = firstActiveFor(StayAlignedBodyParts.foot(side)) + val foot = trackerStates.getFirstActiveFor(StayAlignedBodyParts.foot(side)) val footError = if (foot != null) { neighbourError(foot.rotation) - sideYaw(side, relaxedPose.foot) + sideYaw(side, relaxedPose.lowerLeg) } else { @@ -236,7 +229,7 @@ object TrackerYawCorrection { StayAlignedBodyParts.leftFoot, StayAlignedBodyParts.rightFoot, -> { - val lowerLeg = firstActiveFor(StayAlignedBodyParts.lowerLeg(side)) + val lowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.lowerLeg(side)) if (lowerLeg != null) { neighbourError(lowerLeg.rotation) - sideYaw(side, relaxedPose.lowerLeg) + sideYaw(side, relaxedPose.foot) } else { diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt index 94565f7be..25dad0e56 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt @@ -2,7 +2,6 @@ package dev.slimevr.tracker.stayaligned import dev.slimevr.math.angle.Angle import dev.slimevr.math.angle.AngleAverage -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.TrackerState import dev.slimevr.tracker.getAllActiveFor import dev.slimevr.tracker.getFirstActiveFor @@ -73,13 +72,13 @@ object YawUtils { fun centreYawOfTrackers( trackerStates: List, ): Angle? { - val head = trackerStates.getFirstActiveFor(StayAlignedBodyParts.head.boneId) // Optional - val upperBody = trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup.map { it.boneId }) + val head = trackerStates.getFirstActiveFor(StayAlignedBodyParts.head) // Optional + val upperBody = trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup) if (upperBody.isEmpty()) return null - val leftUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg.boneId) ?: return null - val rightUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg.boneId) ?: return null - val leftLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg.boneId) ?: return null - val rightLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg.boneId) ?: return null + val leftUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg) ?: return null + val rightUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg) ?: return null + val leftLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg) ?: return null + val rightLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg) ?: return null // Need a minimum set of trackers, and the trackers need to be oriented in a // way where we can actually calculate its yaw. diff --git a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt index ec5e5c71e..b5bdd894f 100644 --- a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt @@ -5,14 +5,13 @@ package dev.slimevr.trackingchecklist import dev.slimevr.VRServer import dev.slimevr.VRServerState import dev.slimevr.config.Settings +import dev.slimevr.device.DeviceState import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.resets.ResetBodyParts import dev.slimevr.resets.ResetsManager import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.routing.Routes -import dev.slimevr.skeleton.BoneId import dev.slimevr.skeleton.Skeleton -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.TrackerState import dev.slimevr.vrchat.VRCConfigManager import dev.slimevr.vrchat.VRCConfigState @@ -75,8 +74,8 @@ data class ChecklistTracker( val id: Int, val origin: DeviceOrigin, val status: TrackerStatus, - val boneId: BoneId?, - val intendedBoneId: BoneId?, + val bodyPart: BodyPart?, + val intendedBodyPart: BodyPart?, val imuType: ImuType?, val completedRestCalibration: Boolean?, // Deliberately not the position itself: the checks only ask whether there is one, and carrying the @@ -88,8 +87,8 @@ fun checklistTracker(tracker: TrackerState) = ChecklistTracker( id = tracker.id, origin = tracker.origin, status = tracker.status, - boneId = tracker.boneId, - intendedBoneId = tracker.intendedBoneId, + bodyPart = tracker.bodyPart, + intendedBodyPart = tracker.intendedBodyPart, imuType = tracker.imuType, completedRestCalibration = tracker.completedRestCalibration, hasPosition = tracker.position != null, @@ -101,8 +100,8 @@ internal fun trackerStatesFlow(server: VRServer): Flow> = class HMDCheckBehaviour(private val trackerStates: StateFlow>) : TrackingChecklistBehaviourType { private fun computeStep(trackers: List): TrackingChecklistStep { - val hmdTracker = trackers.firstOrNull { tracker -> tracker.origin == DeviceOrigin.DRIVER && tracker.intendedBoneId == BodyPart.HEAD.boneId } - val isAssigned = hmdTracker?.boneId == BodyPart.HEAD.boneId + val hmdTracker = trackers.firstOrNull { tracker -> tracker.origin == DeviceOrigin.DRIVER && tracker.intendedBodyPart == BodyPart.HEAD } + val isAssigned = hmdTracker?.bodyPart == BodyPart.HEAD return TrackingChecklistStep( valid = isAssigned, enabled = hmdTracker != null, @@ -159,7 +158,7 @@ class TrackerRestCheckBehaviour(private val trackerStates: StateFlow>) : TrackingChecklistBehaviourType { private fun computeStep(trackers: List): TrackingChecklistStep { val errorTrackers = trackers - .filter { tracker -> tracker.status == TrackerStatus.ERROR && tracker.boneId != null } + .filter { tracker -> tracker.status == TrackerStatus.ERROR && tracker.bodyPart != null } .toSet() return TrackingChecklistStep( valid = errorTrackers.isEmpty(), @@ -190,7 +189,7 @@ class SteamVRHandsCheckBehaviour( private val boneRouting: BoneRoutingManager, ) : TrackingChecklistBehaviourType { companion object { - private val HAND_BONES = setOf(BodyPart.LEFT_HAND.boneId, BodyPart.RIGHT_HAND.boneId) + private val HAND_BONES = setOf(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) fun computeStep( trackers: List, @@ -200,7 +199,7 @@ class SteamVRHandsCheckBehaviour( // The skeleton computes a hand bone from the arm chain, so routing one sends a hand // tracker to SteamVR whether or not the user wears anything on that hand. val handsSentToDriver = HAND_BONES.any { hand -> routes[hand]?.contains(RoutingOutput.DRIVER) == true } - val handTrackers = trackers.filter { tracker -> tracker.boneId in HAND_BONES } + val handTrackers = trackers.filter { tracker -> tracker.bodyPart in HAND_BONES } // Controllers reach us back through the driver, anything else on a hand is a // tracker the user actually wears. val hasControllers = handTrackers.any { tracker -> tracker.origin == DeviceOrigin.DRIVER } @@ -290,13 +289,13 @@ private fun isImuAssigned(tracker: ChecklistTracker): Boolean = (tracker.origin !tracker.hasPosition && tracker.imuType !== null && tracker.status != TrackerStatus.ERROR && - tracker.boneId != null + tracker.bodyPart != null private fun isConnectedAssignedImu(tracker: ChecklistTracker): Boolean = (tracker.origin == DeviceOrigin.UDP || tracker.origin == DeviceOrigin.HID) && !tracker.hasPosition && tracker.imuType !== null && (tracker.status == TrackerStatus.OK || tracker.status == TrackerStatus.SLEEPING) && - tracker.boneId != null + tracker.bodyPart != null class FullResetCheckBehaviour( private val trackerStates: StateFlow>, @@ -318,19 +317,19 @@ class FullResetCheckBehaviour( } .launchIn(scope) - val boneIds = mutableMapOf() + val bodyParts = mutableMapOf() trackerStates - .map { trackers -> trackers.mapNotNull { tracker -> tracker.boneId?.let { tracker.id to it } }.toMap() } + .map { trackers -> trackers.mapNotNull { tracker -> tracker.bodyPart?.let { tracker.id to it } }.toMap() } .distinctUntilChanged() .onEach { current -> - for ((id, boneId) in current) { - val previous = boneIds[id] - if (previous != null && previous != boneId) { + for ((id, bodyPart) in current) { + val previous = bodyParts[id] + if (previous != null && previous != bodyPart) { needsReset.update { ids -> ids + id } } } - boneIds.clear() - boneIds.putAll(current) + bodyParts.clear() + bodyParts.putAll(current) } .launchIn(scope) @@ -387,8 +386,6 @@ class MountingCalibrationCheckBehaviour( } } -private val FEET_BONE_IDS = ResetBodyParts.FEET.mapTo(mutableSetOf()) { it.boneId } - class FeetMountingCalibrationCheckBehaviour( private val trackerStates: StateFlow>, private val resetsManager: ResetsManager, @@ -406,7 +403,7 @@ class FeetMountingCalibrationCheckBehaviour( valid = resetsState.feetMountingResetCompleted, enabled = resetsConfig.lastMountingMethod == MountingMethod.POSE && !resetsConfig.resetMountingFeet && - imuTrackers.any { it.boneId in FEET_BONE_IDS }, + imuTrackers.any { it.bodyPart in ResetBodyParts.FEET }, ignorable = true, visibility = TrackingChecklistStepVisibility.ALWAYS, ) diff --git a/server/core/src/main/java/dev/slimevr/vmc/input.kt b/server/core/src/main/java/dev/slimevr/vmc/input.kt index f11a8cab2..27271c30c 100644 --- a/server/core/src/main/java/dev/slimevr/vmc/input.kt +++ b/server/core/src/main/java/dev/slimevr/vmc/input.kt @@ -9,8 +9,6 @@ import dev.slimevr.logging.AppLogger import dev.slimevr.osc.OscBundle import dev.slimevr.osc.OscReceiver import dev.slimevr.osc.forEachOscMessage -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import dev.slimevr.util.formatExceptionMessage @@ -29,12 +27,11 @@ internal class VmcTrackerRegistry( private val manager: VMCManager, ) { private var deviceId: Int? = null - private val boneTrackerIds = mutableMapOf() + private val boneTrackerIds = mutableMapOf() private val poseTrackerIds = mutableMapOf() fun boneTracker(bodyPart: BodyPart, unityName: String): Tracker { - val boneId = bodyPart.boneId - boneTrackerIds[boneId]?.let { id -> appContext.server.getTracker(id)?.let { existing -> return existing } } + boneTrackerIds[bodyPart]?.let { id -> appContext.server.getTracker(id)?.let { existing -> return existing } } val device = findOrCreateDevice() val trackerId = appContext.server.nextHandle() @@ -42,8 +39,8 @@ internal class VmcTrackerRegistry( scope = manager.context.scope, id = trackerId, name = "VMC-Bone-$unityName", - boneId = boneId, - intendedBoneId = boneId, + bodyPart = bodyPart, + intendedBodyPart = bodyPart, deviceId = device.context.state.value.id, hardwareId = "vmc:bone:$bodyPart", origin = DeviceOrigin.VMC, @@ -51,7 +48,7 @@ internal class VmcTrackerRegistry( ) appContext.server.context.dispatch(VRServerActions.NewTracker(trackerId, runtimeTracker)) runtimeTracker.context.dispatch(TrackerActions.SetStatus(TrackerStatus.OK)) - boneTrackerIds[boneId] = trackerId + boneTrackerIds[bodyPart] = trackerId return runtimeTracker } @@ -64,8 +61,8 @@ internal class VmcTrackerRegistry( scope = manager.context.scope, id = trackerId, name = "VMC-Tracker-$serial", - boneId = null, - intendedBoneId = null, + bodyPart = null, + intendedBodyPart = null, deviceId = device.context.state.value.id, hardwareId = "vmc:tracker:$serial", origin = DeviceOrigin.VMC, diff --git a/server/core/src/main/java/dev/slimevr/vmc/output-encoder.kt b/server/core/src/main/java/dev/slimevr/vmc/output-encoder.kt index b4f69d6c5..97d4ecd29 100644 --- a/server/core/src/main/java/dev/slimevr/vmc/output-encoder.kt +++ b/server/core/src/main/java/dev/slimevr/vmc/output-encoder.kt @@ -7,7 +7,6 @@ import dev.slimevr.osc.OscContent import dev.slimevr.osc.OscMessage import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.ComputedSkeleton -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -32,7 +31,7 @@ internal fun buildOutgoingBundle( val targetParentBodyPart = VMC_OUTPUT_BONE_PARENTS[targetBodyPart] val trackingBodyPart = if (config.mirrorTracking) vmcMirrorSource(targetBodyPart) else targetBodyPart - val trackingBone = bones[trackingBodyPart.boneId] ?: continue + val trackingBone = bones[trackingBodyPart] ?: continue if (targetParentBodyPart == null) { // TODO anchorHip https://github.com/SlimeVR/SlimeVR-Server/blob/main/server/core/src/main/java/dev/slimevr/osc/VMCHandler.kt#L371 @@ -47,7 +46,7 @@ internal fun buildOutgoingBundle( } else { targetParentBodyPart } - val trackingParent = bones[trackingParentBodyPart.boneId] ?: continue + val trackingParent = bones[trackingParentBodyPart] ?: continue val pos = if (vrm != null) { vrm.bindOffsets[targetBodyPart] ?: Vector3.ZERO @@ -74,7 +73,7 @@ internal fun buildInitRequestMessage(): OscMessage = OscMessage("/VMC/Ext/Req", private fun restAdjustedWorld( bone: BoneState, - restBodyPart: BodyPart, + restBodyPart: BodyPart = bone.bodyPart, mirror: Boolean = false, ): Quaternion { val world = if (mirror) vmcMirrorRotation(bone.rotation) else bone.rotation @@ -90,8 +89,8 @@ internal fun vmcLocalRotation( mirror: Boolean, ): Quaternion { val adjusted = restAdjustedWorld(bone, restBodyPart, mirror) - if (parent == null || restParentBodyPart == null) return adjusted - return restAdjustedWorld(parent, restParentBodyPart, mirror).inv() * adjusted + if (parent == null) return adjusted + return restAdjustedWorld(parent, restParentBodyPart ?: parent.bodyPart, mirror).inv() * adjusted } internal fun vmcLocalPosition( diff --git a/server/core/src/main/java/dev/slimevr/vmc/output.kt b/server/core/src/main/java/dev/slimevr/vmc/output.kt index a62b2e31a..b10468d2d 100644 --- a/server/core/src/main/java/dev/slimevr/vmc/output.kt +++ b/server/core/src/main/java/dev/slimevr/vmc/output.kt @@ -60,7 +60,6 @@ class VMCOutputBehaviour( val routedBones = boneRouting.context.state .map { state -> state.routes.filterValues { RoutingOutput.VMC in it }.keys } .distinctUntilChanged() - .map { boneIds -> boneIds.mapNotNullTo(mutableSetOf(), skeleton.registry::bodyPartOf) } val config = settings.context.state .map { it.data.vmcConfig } diff --git a/server/core/src/main/java/dev/slimevr/vrchat/module.kt b/server/core/src/main/java/dev/slimevr/vrchat/module.kt index 25dab11e0..52d730f9e 100644 --- a/server/core/src/main/java/dev/slimevr/vrchat/module.kt +++ b/server/core/src/main/java/dev/slimevr/vrchat/module.kt @@ -4,7 +4,6 @@ import dev.slimevr.VRServer import dev.slimevr.config.AppConfig import dev.slimevr.context.Behaviour import dev.slimevr.context.Context -import dev.slimevr.skeleton.boneId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch @@ -85,7 +84,7 @@ class VRCConfigManager( fun computeRecommendedValues(server: VRServer, userHeight: Float): VRCConfigRecommendedValues { val trackers = server.context.state.value.trackers.values - fun hasTracker(bodyPart: BodyPart) = trackers.any { it.context.state.value.boneId == bodyPart.boneId } + fun hasTracker(bodyPart: BodyPart) = trackers.any { it.context.state.value.bodyPart == bodyPart } val hasLeftHandWithPosition = hasTracker(BodyPart.LEFT_HAND) val hasRightHandWithPosition = hasTracker(BodyPart.RIGHT_HAND) diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/input.kt b/server/core/src/main/java/dev/slimevr/vrcosc/input.kt index e076aa999..9e1c5cbdb 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/input.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/input.kt @@ -9,7 +9,6 @@ import dev.slimevr.logging.AppLogger import dev.slimevr.osc.OscMessage import dev.slimevr.osc.OscReceiver import dev.slimevr.osc.forEachOscMessage -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import dev.slimevr.util.formatExceptionMessage @@ -52,13 +51,12 @@ private class VRSystemTrackerRegistry( VRSystemTracker.LEFT_WRIST -> "VRChat left hand" VRSystemTracker.RIGHT_WRIST -> "VRChat right hand" } - val boneId = bodyPart.boneId val runtimeTracker = Tracker.create( scope = manager.context.scope, id = trackerId, name = trackerName, - boneId = boneId, - intendedBoneId = boneId, + bodyPart = bodyPart, + intendedBodyPart = bodyPart, deviceId = device.context.state.value.id, hardwareId = "vrcosc:vrsystem:${tracker.name.lowercase()}", origin = DeviceOrigin.VRC, diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt b/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt index fd455fe16..baa5ac49f 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt @@ -4,8 +4,8 @@ import dev.slimevr.osc.OscArg import dev.slimevr.osc.OscBundle import dev.slimevr.osc.OscContent import dev.slimevr.osc.OscMessage +import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.ComputedSkeleton -import dev.slimevr.skeleton.boneId import io.github.axisangles.ktmath.EulerOrder import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 @@ -34,7 +34,7 @@ internal fun buildOutgoingBundle( for ((bodyPart, trackerId) in trackerIdsByBodyPart) { if (bodyPart !in routedBones) continue - val bone = bones[bodyPart.boneId] ?: continue + val bone = bones[bodyPart] ?: continue add( OscContent.Message( positionMessage("/tracking/trackers/$trackerId/position", bone.headPosition), @@ -47,14 +47,14 @@ internal fun buildOutgoingBundle( ) } - bones[BodyPart.HEAD.boneId]?.let { head -> + bones[BodyPart.HEAD]?.let { head -> add( OscContent.Message( positionMessage("/tracking/trackers/head/position", head.headPosition), ), ) } - + addAll(buildToeMessages(bones)) } diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/output.kt b/server/core/src/main/java/dev/slimevr/vrcosc/output.kt index ac2e5146b..c78f9a8c8 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/output.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/output.kt @@ -70,7 +70,6 @@ class VRCOSCOutputBehaviour( val routedBones = boneRouting.context.state .map { state -> state.routes.filterValues { RoutingOutput.VRC_OSC in it }.keys } .distinctUntilChanged() - .map { boneIds -> boneIds.mapNotNullTo(mutableSetOf(), skeleton.registry::bodyPartOf) } combine(skeleton.computed, routedBones, ::Pair) .onEach { (computedSkeleton, bones) -> sendFrame(receiver, runtime, computedSkeleton, bones) } diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/toe-plugin-output-encoder.kt b/server/core/src/main/java/dev/slimevr/vrcosc/toe-plugin-output-encoder.kt index 8c8e7fa3e..bae580730 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/toe-plugin-output-encoder.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/toe-plugin-output-encoder.kt @@ -4,44 +4,44 @@ import dev.slimevr.osc.OscArg import dev.slimevr.osc.OscContent import dev.slimevr.osc.OscMessage import dev.slimevr.skeleton.BoneState -import dev.slimevr.skeleton.ComputedSkeleton -import dev.slimevr.skeleton.boneId import dev.slimevr.util.Side import dev.slimevr.util.opposite import io.github.axisangles.ktmath.EulerOrder +import io.github.axisangles.ktmath.Quaternion +import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart +import kotlin.math.* private const val ABSOLUTE_SPLAY_THRESHOLD_ANGLE = 7 private const val MINIMUM_TIP_TOE_PITCH = -14 private const val MINIMUM_BENDING_PITCH = 15 private const val MAXIMUM_ABSOLUTE_TOE_RANGE = 90 -internal fun buildToeMessages(bones: ComputedSkeleton): List { +internal fun buildToeMessages(bones: Map): List { val messages = mutableListOf() - fun bone(bodyPart: BodyPart): BoneState? = bones[bodyPart.boneId] // LEFT FOOT + TOES - val leftFoot = bone(BodyPart.LEFT_FOOT) + val leftFoot = bones[BodyPart.LEFT_FOOT] if (leftFoot != null) { val leftToes = listOf( - bone(BodyPart.LEFT_BIG_TOE), - bone(BodyPart.LEFT_INDEX_TOE), - bone(BodyPart.LEFT_MIDDLE_TOE), - bone(BodyPart.LEFT_RING_TOE), - bone(BodyPart.LEFT_LITTLE_TOE), + bones[BodyPart.LEFT_BIG_TOE], + bones[BodyPart.LEFT_INDEX_TOE], + bones[BodyPart.LEFT_MIDDLE_TOE], + bones[BodyPart.LEFT_RING_TOE], + bones[BodyPart.LEFT_LITTLE_TOE], ) processToesForFoot(leftFoot, leftToes, Side.LEFT, messages) } // RIGHT FOOT + TOES - val rightFoot = bone(BodyPart.RIGHT_FOOT) + val rightFoot = bones[BodyPart.RIGHT_FOOT] if (rightFoot != null) { val rightToes = listOf( - bone(BodyPart.RIGHT_BIG_TOE), - bone(BodyPart.RIGHT_INDEX_TOE), - bone(BodyPart.RIGHT_MIDDLE_TOE), - bone(BodyPart.RIGHT_RING_TOE), - bone(BodyPart.RIGHT_LITTLE_TOE), + bones[BodyPart.RIGHT_BIG_TOE], + bones[BodyPart.RIGHT_INDEX_TOE], + bones[BodyPart.RIGHT_MIDDLE_TOE], + bones[BodyPart.RIGHT_RING_TOE], + bones[BodyPart.RIGHT_LITTLE_TOE], ) processToesForFoot(rightFoot, rightToes, Side.RIGHT, messages) } diff --git a/server/core/src/test/java/dev/slimevr/TestServer.kt b/server/core/src/test/java/dev/slimevr/TestServer.kt index 878cb6a1b..41c53f540 100644 --- a/server/core/src/test/java/dev/slimevr/TestServer.kt +++ b/server/core/src/test/java/dev/slimevr/TestServer.kt @@ -27,15 +27,14 @@ import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.serial.FlashingHandler import dev.slimevr.serial.SerialPortHandle import dev.slimevr.serial.SerialServer -import dev.slimevr.skeleton.BoneId -import dev.slimevr.skeleton.BoneMap -import dev.slimevr.skeleton.BoneRegistry -import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.ComputedSkeleton +import dev.slimevr.skeleton.DEFAULT_SKELETON_STATE import dev.slimevr.skeleton.ProportionsBehaviour import dev.slimevr.skeleton.Skeleton import dev.slimevr.skeleton.buildBones -import dev.slimevr.skeleton.defaultSkeletonState +import dev.slimevr.solarxr.SolarXRBridge +import dev.slimevr.solarxr.SolarXRBridgeState +import dev.slimevr.solarxr.driver.DriverHandshakeBehaviour import dev.slimevr.solarxr.rpc.ServerInfos import dev.slimevr.tapdetection.TapDetectionManager import dev.slimevr.tracker.Motion @@ -105,12 +104,12 @@ fun buildTestUserConfig(scope: CoroutineScope): UserConfig { return userConfig } -fun buildTestSkeleton(scope: CoroutineScope, registry: BoneRegistry = BoneRegistry.standard()): Skeleton { +fun buildTestSkeleton(scope: CoroutineScope): Skeleton { val context = Context.create( - initialState = defaultSkeletonState(registry), + initialState = DEFAULT_SKELETON_STATE, scope = scope, reducer = ::reduceSkeleton, - behaviours = listOf(ProportionsBehaviour(buildTestUserConfig(scope), registry)), + behaviours = listOf(ProportionsBehaviour(buildTestUserConfig(scope))), name = "TestSkeleton", ) val computed = MutableSharedFlow( @@ -123,11 +122,6 @@ fun buildTestSkeleton(scope: CoroutineScope, registry: BoneRegistry = BoneRegist return skeleton } -/** Builds a [ComputedSkeleton] from BodyPart-keyed bones, for tests that think in anatomy. */ -fun BoneRegistry.computedSkeletonOf(vararg bones: Pair): ComputedSkeleton = BoneMap.of(this).also { map -> - for ((bodyPart, bone) in bones) map[requireNotNull(this[bodyPart]) { "$bodyPart is not in this registry" }] = bone -} - fun buildTestResetsManager(server: VRServer, settings: Settings, scope: CoroutineScope): ResetsManager { val context = Context.create( initialState = ResetsState( @@ -150,8 +144,8 @@ fun buildTestTracker( appContext: AppContextProvider, settings: Settings, id: Int, - boneId: BoneId? = null, - intendedBoneId: BoneId? = null, + bodyPart: BodyPart? = null, + intendedBodyPart: BodyPart? = null, status: TrackerStatus = TrackerStatus.DISCONNECTED, origin: DeviceOrigin = DeviceOrigin.UDP, imuType: ImuType? = ImuType.BNO085, @@ -170,8 +164,8 @@ fun buildTestTracker( hardwareId = "test-$id", name = "Tracker $id", imuType = imuType, - boneId = boneId, - intendedBoneId = intendedBoneId, + bodyPart = bodyPart, + intendedBodyPart = intendedBodyPart, customName = null, sessionCalibration = sessionCalibration, rawRotation = rawRotation, diff --git a/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt b/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt index 77e24b9c6..84bf56521 100644 --- a/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt +++ b/server/core/src/test/java/dev/slimevr/bvh/BvhStreamTest.kt @@ -1,10 +1,8 @@ package dev.slimevr.bvh import dev.slimevr.config.TextFileHandle -import dev.slimevr.skeleton.BoneRegistry -import dev.slimevr.skeleton.boneId +import dev.slimevr.skeleton.DEFAULT_SKELETON_STATE import dev.slimevr.skeleton.buildBones -import dev.slimevr.skeleton.defaultSkeletonState import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.test.runTest @@ -14,23 +12,19 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class BvhStreamTest { - private val registry = BoneRegistry.standard() - private val headId = BodyPart.HEAD.boneId - private val defaultState = defaultSkeletonState(registry) - @Test fun `close persists header and frame data`() = runTest { val file = InMemoryBvhFile() val stream = BvhStream(file) - val initialBones = buildBones(defaultState.boneInputs) + val initialBones = buildBones(DEFAULT_SKELETON_STATE.boneInputs) val firstFrame = buildBones( - defaultState.boneInputs.mutateCopy { - it[headId] = it.getValue(headId).copy(position = Vector3(1f, 2f, 3f)) + DEFAULT_SKELETON_STATE.boneInputs.mutateCopy { + it[BodyPart.HEAD] = it.getValue(BodyPart.HEAD).copy(position = Vector3(1f, 2f, 3f)) }, ) val secondFrame = buildBones( - defaultState.boneInputs.mutateCopy { - it[headId] = it.getValue(headId).copy(position = Vector3(4f, 5f, 6f)) + DEFAULT_SKELETON_STATE.boneInputs.mutateCopy { + it[BodyPart.HEAD] = it.getValue(BodyPart.HEAD).copy(position = Vector3(4f, 5f, 6f)) }, ) @@ -51,7 +45,7 @@ class BvhStreamTest { fun `writeFrame after close is ignored`() = runTest { val file = InMemoryBvhFile() val stream = BvhStream(file) - val bones = buildBones(defaultState.boneInputs) + val bones = buildBones(DEFAULT_SKELETON_STATE.boneInputs) stream.writeHeader(bones) stream.close() @@ -59,8 +53,8 @@ class BvhStreamTest { stream.writeFrame( buildBones( - defaultState.boneInputs.mutateCopy { - it[headId] = it.getValue(headId).copy(position = Vector3(7f, 8f, 9f)) + DEFAULT_SKELETON_STATE.boneInputs.mutateCopy { + it[BodyPart.HEAD] = it.getValue(BodyPart.HEAD).copy(position = Vector3(7f, 8f, 9f)) }, ), ) diff --git a/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt b/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt index 87384b067..88e96c3e1 100644 --- a/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt +++ b/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt @@ -1,6 +1,5 @@ package dev.slimevr.routing -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.solarxr.driver.DRIVER_SUPPORTED_BONES import dev.slimevr.vmc.VMC_SUPPORTED_BONES import dev.slimevr.vrcosc.VRC_OSC_SUPPORTED_BONES @@ -32,15 +31,12 @@ private val COMMON_CANDIDATES = setOf( BodyPart.RIGHT_LOWER_LEG, ) +private fun routedTo( + routes: Map>, + output: RoutingOutput, +): Set = routes.filterValues { output in it }.keys + class AutomaticRoutesTest { - private val registry = BoneRegistry.standard() - - private fun routedTo(routes: Routes, output: RoutingOutput): Set = routes.filterValues { output in it }.keys.mapNotNullTo(mutableSetOf(), registry::bodyPartOf) - - private fun computeAutomaticRoutes(candidateBones: Set, outputStates: OutputStates): Routes = computeAutomaticRoutes(candidateBones, outputStates, registry) - - private fun effectiveRoutes(routes: Routes, outputStates: OutputStates): Routes = effectiveRoutes(routes, outputStates, registry) - @Test fun `the driver alone takes every bone it supports`() { val routes = computeAutomaticRoutes(COMMON_CANDIDATES, active(RoutingOutput.DRIVER)) diff --git a/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt b/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt index 501c65015..508187be1 100644 --- a/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt +++ b/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt @@ -1,8 +1,6 @@ package dev.slimevr.routing import dev.slimevr.config.BoneRoutingConfig -import dev.slimevr.skeleton.BoneRegistry -import dev.slimevr.skeleton.boneId import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.RoutingOutput import solarxr_protocol.rpc.RoutingOutputState @@ -10,8 +8,6 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull -private val registry = BoneRegistry.standard() - private fun active(vararg outputs: RoutingOutput): OutputStates = RoutingOutput.entries.associateWith { if (it in outputs) RoutingOutputState.ACTIVE else RoutingOutputState.INACTIVE } @@ -19,16 +15,14 @@ private fun active(vararg outputs: RoutingOutput): OutputStates = RoutingOutput. private val NONE_ACTIVE = active() private val ALL_ON = active(*RoutingOutput.entries.toTypedArray()) -private fun routesOf(vararg pairs: Pair>): Routes = pairs.associate { (bodyPart, outputs) -> bodyPart.boneId to outputs } - -private fun manualRoutesOf(manualRoutes: Map>?): Routes = manualRoutesAsBoneIds(manualRoutes, registry) +private fun routesOf(vararg pairs: Pair>): Routes = mapOf(*pairs) private val AUTO_ROUTES = routesOf( BodyPart.HIP to setOf(RoutingOutput.DRIVER), BodyPart.LEFT_FOOT to setOf(RoutingOutput.DRIVER), ) -private val HAND_TABLE = routesOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER)) +private val HAND_TABLE = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER)) class ManualRoutesTest { @Test @@ -37,11 +31,11 @@ class ManualRoutesTest { BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC), ) - val sanitized = effectiveRoutes(routes, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC), registry) + val sanitized = effectiveRoutes(routes, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC)) assertEquals( setOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC), - sanitized[BodyPart.HIP.boneId], + sanitized[BodyPart.HIP], ) } @@ -49,25 +43,25 @@ class ManualRoutesTest { fun `an unavailable output is dropped even when explicitly routed`() { val routes = routesOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC)) - val sanitized = effectiveRoutes(routes, active(RoutingOutput.VRC_OSC), registry) + val sanitized = effectiveRoutes(routes, active(RoutingOutput.VRC_OSC)) - assertEquals(setOf(RoutingOutput.VRC_OSC), sanitized[BodyPart.HIP.boneId]) + assertEquals(setOf(RoutingOutput.VRC_OSC), sanitized[BodyPart.HIP]) } @Test fun `an output that cannot take the bone is dropped`() { val routes = routesOf(BodyPart.NECK to setOf(RoutingOutput.VRC_OSC, RoutingOutput.VMC)) - val sanitized = effectiveRoutes(routes, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC), registry) + val sanitized = effectiveRoutes(routes, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC)) - assertEquals(setOf(RoutingOutput.VMC), sanitized[BodyPart.NECK.boneId]) + assertEquals(setOf(RoutingOutput.VMC), sanitized[BodyPart.NECK]) } @Test fun `a bone left with no output is not kept`() { val routes = routesOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) - assertEquals(emptyMap(), effectiveRoutes(routes, NONE_ACTIVE, registry)) + assertEquals(emptyMap(), effectiveRoutes(routes, NONE_ACTIVE)) } } @@ -84,7 +78,7 @@ class RoutingChangeTest { fun `switching to manual the first time starts from an empty table`() { val config = BoneRoutingConfig(automatic = true, manualRoutes = null) - val next = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES, registry = registry) + val next = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES) assertEquals(false, next.automatic) assertEquals(emptyMap(), next.manualRoutes.orEmpty()) @@ -93,38 +87,38 @@ class RoutingChangeTest { @Test fun `switching to manual again keeps the table the user built`() { val built = routesOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) - val config = BoneRoutingConfig(automatic = true, manualRoutes = built.toManualRoutesConfig(registry)) + val config = BoneRoutingConfig(automatic = true, manualRoutes = built) - val next = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES, registry = registry) + val next = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES) - assertEquals(built, manualRoutesOf(next.manualRoutes)) + assertEquals(built, next.manualRoutes) } @Test fun `editing while manual stores the new table`() { - val config = BoneRoutingConfig(automatic = false, manualRoutes = HAND_TABLE.toManualRoutesConfig(registry)) - val edited = routesOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) + val config = BoneRoutingConfig(automatic = false, manualRoutes = HAND_TABLE) + val edited = mapOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) - val next = applyRoutingChange(config, automatic = false, routes = edited, registry = registry) + val next = applyRoutingChange(config, automatic = false, routes = edited) - assertEquals(edited, manualRoutesOf(next.manualRoutes)) + assertEquals(edited, next.manualRoutes) } @Test fun `switching back to automatic keeps the manual table`() { - val config = BoneRoutingConfig(automatic = false, manualRoutes = HAND_TABLE.toManualRoutesConfig(registry)) + val config = BoneRoutingConfig(automatic = false, manualRoutes = HAND_TABLE) - val next = applyRoutingChange(config, automatic = true, routes = emptyMap(), registry = registry) + val next = applyRoutingChange(config, automatic = true, routes = emptyMap()) assertEquals(true, next.automatic) - assertEquals(HAND_TABLE, manualRoutesOf(next.manualRoutes)) + assertEquals(HAND_TABLE, next.manualRoutes) } @Test fun `staying automatic never creates a manual table`() { val config = BoneRoutingConfig(automatic = true, manualRoutes = null) - val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES, registry = registry) + val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES) assertEquals(emptyMap(), next.manualRoutes) } @@ -134,12 +128,12 @@ class RoutingChangeTest { var config = BoneRoutingConfig(automatic = true, manualRoutes = null) val built = AUTO_ROUTES + HAND_TABLE - config = applyRoutingChange(config, automatic = false, routes = emptyMap(), registry = registry) - config = applyRoutingChange(config, automatic = false, routes = built, registry = registry) - config = applyRoutingChange(config, automatic = true, routes = emptyMap(), registry = registry) - config = applyRoutingChange(config, automatic = false, routes = emptyMap(), registry = registry) + config = applyRoutingChange(config, automatic = false, routes = emptyMap()) + config = applyRoutingChange(config, automatic = false, routes = built) + config = applyRoutingChange(config, automatic = true, routes = emptyMap()) + config = applyRoutingChange(config, automatic = false, routes = emptyMap()) - assertEquals(built, manualRoutesOf(config.manualRoutes)) + assertEquals(built, config.manualRoutes) } } @@ -149,11 +143,10 @@ class ForcedRoutesTest { val config = applyRoutingChange( BoneRoutingConfig(automatic = false, manualRoutes = emptyMap()), automatic = false, - routes = routesOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VMC)), - registry = registry, + routes = mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VMC)), ) - assertEquals(routesOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), manualRoutesOf(config.manualRoutes)) + assertEquals(mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), config.manualRoutes) } @Test @@ -161,8 +154,7 @@ class ForcedRoutesTest { val config = applyRoutingChange( BoneRoutingConfig(automatic = false, manualRoutes = emptyMap()), automatic = false, - routes = routesOf(BodyPart.NECK to setOf(RoutingOutput.VMC)), - registry = registry, + routes = mapOf(BodyPart.NECK to setOf(RoutingOutput.VMC)), ) assertEquals(emptyMap(), config.manualRoutes) @@ -172,44 +164,43 @@ class ForcedRoutesTest { fun `required bones come back when the routes are resolved`() { val config = BoneRoutingConfig( automatic = false, - manualRoutes = routesOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)).toManualRoutesConfig(registry), + manualRoutes = mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), ) val resolved = effectiveRoutes( - manualRoutesOf(config.manualRoutes), + config.manualRoutes.orEmpty(), active(RoutingOutput.DRIVER, RoutingOutput.VMC), - registry, ) - assertEquals(setOf(RoutingOutput.DRIVER, RoutingOutput.VMC), resolved[BodyPart.HIP.boneId]) - assertEquals(setOf(RoutingOutput.VMC), resolved[BodyPart.NECK.boneId]) + assertEquals(setOf(RoutingOutput.DRIVER, RoutingOutput.VMC), resolved[BodyPart.HIP]) + assertEquals(setOf(RoutingOutput.VMC), resolved[BodyPart.NECK]) } @Test fun `an inactive output does not force anything`() { val config = BoneRoutingConfig(automatic = false, manualRoutes = emptyMap()) - val resolved = effectiveRoutes(manualRoutesOf(config.manualRoutes), active(RoutingOutput.DRIVER), registry) + val resolved = effectiveRoutes(config.manualRoutes.orEmpty(), active(RoutingOutput.DRIVER)) assertEquals(emptyMap(), resolved) } @Test fun `the page shows required bones ticked whatever is stored`() { - val shown = effectiveRoutes(emptyMap(), ALL_ON, registry) + val shown = effectiveRoutes(emptyMap(), ALL_ON) - assertEquals(setOf(RoutingOutput.VMC), shown[BodyPart.NECK.boneId]) + assertEquals(setOf(RoutingOutput.VMC), shown[BodyPart.NECK]) } @Test fun `automatic gets required bones through the same step as manual`() { val states = active(RoutingOutput.DRIVER, RoutingOutput.VMC) - val automatic = effectiveRoutes(computeAutomaticRoutes(setOf(BodyPart.HIP), states, registry), states, registry) - val manual = effectiveRoutes(routesOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), states, registry) + val automatic = effectiveRoutes(computeAutomaticRoutes(setOf(BodyPart.HIP), states), states) + val manual = effectiveRoutes(mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), states) - assertEquals(automatic[BodyPart.NECK.boneId], manual[BodyPart.NECK.boneId]) - assertEquals(automatic[BodyPart.HIP.boneId], manual[BodyPart.HIP.boneId]) + assertEquals(automatic[BodyPart.NECK], manual[BodyPart.NECK]) + assertEquals(automatic[BodyPart.HIP], manual[BodyPart.HIP]) } @Test @@ -233,25 +224,25 @@ class OverrideRoutesTest { fun `automatic routes no hands on its own`() { val candidates = determineCandidateBones(setOf(BodyPart.LEFT_HAND, BodyPart.HIP)) - val routes = computeAutomaticRoutes(candidates, ALL_ON, registry) + val routes = computeAutomaticRoutes(candidates, ALL_ON) - assertNull(routes[BodyPart.LEFT_HAND.boneId]) + assertNull(routes[BodyPart.LEFT_HAND]) } @Test fun `an override routes the hand while automatic`() { - val config = BoneRoutingConfig(automatic = true, manualRoutes = HAND_TABLE.toManualRoutesConfig(registry)) + val config = BoneRoutingConfig(automatic = true, manualRoutes = HAND_TABLE) - val routes = computeAutomaticRoutes(determineCandidateBones(emptySet()), ALL_ON, registry) + overrideRoutes(config, registry) + val routes = computeAutomaticRoutes(determineCandidateBones(emptySet()), ALL_ON) + overrideRoutes(config) - assertEquals(setOf(RoutingOutput.DRIVER), routes[BodyPart.LEFT_HAND.boneId]) + assertEquals(setOf(RoutingOutput.DRIVER), routes[BodyPart.LEFT_HAND]) } @Test fun `only the overridable bones of a stored table count as overrides`() { - val config = BoneRoutingConfig(automatic = true, manualRoutes = (AUTO_ROUTES + HAND_TABLE).toManualRoutesConfig(registry)) + val config = BoneRoutingConfig(automatic = true, manualRoutes = AUTO_ROUTES + HAND_TABLE) - assertEquals(HAND_TABLE, overrideRoutes(config, registry)) + assertEquals(HAND_TABLE, overrideRoutes(config)) } @Test @@ -261,8 +252,7 @@ class OverrideRoutesTest { val next = applyRoutingChange( config, automatic = true, - routes = routesOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.VMC)), - registry = registry, + routes = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.VMC)), ) assertEquals(emptyMap(), next.manualRoutes) @@ -272,26 +262,26 @@ class OverrideRoutesTest { fun `editing while automatic stores the override and nothing else`() { val config = BoneRoutingConfig(automatic = true, manualRoutes = null) - val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES + HAND_TABLE, registry = registry) + val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES + HAND_TABLE) - assertEquals(HAND_TABLE, manualRoutesOf(next.manualRoutes)) + assertEquals(HAND_TABLE, next.manualRoutes) } @Test fun `editing while automatic leaves a stored manual table alone`() { val stored = routesOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) - val config = BoneRoutingConfig(automatic = true, manualRoutes = stored.toManualRoutesConfig(registry)) + val config = BoneRoutingConfig(automatic = true, manualRoutes = stored) - val next = applyRoutingChange(config, automatic = true, routes = HAND_TABLE, registry = registry) + val next = applyRoutingChange(config, automatic = true, routes = HAND_TABLE) - assertEquals(stored + HAND_TABLE, manualRoutesOf(next.manualRoutes)) + assertEquals(stored + HAND_TABLE, next.manualRoutes) } @Test fun `dropping the hand from the request clears the override`() { - val config = BoneRoutingConfig(automatic = true, manualRoutes = HAND_TABLE.toManualRoutesConfig(registry)) + val config = BoneRoutingConfig(automatic = true, manualRoutes = HAND_TABLE) - val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES, registry = registry) + val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES) assertEquals(emptyMap(), next.manualRoutes) } @@ -300,10 +290,10 @@ class OverrideRoutesTest { fun `the override survives a round trip through manual`() { var config = BoneRoutingConfig(automatic = true, manualRoutes = null) - config = applyRoutingChange(config, automatic = true, routes = HAND_TABLE, registry = registry) - config = applyRoutingChange(config, automatic = false, routes = emptyMap(), registry = registry) - config = applyRoutingChange(config, automatic = true, routes = emptyMap(), registry = registry) + config = applyRoutingChange(config, automatic = true, routes = HAND_TABLE) + config = applyRoutingChange(config, automatic = false, routes = emptyMap()) + config = applyRoutingChange(config, automatic = true, routes = emptyMap()) - assertEquals(setOf(RoutingOutput.DRIVER), overrideRoutes(config, registry)[BodyPart.LEFT_HAND.boneId]) + assertEquals(setOf(RoutingOutput.DRIVER), overrideRoutes(config)[BodyPart.LEFT_HAND]) } } diff --git a/server/core/src/test/java/dev/slimevr/skeleton/BodyPartHierarchyTest.kt b/server/core/src/test/java/dev/slimevr/skeleton/BodyPartHierarchyTest.kt new file mode 100644 index 000000000..c30e5beca --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/skeleton/BodyPartHierarchyTest.kt @@ -0,0 +1,59 @@ +package dev.slimevr.skeleton + +import solarxr_protocol.datatypes.BodyPart +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * [iterateBodyPartHierarchy] returns a traversal derived once at class init rather than walked per + * call. That is only safe while the cached result matches a fresh walk of [BODY_PART_HIERARCHY_MAP], + * so this pins the two together: order included, since [buildBones] relies on a parent being visited + * before its children. + */ +class BodyPartHierarchyTest { + + private fun walk(root: BodyPart, onlyChildren: Boolean): List> { + val expected = mutableListOf>() + fun visit(parent: BodyPart?, bone: BodyPart, skipSelf: Boolean) { + if (!skipSelf) expected += parent to bone + for (child in BODY_PART_HIERARCHY_MAP[bone] ?: return) visit(bone, child, false) + } + visit(null, root, onlyChildren) + return expected + } + + @Test + fun `cached traversal matches a fresh walk for every root`() { + for (root in BodyPart.entries) { + for (onlyChildren in listOf(false, true)) { + assertEquals( + walk(root, onlyChildren), + iterateBodyPartHierarchy(root, onlyChildren), + "traversal drifted for root=$root onlyChildren=$onlyChildren", + ) + } + } + } + + @Test + fun `every bone is visited after its parent`() { + val seen = mutableSetOf() + for ((parent, bone) in iterateBodyPartHierarchy()) { + if (parent != null) { + assertTrue(parent in seen, "$bone was visited before its parent $parent") + } + seen += bone + } + } + + @Test + fun `repeated calls hand back the same instance`() { + assertSame( + iterateBodyPartHierarchy(BodyPart.LEFT_HAND, true), + iterateBodyPartHierarchy(BodyPart.LEFT_HAND, true), + "the traversal is meant to be derived once, not rebuilt per call", + ) + } +} diff --git a/server/core/src/test/java/dev/slimevr/skeleton/BoneRegistryTest.kt b/server/core/src/test/java/dev/slimevr/skeleton/BoneRegistryTest.kt deleted file mode 100644 index 175f06fa5..000000000 --- a/server/core/src/test/java/dev/slimevr/skeleton/BoneRegistryTest.kt +++ /dev/null @@ -1,188 +0,0 @@ -package dev.slimevr.skeleton - -import solarxr_protocol.connection.BoneDefinition -import solarxr_protocol.datatypes.BodyPart -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertSame -import kotlin.test.assertTrue -import solarxr_protocol.connection.BoneRegistry as WireBoneRegistry - -class BoneRegistryTest { - private val registry = BoneRegistry.standard() - - @Test - fun `standard registry resolves every standardized body part`() { - for (bodyPart in BodyPart.entries) { - if (bodyPart == BodyPart.NONE) continue - val id = assertNotNull(registry[bodyPart], "Expected an ID for $bodyPart") - assertEquals(bodyPart, registry.bodyPartOf(id)) - } - } - - @Test - fun `unknown ID resolves to no definition`() { - assertNull(registry[BoneId(0xdeadu)]) - } - - @Test - fun `accepts a multi-level parent chain`() { - val registry = BoneRegistry.from( - WireBoneRegistry( - bones = listOf( - BoneDefinition(1u, "a", null, 0u, null), - BoneDefinition(2u, "b", null, 1u, null), - BoneDefinition(3u, "c", null, 2u, null), - ), - ), - ) - assertNotNull(registry[BoneId(3u)]) - } - - @Test - fun `rejects duplicate IDs`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf( - BoneDefinition(1u, "a", null, 0u, null), - BoneDefinition(1u, "b", null, 0u, null), - ), - ), - ) - } - } - - @Test - fun `rejects ID 0`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf(BoneDefinition(0u, "a", null, 0u, null)), - ), - ) - } - } - - @Test - fun `rejects an unknown parent`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf(BoneDefinition(1u, "a", null, 2u, null)), - ), - ) - } - } - - @Test - fun `rejects a cycle`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf( - BoneDefinition(1u, "a", null, 2u, null), - BoneDefinition(2u, "b", null, 1u, null), - ), - ), - ) - } - } - - @Test - fun `rejects a bone that is its own parent`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf(BoneDefinition(1u, "a", null, 1u, null)), - ), - ) - } - } - - @Test - fun `rejects duplicate standard body parts`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf( - BoneDefinition(1u, "a", null, 0u, BodyPart.HIP), - BoneDefinition(2u, "b", null, 0u, BodyPart.HIP), - ), - ), - ) - } - } - - @Test - fun `rejects non-contiguous IDs`() { - assertFailsWith { - BoneRegistry.from( - WireBoneRegistry( - bones = listOf( - BoneDefinition(1u, "a", null, 0u, null), - BoneDefinition(3u, "b", null, 0u, null), - ), - ), - ) - } - } - - /** - * [BoneRegistry.hierarchyFrom] returns a traversal cached lazily per registry rather than walked - * every call. That is only safe while the cached result matches a fresh walk of - * [BODY_PART_HIERARCHY_MAP], so this pins the two together: order included, since [buildBones] - * relies on a parent being visited before its children. - */ - private fun walk(root: BodyPart, onlyChildren: Boolean): List> { - val expected = mutableListOf>() - fun visit(parent: BodyPart?, bone: BodyPart, skipSelf: Boolean) { - if (!skipSelf) expected += parent to bone - for (child in BODY_PART_HIERARCHY_MAP[bone] ?: return) visit(bone, child, false) - } - visit(null, root, onlyChildren) - return expected - } - - @Test - fun `cached traversal matches a fresh walk for every root`() { - for (root in BodyPart.entries) { - if (root == BodyPart.NONE) continue - val rootId = requireNotNull(registry[root]) - for (onlyChildren in listOf(false, true)) { - val actual = registry.hierarchyFrom(rootId, onlyChildren) - .map { (parentId, boneId) -> parentId?.let { registry.bodyPartOf(it) } to requireNotNull(registry.bodyPartOf(boneId)) } - assertEquals( - walk(root, onlyChildren), - actual, - "traversal drifted for root=$root onlyChildren=$onlyChildren", - ) - } - } - } - - @Test - fun `every bone is visited after its parent`() { - val seen = mutableSetOf() - val headId = requireNotNull(registry[BodyPart.HEAD]) - for ((parent, boneId) in registry.hierarchyFrom(headId)) { - if (parent != null) { - assertTrue(parent in seen, "$boneId was visited before its parent $parent") - } - seen += boneId - } - } - - @Test - fun `repeated calls hand back the same instance`() { - val leftHandId = requireNotNull(registry[BodyPart.LEFT_HAND]) - assertSame( - registry.hierarchyFrom(leftHandId, true), - registry.hierarchyFrom(leftHandId, true), - "the traversal is meant to be derived once, not rebuilt per call", - ) - } -} diff --git a/server/core/src/test/java/dev/slimevr/skeleton/IKTest.kt b/server/core/src/test/java/dev/slimevr/skeleton/IKTest.kt index 6693aeac4..48e62ca6c 100644 --- a/server/core/src/test/java/dev/slimevr/skeleton/IKTest.kt +++ b/server/core/src/test/java/dev/slimevr/skeleton/IKTest.kt @@ -9,31 +9,29 @@ import kotlin.test.Test class IKTest { @Test fun testCcdIk() { - val registry = BoneRegistry.standard() - - val boneInputs: InputSkeleton = BoneMap.of(registry) - boneInputs[BodyPart.NECK.boneId] = DEFAULT_BONE_INPUT.copy( - boneId = BodyPart.NECK.boneId, + val boneInputs: InputSkeleton = bodyPartMap() + boneInputs[BodyPart.NECK] = DEFAULT_BONE_INPUT.copy( + bodyPart = BodyPart.NECK, offset = Vector3.NEG_Y, ) - boneInputs[BodyPart.UPPER_CHEST.boneId] = DEFAULT_BONE_INPUT.copy( - boneId = BodyPart.UPPER_CHEST.boneId, + boneInputs[BodyPart.UPPER_CHEST] = DEFAULT_BONE_INPUT.copy( + bodyPart = BodyPart.UPPER_CHEST, offset = Vector3.NEG_Y, ) - boneInputs[BodyPart.LOWER_CHEST.boneId] = DEFAULT_BONE_INPUT.copy( - boneId = BodyPart.LOWER_CHEST.boneId, + boneInputs[BodyPart.LOWER_CHEST] = DEFAULT_BONE_INPUT.copy( + bodyPart = BodyPart.LOWER_CHEST, offset = Vector3.NEG_Y, ) - boneInputs[BodyPart.UPPER_WAIST.boneId] = DEFAULT_BONE_INPUT.copy( - boneId = BodyPart.UPPER_WAIST.boneId, + boneInputs[BodyPart.UPPER_WAIST] = DEFAULT_BONE_INPUT.copy( + bodyPart = BodyPart.UPPER_WAIST, offset = Vector3.NEG_Y, ) - boneInputs[BodyPart.LOWER_WAIST.boneId] = DEFAULT_BONE_INPUT.copy( - boneId = BodyPart.LOWER_WAIST.boneId, + boneInputs[BodyPart.LOWER_WAIST] = DEFAULT_BONE_INPUT.copy( + bodyPart = BodyPart.LOWER_WAIST, offset = Vector3.NEG_Y, ) - boneInputs[BodyPart.HIP.boneId] = DEFAULT_BONE_INPUT.copy( - boneId = BodyPart.HIP.boneId, + boneInputs[BodyPart.HIP] = DEFAULT_BONE_INPUT.copy( + bodyPart = BodyPart.HIP, offset = Vector3.NEG_Y, ) @@ -41,20 +39,20 @@ class IKTest { val target = Vector3.POS_X * 3f val goal = IKChainGoal( listOf( - BodyPart.NECK.boneId, - BodyPart.UPPER_CHEST.boneId, - BodyPart.LOWER_CHEST.boneId, - BodyPart.UPPER_WAIST.boneId, - BodyPart.LOWER_WAIST.boneId, - BodyPart.HIP.boneId, + BodyPart.NECK, + BodyPart.UPPER_CHEST, + BodyPart.LOWER_CHEST, + BodyPart.UPPER_WAIST, + BodyPart.LOWER_WAIST, + BodyPart.HIP, ), target, ) - val ikOut = ccdIk(boneInputs, bones, listOf(goal), BODY_PART_CONSTRAINT_MAP.resolveToBoneIds(), 0.01f, 100) + val ikOut = ccdIk(boneInputs, bones, listOf(goal), BODY_PART_CONSTRAINT_MAP, 0.01f, 100) assert(ikOut.goalsReached.all { it.value }) { val boneRots = ikOut.bones.values.joinToString { - "${it.boneId}: ${it.rotation.toEulerAngles(EulerOrder.YZX)}" + "${it.bodyPart}: ${it.rotation.toEulerAngles(EulerOrder.YZX)}" } val targetDist = chainDistanceFromTarget(ikOut.bones, goal.chain, goal.target) "Failed to reach target:\nDistance from target: $targetDist\nBone rotations: $boneRots" diff --git a/server/core/src/test/java/dev/slimevr/solarxr/ConnectionInitTest.kt b/server/core/src/test/java/dev/slimevr/solarxr/ConnectionInitTest.kt deleted file mode 100644 index a2baf995e..000000000 --- a/server/core/src/test/java/dev/slimevr/solarxr/ConnectionInitTest.kt +++ /dev/null @@ -1,162 +0,0 @@ -package dev.slimevr.solarxr - -import com.google.flatbuffers.FlatBufferBuilder -import dev.slimevr.EventDispatcher -import dev.slimevr.TestAppContext -import dev.slimevr.buildTestSkeleton -import dev.slimevr.buildTestVrServer -import dev.slimevr.context.Context -import dev.slimevr.fbscodegen.runtime.JvmFlatBufferWriter -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest -import solarxr_protocol.ClientHello -import solarxr_protocol.HelloStatus -import solarxr_protocol.MessageBundle -import solarxr_protocol.ServerHello -import solarxr_protocol.connection.BoneDefinition -import solarxr_protocol.connection.BoneRegistry -import solarxr_protocol.connection.ConfigurationAcknowledged -import solarxr_protocol.connection.ConnectionError -import solarxr_protocol.connection.ConnectionErrorCode -import solarxr_protocol.connection.ConnectionMessageHeader -import solarxr_protocol.data_feed.DataFeedMessageHeader -import solarxr_protocol.data_feed.StartDataFeed -import java.nio.ByteBuffer -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -@OptIn(ExperimentalCoroutinesApi::class) -private fun TestScope.buildTestBridge(sent: MutableList): SolarXRBridge { - val appContext = object : TestAppContext() { - override val server = buildTestVrServer(backgroundScope) - override val skeleton = buildTestSkeleton(backgroundScope) - } - val context = Context.create( - initialState = SolarXRBridgeState(), - scope = backgroundScope, - reducer = ::reduce, - name = "ConnectionInitTest", - ) - val bridge = SolarXRBridge( - id = 1, - context = context, - appContext = appContext, - dataFeedDispatcher = EventDispatcher("test.datafeed", backgroundScope), - rpcDispatcher = EventDispatcher("test.rpc", backgroundScope), - driverDispatcher = EventDispatcher("test.driver", backgroundScope), - ) - bridge.outbound.on { sent += it }.launchIn(backgroundScope) - runCurrent() - return bridge -} - -private fun MessageBundle.singleConnectionError(): ConnectionError = connectionMsgs?.single()?.message as? ConnectionError ?: error("Expected a single ConnectionError") - -@OptIn(ExperimentalCoroutinesApi::class) -class ConnectionInitTest { - - @Test - fun `checkedSolarXRFrame rejects a wrong identifier`() { - val fbb = FlatBufferBuilder(64) - ClientHello(protocolVersion = SOLARXR_PROTOCOL_VERSION).finish(JvmFlatBufferWriter(fbb)) - assertFailsWith { - checkedSolarXRFrame(fbb.dataBuffer(), ServerHello.FILE_IDENTIFIER) - } - } - - @Test - fun `checkedSolarXRFrame rejects a truncated frame`() { - assertFailsWith { - checkedSolarXRFrame(ByteBuffer.allocate(4), ClientHello.FILE_IDENTIFIER) - } - } - - @Test - fun `checkedSolarXRFrame rejects an oversized frame`() { - assertFailsWith { - checkedSolarXRFrame(ByteBuffer.allocate(SOLARXR_MAX_FRAME_SIZE + 1), ClientHello.FILE_IDENTIFIER) - } - } - - @Test - fun `ClientHello, ServerHello and MessageBundle round-trip with their identifiers`() { - val helloFbb = FlatBufferBuilder(64) - ClientHello(protocolVersion = SOLARXR_PROTOCOL_VERSION).finish(JvmFlatBufferWriter(helloFbb)) - val helloReader = checkedSolarXRFrame(helloFbb.dataBuffer(), ClientHello.FILE_IDENTIFIER) - assertTrue(ClientHello.hasIdentifier(helloReader)) - assertEquals(SOLARXR_PROTOCOL_VERSION, ClientHello.fromByteBuffer(helloReader).protocolVersion) - - val replyFbb = FlatBufferBuilder(64) - ServerHello(HelloStatus.ACCEPTED, SOLARXR_PROTOCOL_VERSION).finish(JvmFlatBufferWriter(replyFbb)) - val replyReader = checkedSolarXRFrame(replyFbb.dataBuffer(), ServerHello.FILE_IDENTIFIER) - assertTrue(ServerHello.hasIdentifier(replyReader)) - assertEquals(HelloStatus.ACCEPTED, ServerHello.fromByteBuffer(replyReader).status) - - val bundleFbb = FlatBufferBuilder(64) - MessageBundle(connectionMsgs = listOf(ConnectionMessageHeader(ConfigurationAcknowledged()))) - .finish(JvmFlatBufferWriter(bundleFbb)) - val bundleReader = checkedSolarXRFrame(bundleFbb.dataBuffer(), MessageBundle.FILE_IDENTIFIER) - assertTrue(MessageBundle.hasIdentifier(bundleReader)) - assertTrue(MessageBundle.fromByteBuffer(bundleReader).connectionMsgs?.single()?.message is ConfigurationAcknowledged) - } - - @Test - fun `application bundles are rejected before configuration completes`() = runTest { - val sent = mutableListOf() - val bridge = buildTestBridge(sent) - var dispatched = false - bridge.dataFeedDispatcher.on { dispatched = true }.launchIn(backgroundScope) - runCurrent() - - onSolarXRMessage( - MessageBundle(dataFeedMsgs = listOf(DataFeedMessageHeader(message = StartDataFeed(dataFeeds = emptyList())))), - bridge, - ) - runCurrent() - - assertFalse(dispatched) - assertEquals(ConnectionErrorCode.INITIALIZATION_REQUIRED, sent.single().singleConnectionError().code) - } - - @Test - fun `application bundles dispatch once configuration completes`() = runTest { - val sent = mutableListOf() - val bridge = buildTestBridge(sent) - var dispatched = false - bridge.dataFeedDispatcher.on { dispatched = true }.launchIn(backgroundScope) - runCurrent() - - onSolarXRMessage(MessageBundle(connectionMsgs = listOf(ConnectionMessageHeader(ConfigurationAcknowledged()))), bridge) - runCurrent() - assertTrue(bridge.isReady) - - onSolarXRMessage( - MessageBundle(dataFeedMsgs = listOf(DataFeedMessageHeader(message = StartDataFeed(dataFeeds = emptyList())))), - bridge, - ) - runCurrent() - - assertTrue(dispatched) - } - - @Test - fun `a client-sent bone registry is silently ignored`() = runTest { - val sent = mutableListOf() - val bridge = buildTestBridge(sent) - - val clientRegistry = BoneRegistry( - bones = listOf(BoneDefinition(1u, "x", null, 0u, null)), - ) - onSolarXRMessage(MessageBundle(connectionMsgs = listOf(ConnectionMessageHeader(clientRegistry))), bridge) - runCurrent() - - assertTrue(sent.isEmpty()) - // The registry stays the server-issued default; the client's attempt never lands. - assertEquals(dev.slimevr.skeleton.BoneRegistry.standard().value, bridge.registry.value) - } -} diff --git a/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt b/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt index 4390878f1..033c30222 100644 --- a/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt +++ b/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt @@ -9,7 +9,6 @@ import dev.slimevr.buildTestSkeleton import dev.slimevr.buildTestUserConfig import dev.slimevr.buildTestVrServer import dev.slimevr.context.Context -import dev.slimevr.skeleton.BoneId import dev.slimevr.solarxr.datafeed.DataFeedInitBehaviour import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope @@ -18,17 +17,13 @@ import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import solarxr_protocol.MessageBundle import solarxr_protocol.data_feed.DataFeedConfig -import solarxr_protocol.data_feed.DataFeedUpdate import solarxr_protocol.data_feed.PollDataFeed import solarxr_protocol.data_feed.StartDataFeed -import solarxr_protocol.datatypes.BodyPart -import solarxr_protocol.datatypes.BoneMask import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) -private fun TestScope.testConn(onSend: suspend (MessageBundle) -> Unit): SolarXRBridge { +private fun TestScope.testConn(onSend: suspend (ByteArray) -> Unit): SolarXRBridge { val server = buildTestVrServer(backgroundScope) val skeleton = buildTestSkeleton(backgroundScope) val settings = buildTestSettings(backgroundScope) @@ -56,7 +51,7 @@ private fun TestScope.testConn(onSend: suspend (MessageBundle) -> Unit): SolarXR rpcDispatcher = EventDispatcher("test.rpc", backgroundScope), ) bridge.startObserving() - bridge.outbound.on { onSend(it) }.launchIn(backgroundScope) + bridge.outbound.on { onSend(ByteArray(0)) }.launchIn(backgroundScope) // launchIn registers the handler synchronously, but the dispatcher's own drain loop still has to // start before anything emitted here can reach it. @@ -137,22 +132,5 @@ class DataFeedTest { assertEquals(0, sendCount) } - @Test - fun `emitted bones carry the registry ID for their body part`() = runTest { - val bundles = mutableListOf() - val conn = testConn { bundles += it } - val boneMask = BoneMask(boneLength = true) - - conn.dataFeedDispatcher.emit(PollDataFeed(config = config(100).copy(boneMask = boneMask))) - advanceTimeBy(1) - - val bones = (bundles.single().dataFeedMsgs?.single()?.message as DataFeedUpdate).bones - assertTrue(!bones.isNullOrEmpty()) - - val hipId = requireNotNull(conn.registry[BodyPart.HIP]) - assertTrue(bones.any { it.id == hipId.value }) - bones.forEach { bone -> assertTrue(conn.registry[BoneId(bone.id)] != null) } - } - // TODO: need more tests for the content of a datafeed + check if the masks work } diff --git a/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt b/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt index 6615d5908..bd112bcc9 100644 --- a/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt +++ b/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt @@ -3,8 +3,6 @@ package dev.slimevr.stayaligned import dev.slimevr.config.StayAlignedConfig import dev.slimevr.config.StayAlignedRelaxedPoseConfig import dev.slimevr.math.angle.Angle -import dev.slimevr.skeleton.BoneRegistry -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.Motion import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.stayaligned.TrackerYawCorrection @@ -24,8 +22,6 @@ import kotlin.test.assertNull */ class ComputeYawCorrectionTest { - val registry = BoneRegistry.standard() - val enabledStayAlignedConfig = StayAlignedConfig( enabled = true, standingRelaxedPose = StayAlignedRelaxedPoseConfig(true), @@ -50,7 +46,7 @@ class ComputeYawCorrectionTest { val lockedTrackerState = Tracker.DEFAULT_STATE.copy( motion = Motion.RESTING, - boneId = BodyPart.HIP.boneId, + bodyPart = BodyPart.HIP, status = TrackerStatus.OK, stayAlignedData = Tracker.DEFAULT_STATE.stayAlignedData.copy(lockedRotation = pointFiveYaw), ) @@ -68,7 +64,6 @@ class ComputeYawCorrectionTest { listOf(lockedTrackerState), Angle(0.002f), enabledStayAlignedConfig, - registry, ) assertNotNull(result) @@ -82,7 +77,6 @@ class ComputeYawCorrectionTest { listOf(lockedTrackerState), Angle(0f), enabledStayAlignedConfig, - registry, ) assertNotNull(result) @@ -96,7 +90,6 @@ class ComputeYawCorrectionTest { listOf(primarilyAtRestTrackerState), Angle(0.002f), enabledStayAlignedConfig, - registry, ) assertNull(result) @@ -108,14 +101,13 @@ class ComputeYawCorrectionTest { movingTrackerState, listOf( movingTrackerState, - movingTrackerState.copy(boneId = BodyPart.LEFT_UPPER_LEG.boneId, rotation = fiveYaw), - movingTrackerState.copy(boneId = BodyPart.RIGHT_UPPER_LEG.boneId, rotation = fiveYaw), - movingTrackerState.copy(boneId = BodyPart.LEFT_LOWER_LEG.boneId, rotation = fiveYaw), - movingTrackerState.copy(boneId = BodyPart.RIGHT_LOWER_LEG.boneId, rotation = fiveYaw), + movingTrackerState.copy(bodyPart = BodyPart.LEFT_UPPER_LEG, rotation = fiveYaw), + movingTrackerState.copy(bodyPart = BodyPart.RIGHT_UPPER_LEG, rotation = fiveYaw), + movingTrackerState.copy(bodyPart = BodyPart.LEFT_LOWER_LEG, rotation = fiveYaw), + movingTrackerState.copy(bodyPart = BodyPart.RIGHT_LOWER_LEG, rotation = fiveYaw), ), Angle(0.002f), enabledStayAlignedConfig, - registry, ) assertNotNull(result) diff --git a/server/core/src/test/java/dev/slimevr/tracker/YawResetSmoothingTest.kt b/server/core/src/test/java/dev/slimevr/tracker/YawResetSmoothingTest.kt index ca414689e..a2fe9b2e8 100644 --- a/server/core/src/test/java/dev/slimevr/tracker/YawResetSmoothingTest.kt +++ b/server/core/src/test/java/dev/slimevr/tracker/YawResetSmoothingTest.kt @@ -8,7 +8,6 @@ import dev.slimevr.buildTestTracker import dev.slimevr.buildTestVrServerStub import dev.slimevr.degreeToRadian import dev.slimevr.quaternionAssertEquals -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.behaviours.TrackerYawResetSmoothingBehaviour import io.github.axisangles.ktmath.Quaternion import kotlinx.coroutines.CoroutineScope @@ -35,7 +34,7 @@ class YawResetSmoothingTest { appContext, settings, id = 0, - boneId = BodyPart.LOWER_CHEST.boneId, + bodyPart = BodyPart.LOWER_CHEST, status = TrackerStatus.OK, rawRotation = raw, additionalBehaviours = listOf(TrackerYawResetSmoothingBehaviour()), diff --git a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt index b290c5196..419132e09 100644 --- a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt +++ b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt @@ -15,7 +15,6 @@ import dev.slimevr.resets.ResetBodyParts import dev.slimevr.resets.ResetsActions import dev.slimevr.resets.ResetsManager import dev.slimevr.routing.BoneRoutingManager -import dev.slimevr.skeleton.boneId import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import io.github.axisangles.ktmath.Vector3 @@ -87,8 +86,8 @@ class TrackingChecklistTest { appContext, settings, id = id, - boneId = bodyPart?.boneId, - intendedBoneId = intendedBodyPart?.boneId, + bodyPart = bodyPart, + intendedBodyPart = intendedBodyPart, status = status, origin = origin, imuType = imuType, @@ -125,7 +124,7 @@ class TrackingChecklistTest { assertEquals(true, h.step(TrackingChecklistStepId.FULL_RESET).valid) // Reassigning the tracker flags it again - tracker.context.dispatch(TrackerActions.Update { copy(boneId = BodyPart.HIP.boneId) }) + tracker.context.dispatch(TrackerActions.Update { copy(bodyPart = BodyPart.HIP) }) runCurrent() assertEquals(false, h.step(TrackingChecklistStepId.FULL_RESET).valid) } @@ -179,7 +178,7 @@ class TrackingChecklistTest { assertEquals(true, h.step(TrackingChecklistStepId.MOUNTING_CALIBRATION).enabled) assertEquals(false, h.step(TrackingChecklistStepId.MOUNTING_CALIBRATION).valid) - h.resetsManager.context.dispatch(ResetsActions.EndReset(ResetType.POSE_MOUNTING, boneIds = null)) + h.resetsManager.context.dispatch(ResetsActions.EndReset(ResetType.POSE_MOUNTING, bodyParts = null)) runCurrent() assertEquals(true, h.step(TrackingChecklistStepId.MOUNTING_CALIBRATION).valid) } @@ -193,7 +192,7 @@ class TrackingChecklistTest { assertEquals(true, h.step(TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION).enabled) assertEquals(false, h.step(TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION).valid) - h.resetsManager.context.dispatch(ResetsActions.EndReset(ResetType.POSE_MOUNTING, boneIds = ResetBodyParts.FEET.map { it.boneId })) + h.resetsManager.context.dispatch(ResetsActions.EndReset(ResetType.POSE_MOUNTING, bodyParts = ResetBodyParts.FEET.toList())) runCurrent() assertEquals(true, h.step(TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION).valid) } @@ -217,7 +216,7 @@ class TrackingChecklistTest { assertEquals(true, h.step(TrackingChecklistStepId.UNASSIGNED_HMD).enabled) assertEquals(false, h.step(TrackingChecklistStepId.UNASSIGNED_HMD).valid) - hmd.context.dispatch(TrackerActions.Update { copy(boneId = BodyPart.HEAD.boneId) }) + hmd.context.dispatch(TrackerActions.Update { copy(bodyPart = BodyPart.HEAD) }) runCurrent() assertEquals(true, h.step(TrackingChecklistStepId.UNASSIGNED_HMD).valid) } @@ -286,7 +285,7 @@ class TrackingChecklistTest { fun `STEAMVR_HANDS_ENABLED is disabled without a driver`() = runTest { val step = SteamVRHandsCheckBehaviour.computeStep( trackers = emptyList(), - routes = mapOf(BodyPart.LEFT_HAND.boneId to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND.boneId to setOf(RoutingOutput.DRIVER)), + routes = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND to setOf(RoutingOutput.DRIVER)), driverConnected = false, ) @@ -296,8 +295,8 @@ class TrackingChecklistTest { @Test fun `STEAMVR_HANDS_ENABLED flags hands sent to the driver while a controller is held`() = runTest { val step = SteamVRHandsCheckBehaviour.computeStep( - trackers = listOf(checklistTracker(Tracker.DEFAULT_STATE.copy(boneId = BodyPart.LEFT_HAND.boneId, origin = DeviceOrigin.UDP)), checklistTracker(Tracker.DEFAULT_STATE.copy(boneId = BodyPart.LEFT_HAND.boneId, origin = DeviceOrigin.DRIVER))), - routes = mapOf(BodyPart.LEFT_HAND.boneId to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND.boneId to setOf(RoutingOutput.DRIVER)), + trackers = listOf(checklistTracker(Tracker.DEFAULT_STATE.copy(bodyPart = BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP)), checklistTracker(Tracker.DEFAULT_STATE.copy(bodyPart = BodyPart.LEFT_HAND, origin = DeviceOrigin.DRIVER))), + routes = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND to setOf(RoutingOutput.DRIVER)), driverConnected = true, ) @@ -309,7 +308,7 @@ class TrackingChecklistTest { fun `STEAMVR_HANDS_ENABLED flags hands sent to the driver with no hand tracker worn`() = runTest { val step = SteamVRHandsCheckBehaviour.computeStep( trackers = emptyList(), - routes = mapOf(BodyPart.LEFT_HAND.boneId to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND.boneId to setOf(RoutingOutput.DRIVER)), + routes = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND to setOf(RoutingOutput.DRIVER)), driverConnected = true, ) @@ -321,8 +320,8 @@ class TrackingChecklistTest { @Test fun `STEAMVR_HANDS_ENABLED accepts hand trackers when no controller is held`() = runTest { val step = SteamVRHandsCheckBehaviour.computeStep( - trackers = listOf(checklistTracker(Tracker.DEFAULT_STATE.copy(boneId = BodyPart.LEFT_HAND.boneId, origin = DeviceOrigin.UDP))), - routes = mapOf(BodyPart.LEFT_HAND.boneId to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND.boneId to setOf(RoutingOutput.DRIVER)), + trackers = listOf(checklistTracker(Tracker.DEFAULT_STATE.copy(bodyPart = BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP))), + routes = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER), BodyPart.RIGHT_HAND to setOf(RoutingOutput.DRIVER)), driverConnected = true, ) @@ -332,7 +331,7 @@ class TrackingChecklistTest { @Test fun `STEAMVR_HANDS_ENABLED ignores hands that are not routed to the driver`() = runTest { val step = SteamVRHandsCheckBehaviour.computeStep( - trackers = listOf(checklistTracker(Tracker.DEFAULT_STATE.copy(boneId = BodyPart.LEFT_HAND.boneId, origin = DeviceOrigin.UDP)), checklistTracker(Tracker.DEFAULT_STATE.copy(boneId = BodyPart.LEFT_HAND.boneId, origin = DeviceOrigin.DRIVER))), + trackers = listOf(checklistTracker(Tracker.DEFAULT_STATE.copy(bodyPart = BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP)), checklistTracker(Tracker.DEFAULT_STATE.copy(bodyPart = BodyPart.LEFT_HAND, origin = DeviceOrigin.DRIVER))), routes = emptyMap(), driverConnected = true, ) diff --git a/server/core/src/test/java/dev/slimevr/vmc/InputDecoderTest.kt b/server/core/src/test/java/dev/slimevr/vmc/InputDecoderTest.kt index 2ed5e6700..f155f1041 100644 --- a/server/core/src/test/java/dev/slimevr/vmc/InputDecoderTest.kt +++ b/server/core/src/test/java/dev/slimevr/vmc/InputDecoderTest.kt @@ -1,6 +1,5 @@ package dev.slimevr.vmc -import dev.slimevr.computedSkeletonOf import dev.slimevr.config.VMCConfig import dev.slimevr.osc.OscArg import dev.slimevr.osc.OscBundle @@ -9,11 +8,9 @@ import dev.slimevr.osc.OscMessage import dev.slimevr.osc.forEachOscMessage import dev.slimevr.quaternionApproxEqual import dev.slimevr.skeleton.BodyPartMap -import dev.slimevr.skeleton.BoneRegistry import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.Velocity import dev.slimevr.skeleton.bodyPartMap -import dev.slimevr.skeleton.boneId import dev.slimevr.vectorAssertEquals import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 @@ -35,11 +32,9 @@ private fun assertApprox(expected: Quaternion, actual: Quaternion, message: Stri ) } -private val registry = BoneRegistry.standard() - private fun bone(bodyPart: BodyPart, rotation: Quaternion = Quaternion.IDENTITY, headPosition: Vector3 = Vector3.ZERO) = BoneState( parentBone = null, - boneId = bodyPart.boneId, + bodyPart = bodyPart, headOffset = Vector3.ZERO, offset = Vector3(0f, -0.1f, 0f), rotation = rotation, @@ -126,24 +121,25 @@ class InputDecoderTest { val chestRotation = Quaternion.rotationAroundYAxis(0.4f) val chestHead = Vector3(0f, 0.3f, 0f) - val bonesByPart = mapOf( - BodyPart.HIP to bone(BodyPart.HIP, Quaternion.rotationAroundYAxis(0.1f), Vector3.ZERO), - BodyPart.UPPER_WAIST to bone(BodyPart.UPPER_WAIST, Quaternion.rotationAroundXAxis(0.2f), Vector3(0f, 0.15f, 0f)), - BodyPart.LOWER_CHEST to bone(BodyPart.LOWER_CHEST, chestRotation, chestHead), - BodyPart.UPPER_CHEST to bone(BodyPart.UPPER_CHEST, chestRotation, chestHead), - BodyPart.NECK to bone(BodyPart.NECK, Quaternion.rotationAroundZAxis(0.15f), Vector3(0f, 0.5f, 0f)), - BodyPart.HEAD to bone(BodyPart.HEAD, Quaternion.rotationAroundXAxis(-0.1f), Vector3(0f, 0.65f, 0f)), - BodyPart.LEFT_SHOULDER to bone(BodyPart.LEFT_SHOULDER, Quaternion.rotationAroundZAxis(0.05f), Vector3(0.05f, 0.45f, 0f)), - BodyPart.LEFT_UPPER_ARM to bone(BodyPart.LEFT_UPPER_ARM, Quaternion.rotationAroundZAxis(0.7f), Vector3(0.15f, 0.45f, 0f)), - BodyPart.LEFT_LOWER_ARM to bone(BodyPart.LEFT_LOWER_ARM, Quaternion.rotationAroundXAxis(0.9f), Vector3(0.4f, 0.45f, 0f)), - BodyPart.LEFT_HAND to bone(BodyPart.LEFT_HAND, Quaternion.rotationAroundYAxis(0.2f), Vector3(0.65f, 0.45f, 0f)), - BodyPart.LEFT_UPPER_LEG to bone(BodyPart.LEFT_UPPER_LEG, Quaternion.rotationAroundXAxis(0.5f), Vector3(0.1f, 0f, 0f)), - BodyPart.LEFT_LOWER_LEG to bone(BodyPart.LEFT_LOWER_LEG, Quaternion.rotationAroundXAxis(-0.3f), Vector3(0.1f, -0.4f, 0f)), - BodyPart.LEFT_FOOT to bone(BodyPart.LEFT_FOOT, Quaternion.rotationAroundYAxis(0.25f), Vector3(0.1f, -0.8f, 0f)), + val bones = BodyPartMap( + mapOf( + BodyPart.HIP to bone(BodyPart.HIP, Quaternion.rotationAroundYAxis(0.1f), Vector3.ZERO), + BodyPart.UPPER_WAIST to bone(BodyPart.UPPER_WAIST, Quaternion.rotationAroundXAxis(0.2f), Vector3(0f, 0.15f, 0f)), + BodyPart.LOWER_CHEST to bone(BodyPart.LOWER_CHEST, chestRotation, chestHead), + BodyPart.UPPER_CHEST to bone(BodyPart.UPPER_CHEST, chestRotation, chestHead), + BodyPart.NECK to bone(BodyPart.NECK, Quaternion.rotationAroundZAxis(0.15f), Vector3(0f, 0.5f, 0f)), + BodyPart.HEAD to bone(BodyPart.HEAD, Quaternion.rotationAroundXAxis(-0.1f), Vector3(0f, 0.65f, 0f)), + BodyPart.LEFT_SHOULDER to bone(BodyPart.LEFT_SHOULDER, Quaternion.rotationAroundZAxis(0.05f), Vector3(0.05f, 0.45f, 0f)), + BodyPart.LEFT_UPPER_ARM to bone(BodyPart.LEFT_UPPER_ARM, Quaternion.rotationAroundZAxis(0.7f), Vector3(0.15f, 0.45f, 0f)), + BodyPart.LEFT_LOWER_ARM to bone(BodyPart.LEFT_LOWER_ARM, Quaternion.rotationAroundXAxis(0.9f), Vector3(0.4f, 0.45f, 0f)), + BodyPart.LEFT_HAND to bone(BodyPart.LEFT_HAND, Quaternion.rotationAroundYAxis(0.2f), Vector3(0.65f, 0.45f, 0f)), + BodyPart.LEFT_UPPER_LEG to bone(BodyPart.LEFT_UPPER_LEG, Quaternion.rotationAroundXAxis(0.5f), Vector3(0.1f, 0f, 0f)), + BodyPart.LEFT_LOWER_LEG to bone(BodyPart.LEFT_LOWER_LEG, Quaternion.rotationAroundXAxis(-0.3f), Vector3(0.1f, -0.4f, 0f)), + BodyPart.LEFT_FOOT to bone(BodyPart.LEFT_FOOT, Quaternion.rotationAroundYAxis(0.25f), Vector3(0.1f, -0.8f, 0f)), + ), ) - val bones = registry.computedSkeletonOf(*bonesByPart.toList().toTypedArray()) - val bundle = buildOutgoingBundle(bones, bonesByPart.keys, VMCConfig(), vrm = null, elapsed = 0.seconds) + val bundle = buildOutgoingBundle(bones, bones.keys, VMCConfig(), vrm = null, elapsed = 0.seconds) val frame = decodeVmcBundle(bundle, emptyVmcInputFrame()) val worldTransforms = vmcWorldTransforms( locals = frame.boneLocalRotations, @@ -153,7 +149,7 @@ class InputDecoderTest { scale = 1f, ) - for ((bodyPart, originalBone) in bonesByPart) { + for ((bodyPart, originalBone) in bones) { val recovered = assertNotNull(worldTransforms[bodyPart], "missing $bodyPart") assertApprox(originalBone.rotation, recovered.rotation, "$bodyPart rotation") assertApprox(originalBone.headPosition, recovered.position, "$bodyPart position") diff --git a/server/core/src/test/java/dev/slimevr/vmc/OutputEncoderTest.kt b/server/core/src/test/java/dev/slimevr/vmc/OutputEncoderTest.kt index c648f661d..f78e58dda 100644 --- a/server/core/src/test/java/dev/slimevr/vmc/OutputEncoderTest.kt +++ b/server/core/src/test/java/dev/slimevr/vmc/OutputEncoderTest.kt @@ -1,16 +1,14 @@ package dev.slimevr.vmc -import dev.slimevr.computedSkeletonOf import dev.slimevr.config.VMCConfig import dev.slimevr.osc.OscArg import dev.slimevr.osc.OscBundle import dev.slimevr.osc.OscContent import dev.slimevr.osc.OscMessage -import dev.slimevr.skeleton.BoneMap -import dev.slimevr.skeleton.BoneRegistry +import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.Velocity -import dev.slimevr.skeleton.boneId +import dev.slimevr.skeleton.bodyPartMap import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -21,11 +19,9 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Duration.Companion.seconds -private val registry = BoneRegistry.standard() - private fun bone(bodyPart: BodyPart, rotation: Quaternion = Quaternion.IDENTITY) = BoneState( parentBone = null, - boneId = bodyPart.boneId, + bodyPart = bodyPart, headOffset = Vector3.ZERO, offset = Vector3(0f, -0.1f, 0f), rotation = rotation, @@ -46,7 +42,7 @@ class OutputEncoderTest { @Test fun testAlwaysSendsTimeAndOkAndRoot() { val bundle = buildOutgoingBundle( - bones = BoneMap.of(registry), + bones = bodyPartMap(), routedBones = emptySet(), config = defaultConfig, vrm = null, @@ -61,9 +57,11 @@ class OutputEncoderTest { @Test fun testSkipsBonesThatAreNotRouted() { - val bones = registry.computedSkeletonOf( - BodyPart.HIP to bone(BodyPart.HIP), - BodyPart.LOWER_WAIST to bone(BodyPart.LOWER_WAIST), + val bones = BodyPartMap( + mapOf( + BodyPart.HIP to bone(BodyPart.HIP), + BodyPart.LOWER_WAIST to bone(BodyPart.LOWER_WAIST), + ), ) val bundle = buildOutgoingBundle( @@ -81,7 +79,7 @@ class OutputEncoderTest { @Test fun testSkipsRoutedBonesMissingFromTheSkeleton() { val bundle = buildOutgoingBundle( - bones = registry.computedSkeletonOf(BodyPart.HIP to bone(BodyPart.HIP)), + bones = BodyPartMap(mapOf(BodyPart.HIP to bone(BodyPart.HIP))), routedBones = setOf(BodyPart.HIP, BodyPart.LOWER_WAIST), config = defaultConfig, vrm = null, @@ -95,10 +93,12 @@ class OutputEncoderTest { @Test fun testMirrorTrackingReadsTheOppositeSideBone() { val leftRotation = Quaternion.rotationAroundXAxis(0.5f) - val bones = registry.computedSkeletonOf( - BodyPart.LEFT_UPPER_LEG to bone(BodyPart.LEFT_UPPER_LEG, leftRotation), - BodyPart.RIGHT_UPPER_LEG to bone(BodyPart.RIGHT_UPPER_LEG), - BodyPart.HIP to bone(BodyPart.HIP), + val bones = BodyPartMap( + mapOf( + BodyPart.LEFT_UPPER_LEG to bone(BodyPart.LEFT_UPPER_LEG, leftRotation), + BodyPart.RIGHT_UPPER_LEG to bone(BodyPart.RIGHT_UPPER_LEG), + BodyPart.HIP to bone(BodyPart.HIP), + ), ) val routed = setOf(BodyPart.HIP, BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG) @@ -119,9 +119,11 @@ class OutputEncoderTest { @Test fun testVrmBindOffsetsReplaceComputedPositions() { - val bones = registry.computedSkeletonOf( - BodyPart.HIP to bone(BodyPart.HIP), - BodyPart.LOWER_WAIST to bone(BodyPart.LOWER_WAIST), + val bones = BodyPartMap( + mapOf( + BodyPart.HIP to bone(BodyPart.HIP), + BodyPart.LOWER_WAIST to bone(BodyPart.LOWER_WAIST), + ), ) val routed = setOf(BodyPart.HIP, BodyPart.LOWER_WAIST) val vrm = buildVrmGeometry(VrmReader(VRM_JSON)) diff --git a/server/core/src/test/java/dev/slimevr/vmc/VMCInputBehaviourTest.kt b/server/core/src/test/java/dev/slimevr/vmc/VMCInputBehaviourTest.kt index 6607a3949..e07f82923 100644 --- a/server/core/src/test/java/dev/slimevr/vmc/VMCInputBehaviourTest.kt +++ b/server/core/src/test/java/dev/slimevr/vmc/VMCInputBehaviourTest.kt @@ -14,7 +14,6 @@ import dev.slimevr.osc.OscMessage import dev.slimevr.quaternionApproxEqual import dev.slimevr.skeleton.Skeleton import dev.slimevr.skeleton.bodyPartMap -import dev.slimevr.skeleton.boneId import dev.slimevr.vectorAssertEquals import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 @@ -80,7 +79,7 @@ class VMCInputBehaviourTest { harness.handle(boneBundle("Hips", Vector3(0f, 1f, 0f), Quaternion.rotationAroundYAxis(0.3f))) val tracker = harness.trackers().single() - assertEquals(BodyPart.HIP.boneId, tracker.context.state.value.boneId) + assertEquals(BodyPart.HIP, tracker.context.state.value.bodyPart) assertEquals(DeviceOrigin.VMC, tracker.context.state.value.origin) vectorAssertEquals(Vector3(0f, 1f, 0f), assertNotNull(tracker.context.state.value.position)) assertApprox(Quaternion.rotationAroundYAxis(0.3f), tracker.context.state.value.rawRotation) @@ -106,7 +105,7 @@ class VMCInputBehaviourTest { harness.handle(bundleOf(OscMessage("/VMC/Ext/Tra/Pos", transformArgs("serial-1", Vector3(0.5f, 0.5f, 0.5f), Quaternion.IDENTITY)))) val tracker = harness.trackers().single() - assertNull(tracker.context.state.value.boneId) + assertNull(tracker.context.state.value.bodyPart) assertEquals(DeviceOrigin.VMC, tracker.context.state.value.origin) vectorAssertEquals(Vector3(0.5f, 0.5f, 0.5f), assertNotNull(tracker.context.state.value.position)) } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/solarxr.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/solarxr.kt index 72716d84f..328cb0a65 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/solarxr.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/solarxr.kt @@ -9,20 +9,17 @@ import dev.slimevr.SLIMEVR_IDENTIFIER import dev.slimevr.VRServerActions import dev.slimevr.desktop.startBindingsProvider import dev.slimevr.desktop.unblockSteamVRDriver +import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader import dev.slimevr.fbscodegen.runtime.JvmFlatBufferWriter import dev.slimevr.logging.AppLogger -import dev.slimevr.solarxr.SOLARXR_PROTOCOL_VERSION import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour -import dev.slimevr.solarxr.checkedSolarXRFrame import dev.slimevr.solarxr.onSolarXRMessage import io.ktor.client.HttpClient import io.ktor.client.engine.cio.CIO import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn @@ -31,14 +28,10 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okio.Buffer -import solarxr_protocol.ClientHello -import solarxr_protocol.HelloStatus import solarxr_protocol.MessageBundle -import solarxr_protocol.ServerHello import solarxr_protocol.rpc.EnableSteamVRDriverRequest import solarxr_protocol.rpc.OpenKeybindSettingsRequest import java.nio.ByteBuffer -import kotlin.time.Duration.Companion.seconds class EnableSteamVRDriverBehaviour : SolarXRBridgeBehaviour { override fun observe(receiver: SolarXRBridge) { @@ -110,47 +103,24 @@ suspend fun handleSolarXRBridge( bridge.outbound.on { bundle -> fbb.clear() - bundle.finish(JvmFlatBufferWriter(fbb)) + fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb))) sendBuffer.write(fbb.dataBuffer()) send(sendBuffer) }.launchIn(this) - val initTimeout = launch { - delay(10.seconds) - if (!bridge.isReady) { - AppLogger.solarxr.warn("SolarXR[${bridge.id}] initialization timed out ($transport)") - this@coroutineScope.cancel() - } - } + bridge.startObserving() val receiveArray = ByteArray(MAX_FRAME_SIZE) try { - var awaitingHello = true messages.collect { frame -> val size = frame.size.toInt() // read(array, offset, count) only copies from one internal segment (up to 8k) per call // and returns however much that was, so filling a fixed array takes a loop var done = 0 while (done < size) done += frame.read(receiveArray, done, size - done) - val bytes = ByteBuffer.wrap(receiveArray, 0, size) - if (awaitingHello) { - val reader = checkedSolarXRFrame(bytes, ClientHello.FILE_IDENTIFIER) - val hello = ClientHello.fromByteBuffer(reader) - val accepted = hello.protocolVersion == SOLARXR_PROTOCOL_VERSION - fbb.clear() - ServerHello(if (accepted) HelloStatus.ACCEPTED else HelloStatus.REJECTED_UNSUPPORTED_VERSION, SOLARXR_PROTOCOL_VERSION) - .finish(JvmFlatBufferWriter(fbb)) - sendBuffer.write(fbb.dataBuffer()) - send(sendBuffer) - require(accepted) { "Unsupported SolarXR protocol version ${hello.protocolVersion}" } - awaitingHello = false - bridge.beginConfiguration() - } else { - val reader = checkedSolarXRFrame(bytes, MessageBundle.FILE_IDENTIFIER) - onSolarXRMessage(MessageBundle.fromByteBuffer(reader), bridge) - if (bridge.isReady) initTimeout.cancel() - } + val reader = JvmFlatBufferReader(ByteBuffer.wrap(receiveArray, 0, size)) + onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge) } } finally { AppLogger.solarxr.info("SolarXR[${bridge.id}] disconnected ($transport)") diff --git a/solarxr-protocol b/solarxr-protocol index 185eab5b5..aac004ca9 160000 --- a/solarxr-protocol +++ b/solarxr-protocol @@ -1 +1 @@ -Subproject commit 185eab5b52d846dbb5ae9cd320b276fc792e6d6d +Subproject commit aac004ca944c393d1d3236b86d0d94be53f00015