From edbaf49e7ac8217da78435533c670bd40713041d Mon Sep 17 00:00:00 2001 From: lucas lelievre Date: Wed, 23 Apr 2025 13:48:31 +0200 Subject: [PATCH] manual proportions rework (#1346) Co-authored-by: Erimel --- gui/public/i18n/en/translation.ftl | 107 ++- gui/src/components/BVHButton.tsx | 24 +- .../ClearDriftCompensationButton.tsx | 18 +- gui/src/components/ClearMountingButton.tsx | 16 +- gui/src/components/TrackingPauseButton.tsx | 20 +- gui/src/components/WidgetsComponent.tsx | 6 +- gui/src/components/commons/BigButton.tsx | 8 +- gui/src/components/commons/Tooltip.tsx | 39 +- .../components/commons/icon/ArrowIcons.tsx | 12 +- .../components/commons/icon/ImportIcon.tsx | 12 + .../components/commons/icon/PercentIcon.tsx | 12 + gui/src/components/home/ResetButton.tsx | 24 +- .../body-proportions/BodyProportions.tsx | 613 +++++++----------- .../body-proportions/ManualProportions.tsx | 454 ++++++++----- .../autobone-steps/Preparation.tsx | 2 +- .../mounting/mounting-steps/MountingReset.tsx | 2 +- .../mounting/mounting-steps/Preparation.tsx | 2 +- .../widgets/SkeletonVisualizerWidget.tsx | 76 ++- gui/src/hooks/manual-proportions.ts | 432 ++++-------- .../dev/slimevr/protocol/rpc/RPCBuilder.java | 28 - .../dev/slimevr/protocol/rpc/RPCBuilder.kt | 25 + .../dev/slimevr/protocol/rpc/RPCHandler.kt | 4 +- .../rpc/autobone/RPCAutoBoneHandler.kt | 4 +- solarxr-protocol | 2 +- 24 files changed, 942 insertions(+), 1000 deletions(-) create mode 100644 gui/src/components/commons/icon/ImportIcon.tsx create mode 100644 gui/src/components/commons/icon/PercentIcon.tsx delete mode 100644 server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.java create mode 100644 server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.kt diff --git a/gui/public/i18n/en/translation.ftl b/gui/public/i18n/en/translation.ftl index 1f4e0a862..b79f3e8ba 100644 --- a/gui/public/i18n/en/translation.ftl +++ b/gui/public/i18n/en/translation.ftl @@ -104,29 +104,125 @@ board_type-GLOVE_IMU_SLIMEVR_DEV = SlimeVR Dev IMU Glove ## Proportions skeleton_bone-NONE = None skeleton_bone-HEAD = Head Shift +skeleton_bone-HEAD-desc = + This is the distance from your headset to the middle of your head. + To adjust it, shake your head left to right as if you're disagreeing and modify + it until any movement in other trackers is negligible. skeleton_bone-NECK = Neck Length +skeleton_bone-NECK-desc = + This is the distance from the middle of your head to the base of your neck. + To adjust it, move your head up and down as if you're nodding or tilt your head + to the left and right and modify it until any movement in other trackers is negligible. skeleton_bone-torso_group = Torso length +skeleton_bone-torso_group-desc = + This is the distance from the base of your neck to your hips. + To adjust it, modify it standing up straight until your virtual hips line + up with your real ones. skeleton_bone-UPPER_CHEST = Upper Chest Length +skeleton_bone-UPPER_CHEST-desc = + This is the distance from the base of your neck to the middle of your chest. + To adjust it, adjust your Torso Length properly and modify it in various positions + (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one. skeleton_bone-CHEST_OFFSET = Chest Offset +skeleton_bone-CHEST_OFFSET-desc = + This can be adjusted to move your virtual chest tracker up or down in order to aid + with calibration in certain games or applications that may expect it to be higher or lower. skeleton_bone-CHEST = Chest Length +skeleton_bone-CHEST-desc = + This is the distance from the middle of your chest to the middle of your spine. + To adjust it, adjust your Torso Length properly and modify it in various positions + (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one. skeleton_bone-WAIST = Waist Length +skeleton_bone-WAIST-desc = + This is the distance from the middle of your spine to your belly button. + To adjust it, adjust your Torso Length properly and modify it in various positions + (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one. skeleton_bone-HIP = Hip Length +skeleton_bone-HIP-desc = + This is the distance from your belly button to your hips + To adjust it, adjust your Torso Length properly and modify it in various positions + (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one. skeleton_bone-HIP_OFFSET = Hip Offset +skeleton_bone-HIP_OFFSET-desc = + This can be adjusted to move your virtual hip tracker up or down in order to aid + with calibration in certain games or applications that may expect it to be on your waist. skeleton_bone-HIPS_WIDTH = Hips Width +skeleton_bone-HIPS_WIDTH-desc = + This is the distance between the start of your legs. + To adjust it, perform a full reset with your legs straight and modify it until + your virtual legs match up with your real ones horizontally. skeleton_bone-leg_group = Leg length +skeleton_bone-leg_group-desc = + This is the distance from your hips to your feet. + To adjust it, adjust your Torso Length properly and modify it + until your virtual feet are at the same level as your real ones. skeleton_bone-UPPER_LEG = Upper Leg Length +skeleton_bone-UPPER_LEG-desc = + This is the distance from your hips to your knees. + To adjust it, adjust your Leg Length properly and modify it + until your virtual knees are at the same level as your real ones. skeleton_bone-LOWER_LEG = Lower Leg Length +skeleton_bone-LOWER_LEG-desc = + This is the distance from your hips to your knees. + To adjust it, adjust your Leg Length properly and modify it + until your virtual knees are at the same level as your real ones. skeleton_bone-FOOT_LENGTH = Foot Length +skeleton_bone-FOOT_LENGTH-desc = + This is the distance from your ankles to your toes. + To adjust it, tiptoe and modify it until your virtual feet stay in place. skeleton_bone-FOOT_SHIFT = Foot Shift +skeleton_bone-FOOT_SHIFT-desc = + This value is the horizontal distance from your knee to your ankle. + It accounts for your lower legs going backwards when standing up straight. + To adjust it, set Foot Length to 0, perform a full reset and modify it until your virtual + feet line up with the middle of your ankles. skeleton_bone-SKELETON_OFFSET = Skeleton Offset +skeleton_bone-SKELETON_OFFSET-desc = + This can be adjusted to offsets all your trackers forward or backwards. + It can be used in order to aid with calibration in certain games or applications + that may expect your trackers to be more forward. skeleton_bone-SHOULDERS_DISTANCE = Shoulders Distance +skeleton_bone-SHOULDERS_DISTANCE-desc = + This is the vertical distance from the base of your neck to your shoulders. + To adjust it, set Upper Arm Length to 0 and modify it until your virtual elbow trackers + line up vertically with your real shoulders. skeleton_bone-SHOULDERS_WIDTH = Shoulders Width +skeleton_bone-SHOULDERS_WIDTH-desc = + This is the horizontal distance from the base of your neck to your shoulders. + To adjust it, set Upper Arm Length to 0 and modify it until your virtual elbow trackers + line up horizontally with your real shoulders. skeleton_bone-arm_group = Arm length +skeleton_bone-arm_group-desc = + This is the distance from your shoulders to your wrists. + To adjust it, adjust Shoulders Distance properly, set Hand Distance Y + to 0 and modify it until your hand trackers line up with your wrists. skeleton_bone-UPPER_ARM = Upper Arm Length +skeleton_bone-UPPER_ARM-desc = + This is the distance from your shoulders to your elbows. + To adjust it, adjust Arm Length properly and modify it until + your elbow trackers line up with your real elbows. skeleton_bone-LOWER_ARM = Lower Arm Length +skeleton_bone-LOWER_ARM-desc = + This is the distance from your elbows to your wrists. + To adjust it, adjust Arm Length properly and modify it until + your elbow trackers line up with your real elbows. skeleton_bone-HAND_Y = Hand Distance Y +skeleton_bone-HAND_Y-desc = + This is the vertical distance from your wrists to the middle of your hand. + To adjust it for motion capture, adjust Arm Length properly and modify it until your + hand trackers line up vertically with the middle of your hands. + To adjust it for elbow tracking from your controllers, set Arm Length to 0 and + modify it until your elbow trackers line up vertically with your wrists. skeleton_bone-HAND_Z = Hand Distance Z +skeleton_bone-HAND_Z-desc = + This is the horizontal distance from your wrists to the middle of your hand. + To adjust it for motion capture, set it to 0. + To adjust it for elbow tracking from your controllers, set Arm Length to 0 and + modify it until your elbow trackers line up horizontally with your wrists. skeleton_bone-ELBOW_OFFSET = Elbow Offset +skeleton_bone-ELBOW_OFFSET-desc = + This can be adjusted to move your virtual elbow trackers up or down in order to aid + with VRChat accidentally binding and elbow tracker to the chest. ## Tracker reset buttons reset-reset_all = Reset all proportions @@ -987,17 +1083,16 @@ onboarding-automatic_mounting-put_trackers_on-next = I have all my trackers on ## Tracker manual proportions setupa onboarding-manual_proportions-back = Go Back to Reset tutorial onboarding-manual_proportions-title = Manual Body Proportions -onboarding-manual_proportions-precision = Precision adjust -onboarding-manual_proportions-auto = Automatic proportions -onboarding-manual_proportions-ratio = Adjust by ratio groups onboarding-manual_proportions-fine_tuning_button = Automatically fine tune proportions onboarding-manual_proportions-fine_tuning_button-disabled-tooltip = Please connect a VR headset to use automatic fine tuning onboarding-manual_proportions-export = Export proportions onboarding-manual_proportions-import = Import proportions -onboarding-manual_proportions-import-success = Imported -onboarding-manual_proportions-import-failed = Failed onboarding-manual_proportions-file_type = Body proportions file - +onboarding-manual_proportions-normal_increment = Normal increment +onboarding-manual_proportions-precise_increment = Precise increment +onboarding-manual_proportions-grouped_proportions = Grouped proportions +onboarding-manual_proportions-all_proportions = All proportions +onboarding-manual_proportions-estimated_height = Estimated user height ## Tracker automatic proportions setup onboarding-automatic_proportions-back = Go Back to Manual Proportions diff --git a/gui/src/components/BVHButton.tsx b/gui/src/components/BVHButton.tsx index 97b62afdd..0b4a2b78a 100644 --- a/gui/src/components/BVHButton.tsx +++ b/gui/src/components/BVHButton.tsx @@ -1,4 +1,4 @@ -import { useLocalization } from '@fluent/react'; +import { Localized } from '@fluent/react'; import { useEffect, useState } from 'react'; import { RecordBVHRequestT, @@ -11,7 +11,6 @@ import { RecordIcon } from './commons/icon/RecordIcon'; import classNames from 'classnames'; export function BVHButton(props: React.HTMLAttributes) { - const { l10n } = useLocalization(); const { useRPCPacket, sendRPCPacket } = useWebsocketAPI(); const [recording, setRecording] = useState(false); @@ -30,15 +29,16 @@ export function BVHButton(props: React.HTMLAttributes) { }); return ( - } - onClick={toggleBVH} - className={classNames( - props.className, - 'border', - recording ? 'border-status-critical' : 'border-transparent' - )} - > + + } + onClick={toggleBVH} + className={classNames( + props.className, + 'border', + recording ? 'border-status-critical' : 'border-transparent' + )} + > + ); } diff --git a/gui/src/components/ClearDriftCompensationButton.tsx b/gui/src/components/ClearDriftCompensationButton.tsx index a71fcd4a7..e43d0e835 100644 --- a/gui/src/components/ClearDriftCompensationButton.tsx +++ b/gui/src/components/ClearDriftCompensationButton.tsx @@ -1,4 +1,4 @@ -import { useLocalization } from '@fluent/react'; +import { Localized } from '@fluent/react'; import { ClearDriftCompensationRequestT, RpcMessage } from 'solarxr-protocol'; import { useWebsocketAPI } from '@/hooks/websocket-api'; import { BigButton } from './commons/BigButton'; @@ -9,7 +9,6 @@ export function ClearDriftCompensationButton({ }: { disabled: boolean; }) { - const { l10n } = useLocalization(); const { sendRPCPacket } = useWebsocketAPI(); const clearDriftCompensation = () => { @@ -18,13 +17,12 @@ export function ClearDriftCompensationButton({ }; return ( - } - onClick={clearDriftCompensation} - disabled={disabled} - > - {} - + + } + onClick={clearDriftCompensation} + disabled={disabled} + > + ); } diff --git a/gui/src/components/ClearMountingButton.tsx b/gui/src/components/ClearMountingButton.tsx index 1b1bb766b..995cd719c 100644 --- a/gui/src/components/ClearMountingButton.tsx +++ b/gui/src/components/ClearMountingButton.tsx @@ -1,4 +1,4 @@ -import { useLocalization } from '@fluent/react'; +import { Localized } from '@fluent/react'; import { ClearMountingResetRequestT, RpcMessage } from 'solarxr-protocol'; import { useWebsocketAPI } from '@/hooks/websocket-api'; import { BigButton } from './commons/BigButton'; @@ -11,7 +11,6 @@ import { useMemo } from 'react'; const _q = new Quaternion(); export function ClearMountingButton() { - const { l10n } = useLocalization(); const { sendRPCPacket } = useWebsocketAPI(); const { useAssignedTrackers } = useTrackers(); const assignedTrackers = useAssignedTrackers(); @@ -34,11 +33,12 @@ export function ClearMountingButton() { }; return ( - } - onClick={clearMounting} - disabled={!trackerWithMounting} - /> + + } + onClick={clearMounting} + disabled={!trackerWithMounting} + /> + ); } diff --git a/gui/src/components/TrackingPauseButton.tsx b/gui/src/components/TrackingPauseButton.tsx index db15b2201..aa5578d29 100644 --- a/gui/src/components/TrackingPauseButton.tsx +++ b/gui/src/components/TrackingPauseButton.tsx @@ -1,4 +1,4 @@ -import { useLocalization } from '@fluent/react'; +import { Localized } from '@fluent/react'; import { useEffect, useState } from 'react'; import { SetPauseTrackingRequestT, @@ -15,7 +15,6 @@ import classNames from 'classnames'; export function TrackingPauseButton( props: React.HTMLAttributes ) { - const { l10n } = useLocalization(); const { useRPCPacket, sendRPCPacket } = useWebsocketAPI(); const [trackingPause, setTrackingPause] = useState(false); @@ -39,13 +38,14 @@ export function TrackingPauseButton( }, []); return ( - : } - onClick={toggleTracking} - className={classNames(props.className, 'min-h-24')} - > + + : + } + onClick={toggleTracking} + className={classNames(props.className, 'min-h-24')} + > + ); } diff --git a/gui/src/components/WidgetsComponent.tsx b/gui/src/components/WidgetsComponent.tsx index b5fe3649f..df869f711 100644 --- a/gui/src/components/WidgetsComponent.tsx +++ b/gui/src/components/WidgetsComponent.tsx @@ -46,9 +46,9 @@ export function WidgetsComponent() { return ( <>
- - - + + + diff --git a/gui/src/components/commons/BigButton.tsx b/gui/src/components/commons/BigButton.tsx index fbf78bc4b..5450de20d 100644 --- a/gui/src/components/commons/BigButton.tsx +++ b/gui/src/components/commons/BigButton.tsx @@ -2,15 +2,15 @@ import classNames from 'classnames'; import React, { ReactNode } from 'react'; export function BigButton({ - text, icon, disabled, + children, onClick, ...props }: { - text: string; disabled?: boolean; icon: ReactNode; + children?: ReactNode; } & React.HTMLAttributes) { return ( ); } diff --git a/gui/src/components/commons/Tooltip.tsx b/gui/src/components/commons/Tooltip.tsx index 8444a71d8..0359cff1a 100644 --- a/gui/src/components/commons/Tooltip.tsx +++ b/gui/src/components/commons/Tooltip.tsx @@ -356,6 +356,10 @@ export function DrawerTooltip({ } }; + const scroll = () => { + close(); + }; + const open = () => { if (drawerStyle) return; clearEffect(); @@ -375,6 +379,8 @@ export function DrawerTooltip({ elem.addEventListener('mousedown', touchStart); // for debug on desktop elem.addEventListener('mouseup', touchEnd); // for debug on desktop + elem.addEventListener('scroll', scroll); + elem.addEventListener('click', touchEnd); elem.addEventListener('touchstart', touchStart); elem.addEventListener('touchend', touchEnd); @@ -382,6 +388,8 @@ export function DrawerTooltip({ return () => { elem.removeEventListener('mousedown', touchStart); // for debug on desktop elem.removeEventListener('mouseup', touchEnd); // for debug on desktop + elem.removeEventListener('scroll', scroll); + elem.removeEventListener('touchstart', touchStart); elem.removeEventListener('touchend', touchEnd); clearTimeout(touchTimeout.current); @@ -442,26 +450,27 @@ export function Tooltip({ const childRef = useRef(null); const { isMobile } = useBreakpoint('mobile'); + const portal = createPortal( + isMobile ? ( + {content} + ) : ( + + {content} + + ), + document.body + ); + return ( <>
{children}
- {!disabled && - createPortal( - isMobile ? ( - {content} - ) : ( - - {content} - - ), - document.body - )} + {!disabled && portal} ); } diff --git a/gui/src/components/commons/icon/ArrowIcons.tsx b/gui/src/components/commons/icon/ArrowIcons.tsx index 7084edd1c..5bad08de1 100644 --- a/gui/src/components/commons/icon/ArrowIcons.tsx +++ b/gui/src/components/commons/icon/ArrowIcons.tsx @@ -29,11 +29,11 @@ export function ArrowUpIcon({ size = 24 }: { size?: number }) { ); } -export function ArrowLeftIcon() { +export function ArrowLeftIcon({ size = 12 }: { size?: number }) { return ( @@ -46,11 +46,11 @@ export function ArrowLeftIcon() { ); } -export function ArrowRightIcon() { +export function ArrowRightIcon({ size = 12 }: { size?: number }) { return ( diff --git a/gui/src/components/commons/icon/ImportIcon.tsx b/gui/src/components/commons/icon/ImportIcon.tsx new file mode 100644 index 000000000..9389de6c4 --- /dev/null +++ b/gui/src/components/commons/icon/ImportIcon.tsx @@ -0,0 +1,12 @@ +export function ImportIcon({ size = 24 }: { size?: number }) { + return ( + + + + ); +} diff --git a/gui/src/components/commons/icon/PercentIcon.tsx b/gui/src/components/commons/icon/PercentIcon.tsx new file mode 100644 index 000000000..2370f3d5a --- /dev/null +++ b/gui/src/components/commons/icon/PercentIcon.tsx @@ -0,0 +1,12 @@ +export function PercentIcon({ size = 24 }: { size?: number }) { + return ( + + + + ); +} diff --git a/gui/src/components/home/ResetButton.tsx b/gui/src/components/home/ResetButton.tsx index e0a9602a9..0bd4874f0 100644 --- a/gui/src/components/home/ResetButton.tsx +++ b/gui/src/components/home/ResetButton.tsx @@ -25,11 +25,13 @@ import classNames from 'classnames'; export function ResetButton({ type, - variant = 'big', + size = 'big', + className, onReseted, }: { + className?: string; type: ResetType; - variant: 'big' | 'small'; + size: 'big' | 'small'; onReseted?: () => void; }) { const { l10n } = useLocalization(); @@ -115,7 +117,7 @@ export function ResetButton({ }; }, []); - return variant === 'small' ? ( + return size === 'small' ? (
-
{text}
- {!isCounting || type === ResetType.Yaw ? text : String(timer)} -
+ {!isCounting || type === ResetType.Yaw ? text : String(timer)} ) : ( + > + {!isCounting || type === ResetType.Yaw ? text : String(timer)} + ); } diff --git a/gui/src/components/onboarding/pages/body-proportions/BodyProportions.tsx b/gui/src/components/onboarding/pages/body-proportions/BodyProportions.tsx index cce31e00c..7fc25d64c 100644 --- a/gui/src/components/onboarding/pages/body-proportions/BodyProportions.tsx +++ b/gui/src/components/onboarding/pages/body-proportions/BodyProportions.tsx @@ -1,16 +1,9 @@ -import { useLocalization } from '@fluent/react'; +import { Localized, useLocalization } from '@fluent/react'; import classNames from 'classnames'; +import { MouseEventHandler, ReactNode, useMemo, useState } from 'react'; import { - MouseEventHandler, - ReactNode, - useEffect, - useRef, - UIEvent, - useMemo, -} from 'react'; -import { - LabelType, - ProportionChangeType, + Label, + UpdateBoneParams, useManualProportions, } from '@/hooks/manual-proportions'; import { useLocaleConfig } from '@/i18n/config'; @@ -19,8 +12,7 @@ import { ArrowDownIcon, ArrowUpIcon, } from '@/components/commons/icon/ArrowIcons'; -import { useBreakpoint } from '@/hooks/breakpoint'; -import { debounce } from '@/hooks/timeout'; +import { Tooltip } from '@/components/commons/Tooltip'; function IncrementButton({ children, @@ -33,17 +25,226 @@ function IncrementButton({
- + {children}
); } +function ProportionItem({ + type, + part, + precise, + onBoneChange, +}: { + type: 'linear' | 'ratio'; + part: Label; + precise: boolean; + onBoneChange: (params: UpdateBoneParams) => void; +}) { + const { l10n } = useLocalization(); + const { currentLocales } = useLocaleConfig(); + + const { cmFormat, percentageFormat, configFormat } = useMemo(() => { + const cmFormat = Intl.NumberFormat(currentLocales, { + style: 'unit', + unit: 'centimeter', + maximumFractionDigits: 1, + }); + const percentageFormat = new Intl.NumberFormat(currentLocales, { + style: 'percent', + maximumFractionDigits: 1, + }); + const configFormat = Intl.NumberFormat(currentLocales, { + signDisplay: 'always', + maximumFractionDigits: 1, + }); + return { + cmFormat, + percentageFormat, + configFormat, + }; + }, [currentLocales]); + + const [open, setOpen] = useState(false); + + const toggleOpen = () => { + if (part.type === 'bone') return; + setOpen((open) => !open); + }; + + const boneIncrement = (addition: number) => { + const newValue = + part.unit === 'cm' + ? (Math.round(part.value * 200) + addition * 2) / 200 + : // In the case of unit === percent we send only the added percent and not the value with added percent to it + // this is so the percent added is relative to the whole group and not the bone as 1% added to the bone is not 1% of the group + addition / 100; + + if (part.type === 'bone') { + onBoneChange({ + type: 'bone', + newValue, + bone: part.bone, + }); + } + if (part.type === 'group-part') { + onBoneChange({ + type: 'group-part', + newValue, + bone: part.bone, + group: part.group, + }); + } + if (part.type === 'group') { + onBoneChange({ + type: 'group', + newValue, + group: part.label, + }); + } + }; + + return ( +
+
+
+ + + + } + preferedDirection="bottom" + mode="corner" + > +
+ + {l10n.getString(part.label)} + +
+
+
+
+ {!precise && ( + boneIncrement(-5)}> + {configFormat.format(-5)} + + )} + boneIncrement(-1)}> + {configFormat.format(-1)} + + {precise && ( + boneIncrement(-0.5)}> + {configFormat.format(-0.5)} + + )} +
+
+ {part.unit === 'percent' + ? /* Make number rounding so it's based on .5 decimals */ + percentageFormat.format(Math.round(part.ratio * 200) / 200) + : cmFormat.format(part.value * 100)} + {part.unit === 'percent' && ( +

{`(${cmFormat.format( + part.value * 100 + )})`}

+ )} +
+
+ {precise && ( + boneIncrement(+0.5)}> + {configFormat.format(+0.5)} + + )} + boneIncrement(+1)}> + {configFormat.format(+1)} + + {!precise && ( + boneIncrement(+5)}> + {configFormat.format(+5)} + + )} +
+
+
+ {type === 'ratio' && part.type !== 'group-part' && ( +
+ {open ? ( + + ) : ( + + )} +
+ )} +
+ {part.type === 'group' && ( +
+
+ {part.bones.map((part) => ( + + ))} +
+
+ )} +
+ ); +} + export function BodyProportions({ precise, type, @@ -53,377 +254,23 @@ export function BodyProportions({ type: 'linear' | 'ratio'; variant: 'onboarding' | 'alone'; }) { - const { bodyParts, dispatch, state, setRatioMode } = useManualProportions(); - const { l10n } = useLocalization(); - const { currentLocales } = useLocaleConfig(); - const { isTall } = useBreakpoint('tall'); - - const offsetItems = isTall ? 2 : 1; - const itemsToDisplay = offsetItems * 2 + 1; - const itemHeight = 80; - const scrollHeight = itemHeight * itemsToDisplay; - - const scrollerRef = useRef(null); - - const cmFormat = Intl.NumberFormat(currentLocales, { - style: 'unit', - unit: 'centimeter', - maximumFractionDigits: 1, + const { bodyPartsGrouped, changeBoneValue } = useManualProportions({ + type, }); - const percentageFormat = new Intl.NumberFormat(currentLocales, { - style: 'percent', - maximumFractionDigits: 1, - }); - const configFormat = Intl.NumberFormat(currentLocales, { - signDisplay: 'always', - maximumFractionDigits: 1, - }); - - useEffect(() => { - if (type === 'linear') { - setRatioMode(false); - } else { - setRatioMode(true); - } - }, [type]); - - useEffect(() => { - if (scrollerRef.current && bodyParts.length > 0) { - selectId(bodyParts[offsetItems].label); - } - }, [scrollerRef, bodyParts.length]); - - const handleUIEvent = (e: UIEvent) => { - const target = e.target as HTMLDivElement; - const itemHeight = target.offsetHeight / itemsToDisplay; - const atSnappingPoint = target.scrollTop % itemHeight === 0; - const index = Math.round(target.scrollTop / itemHeight); - const elem = scrollerRef.current?.childNodes[ - index + offsetItems - ] as HTMLDivElement; - - elem.scrollIntoView({ behavior: 'smooth', block: 'center' }); - - if (atSnappingPoint) { - const elem = scrollerRef.current?.childNodes[ - index + offsetItems - ] as HTMLDivElement; - const id = elem.getAttribute('itemid'); - - if (id) selectNew(id); - } - }; - - const moveToId = (id: string) => { - if (!scrollerRef.current) return; - const index = bodyParts.findIndex(({ label }) => label === id); - scrollerRef.current.scrollTo({ - top: index * itemHeight, - behavior: 'smooth', - }); - }; - - const clickPart = (id: string) => () => { - moveToId(id); - selectNew(id); - }; - - const selectId = (id: string) => { - moveToId(id); - if (id) selectNew(id); - }; - - const selectNew = (id: string) => { - const part = bodyParts.find(({ label }) => label === id); - if (!part) return; - - const { value: originalValue, label, type, ...props } = part; - - const value = - 'index' in props && props.index !== undefined - ? props.bones[props.index].value - : originalValue; - - switch (type) { - case LabelType.Bone: { - if (!('bone' in props)) throw 'unreachable'; - dispatch({ - ...props, - label, - value, - type: ProportionChangeType.Bone, - }); - break; - } - case LabelType.Group: { - if (!('bones' in props)) throw 'unreachable'; - dispatch({ - ...props, - label, - value, - type: ProportionChangeType.Group, - index: undefined, - parentLabel: label, - }); - break; - } - case LabelType.GroupPart: { - if (!('index' in props)) throw 'unreachable'; - dispatch({ - ...props, - label, - // If this isn't done, we are replacing total - // with percentage value - value: originalValue, - type: ProportionChangeType.Group, - index: props.index, - }); - } - } - }; - - const seletedLabel = useMemo(() => { - return bodyParts.find(({ label }) => label === state.currentLabel); - }, [state]); - - const move = (action: 'next' | 'prev') => { - const elem = scrollerRef.current?.querySelector( - `div[itemid=${state.currentLabel}]` - ); - - const moveId = (id: string) => { - moveToId(id); - selectNew(id); - }; - - if (action === 'prev') { - const prevElem = elem?.previousSibling as HTMLDivElement; - const prevId = prevElem.getAttribute('itemid'); - if (!prevId) return; - moveId(prevId); - } - - if (action === 'next') { - const nextElem = elem?.nextSibling as HTMLDivElement; - const nextId = nextElem.getAttribute('itemid'); - if (!nextId) return; - moveId(nextId); - } - }; return ( - (bodyParts.length > 0 && ( + (bodyPartsGrouped.length > 0 && (
-
- {!precise && ( -
- - seletedLabel?.type === LabelType.GroupPart - ? dispatch({ - type: ProportionChangeType.Ratio, - value: -0.05, - }) - : dispatch({ - type: ProportionChangeType.Linear, - value: -5, - }) - } - > - {configFormat.format(-5)} - -
- )} -
- - seletedLabel?.type === LabelType.GroupPart - ? dispatch({ - type: ProportionChangeType.Ratio, - value: -0.01, - }) - : dispatch({ - type: ProportionChangeType.Linear, - value: -1, - }) - } - > - {configFormat.format(-1)} - -
- {precise && ( -
- - seletedLabel?.type === LabelType.GroupPart - ? dispatch({ - type: ProportionChangeType.Ratio, - value: -0.005, - }) - : dispatch({ - type: ProportionChangeType.Linear, - value: -0.5, - }) - } - > - {configFormat.format(-0.5)} - -
- )} -
-
-
-
move('prev')} - className={classNames( - 'h-12 w-32 rounded-lg bg-background-60 flex flex-col justify-center', - 'items-center fill-background-10', - (scrollerRef?.current?.scrollTop ?? 0 > 0) - ? 'opacity-100 active:bg-accent-background-30' - : 'opacity-50' - )} - > - -
-
-
- {Array.from({ length: offsetItems }).map((_, index) => ( -
- ))} - {bodyParts.map((part) => { - const { label, value: originalValue, type, ...props } = part; - const value = - 'index' in props && props.index !== undefined - ? props.bones[props.index].value - : originalValue; - - const selected = state.currentLabel === label; - - return ( -
-
- - {l10n.getString(label)} - - - {type === LabelType.GroupPart - ? /* Make number rounding so it's based on .5 decimals */ - percentageFormat.format(Math.round(value * 200) / 200) - : cmFormat.format(value * 100)} - {type === LabelType.GroupPart && ( -

{`(${cmFormat.format( - value * originalValue * 100 - )})`}

- )} -
-
-
- ); - })} - {Array.from({ length: offsetItems }).map((_, index) => ( -
- ))} -
-
-
move('next')} - className={classNames( - 'h-12 w-32 rounded-lg bg-background-60 flex flex-col justify-center', - 'items-center fill-background-10', - scrollerRef?.current?.scrollTop !== - (scrollerRef?.current?.scrollHeight ?? 0) - - (scrollerRef?.current?.offsetHeight ?? 0) - ? 'opacity-100 active:bg-accent-background-30' - : 'opacity-50' - )} - > - -
-
-
- -
- {precise && ( -
- - seletedLabel?.type === LabelType.GroupPart - ? dispatch({ - type: ProportionChangeType.Ratio, - value: 0.005, - }) - : dispatch({ - type: ProportionChangeType.Linear, - value: 0.5, - }) - } - > - {configFormat.format(+0.5)} - -
- )} - -
- - seletedLabel?.type === LabelType.GroupPart - ? dispatch({ - type: ProportionChangeType.Ratio, - value: 0.01, - }) - : dispatch({ - type: ProportionChangeType.Linear, - value: 1, - }) - } - > - {configFormat.format(+1)} - -
- {!precise && ( -
- - seletedLabel?.type === LabelType.GroupPart - ? dispatch({ - type: ProportionChangeType.Ratio, - value: 0.05, - }) - : dispatch({ - type: ProportionChangeType.Linear, - value: 5, - }) - } - > - {configFormat.format(+5)} - -
- )} +
+ {bodyPartsGrouped.map((part) => ( + + ))}
)) || <> diff --git a/gui/src/components/onboarding/pages/body-proportions/ManualProportions.tsx b/gui/src/components/onboarding/pages/body-proportions/ManualProportions.tsx index 2ff3d0876..5e32a4efb 100644 --- a/gui/src/components/onboarding/pages/body-proportions/ManualProportions.tsx +++ b/gui/src/components/onboarding/pages/body-proportions/ManualProportions.tsx @@ -1,19 +1,18 @@ -import { useForm } from 'react-hook-form'; +import { Control, Controller, useForm } from 'react-hook-form'; import { ChangeSkeletonConfigRequestT, + ResetType, RpcMessage, SkeletonBone, SkeletonConfigRequestT, + SkeletonConfigResponseT, SkeletonResetAllRequestT, } from 'solarxr-protocol'; import { useOnboarding } from '@/hooks/onboarding'; import { useWebsocketAPI } from '@/hooks/websocket-api'; -import { Button } from '@/components/commons/Button'; -import { CheckBox } from '@/components/commons/Checkbox'; -import { Typography } from '@/components/commons/Typography'; import { BodyProportions } from './BodyProportions'; import { Localized, useLocalization } from '@fluent/react'; -import { useEffect, useMemo, useRef, useState } from 'react'; +import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'; import { useBreakpoint, useIsTauri } from '@/hooks/breakpoint'; import { SkeletonVisualizerWidget } from '@/components/widgets/SkeletonVisualizerWidget'; import { ProportionsResetModal } from './ProportionsResetModal'; @@ -24,7 +23,64 @@ import { writeTextFile } from '@tauri-apps/plugin-fs'; import { error } from '@/utils/logging'; import classNames from 'classnames'; import { useAppContext } from '@/hooks/app'; +import { RulerIcon } from '@/components/commons/icon/RulerIcon'; import { Tooltip } from '@/components/commons/Tooltip'; +import { PercentIcon } from '@/components/commons/icon/PercentIcon'; +import { UploadFileIcon } from '@/components/commons/icon/UploadFileIcon'; +import { FullResetIcon } from '@/components/commons/icon/ResetIcon'; +import { ImportIcon } from '@/components/commons/icon/ImportIcon'; +import { HumanIcon } from '@/components/commons/icon/HumanIcon'; +import { Typography } from '@/components/commons/Typography'; +import { useLocaleConfig } from '@/i18n/config'; +import { useNavigate } from 'react-router-dom'; +import { ResetButton } from '@/components/home/ResetButton'; + +function IconButton({ + onClick, + children, + className, + disabled, + tooltip, + showTooltip = false, + icon, +}: { + onClick: () => void; + className?: string; + disabled?: boolean; + children: ReactNode; + tooltip?: ReactNode; + showTooltip?: boolean; + icon: ReactNode; +}) { + const { isMobile } = useBreakpoint('mobile'); + + if (isMobile) showTooltip = true; + + return ( + + + + ); +} function parseConfigImport( config: SkeletonConfigExport @@ -65,17 +121,6 @@ function ImportExportButtons() { const [importState, setImportState] = useState(ImportStatus.OK); const exporting = useRef(false); - const importStatusKey = useMemo(() => { - switch (importState) { - case ImportStatus.FAILED: - return 'onboarding-manual_proportions-import-failed'; - case ImportStatus.SUCCESS: - return 'onboarding-manual_proportions-import-success'; - case ImportStatus.OK: - return 'onboarding-manual_proportions-import'; - } - }, [importState]); - useRPCPacket( RpcMessage.SkeletonConfigResponse, (data: SkeletonConfigExport) => { @@ -160,41 +205,122 @@ function ImportExportButtons() { sendRPCPacket(RpcMessage.ChangeSkeletonConfigRequest, req) ); setImportState(ImportStatus.SUCCESS); + setTimeout(() => { + setImportState(ImportStatus.OK); + }, 2000); }; return ( <> - - + sendRPCPacket( + RpcMessage.SkeletonConfigRequest, + new SkeletonConfigRequestT() + ); + }} + > + + + + +
); } -function ButtonsControl() { - const { l10n } = useLocalization(); +type ManualProportionControls = Control<{ + precise: boolean; + ratio: boolean; +}>; + +function LinearRatioToggle({ control }: { control: ManualProportionControls }) { + return ( + ( + <> + {value ? ( + } + onClick={() => onChange(!value)} + > + + + + + ) : ( + } + onClick={() => onChange(!value)} + > + + + + + )} + + )} + > + ); +} + +function PreciseToggle({ control }: { control: ManualProportionControls }) { + return ( + ( + <> + {!value ? ( + +1
} + onClick={() => onChange(!value)} + > + + + + + ) : ( + +0.5} + onClick={() => onChange(!value)} + > + + + + + )} + + )} + > + ); +} + +function ButtonsControl({ control }: { control: ManualProportionControls }) { const { state } = useOnboarding(); + const nav = useNavigate(); + const { computedTrackers } = useAppContext(); const { sendRPCPacket } = useWebsocketAPI(); const [showWarning, setShowWarning] = useState(false); @@ -205,56 +331,6 @@ function ButtonsControl() { ); }; - return ( -
-
- -
-
- - - { - resetAll(); - setShowWarning(false); - }} - onClose={() => setShowWarning(false)} - isOpen={showWarning} - > -
-
- ); -} - -export function ManualProportionsPage() { - const { isMobile } = useBreakpoint('mobile'); - const { l10n } = useLocalization(); - const { applyProgress, state } = useOnboarding(); - const { computedTrackers } = useAppContext(); - - applyProgress(0.9); - - const savedValue = useMemo(() => localStorage.getItem('ratioMode'), []); - - const defaultValues = { precise: false, ratio: savedValue !== 'false' }; - - const { control, watch } = useForm<{ precise: boolean; ratio: boolean }>({ - defaultValues, - }); - const { precise, ratio } = watch(); - - useEffect(() => { - localStorage.setItem('ratioMode', ratio?.toString() ?? 'true'); - }, [ratio]); - const beneathFloor = useMemo(() => { const hmd = computedTrackers.find( (tracker) => @@ -267,73 +343,141 @@ export function ManualProportionsPage() { const canUseFineTuning = !beneathFloor || import.meta.env.DEV; return ( - <> -
-
-
-
-
- - {l10n.getString('onboarding-manual_proportions-title')} - - - - {isMobile && ( -
- -
- )} -
- - - - } - preferedDirection="top" - disabled={canUseFineTuning} - > - - +
+
+ +
+
+ +
+
+ } + onClick={() => setShowWarning(true)} + > + + + + +
+
+ + + + } + disabled={!canUseFineTuning} + icon={} + onClick={() => + nav('/onboarding/body-proportions/auto', { + state: { alonePage: state.alonePage }, + }) + } + > + + + + +
+
+ + { + resetAll(); + setShowWarning(false); + }} + onClose={() => setShowWarning(false)} + isOpen={showWarning} + > +
+ ); +} -
- -
-
-
- -
+export function ManualProportionsPage() { + const { applyProgress, state } = useOnboarding(); + const { useRPCPacket } = useWebsocketAPI(); + const { currentLocales } = useLocaleConfig(); + + const [userHeight, setUserHeight] = useState(0); + + applyProgress(0.9); + + const savedValue = useMemo(() => localStorage.getItem('ratioMode'), []); + + const defaultValues = { precise: false, ratio: savedValue !== 'false' }; + + const { control, watch } = useForm<{ precise: boolean; ratio: boolean }>({ + defaultValues, + }); + const { precise, ratio } = watch(); + + const { cmFormat } = useMemo(() => { + const cmFormat = Intl.NumberFormat(currentLocales, { + style: 'unit', + unit: 'centimeter', + maximumFractionDigits: 1, + }); + return { cmFormat }; + }, [currentLocales]); + + useEffect(() => { + localStorage.setItem('ratioMode', ratio?.toString() ?? 'true'); + }, [ratio]); + + useRPCPacket( + RpcMessage.SkeletonConfigResponse, + (data: SkeletonConfigResponseT) => { + if (data.userHeight) setUserHeight(data.userHeight); + } + ); + + return ( + <> +
+
+ +
+
- {!isMobile && ( -
- +
+
+ + +
+
+
- )} + + + + } + > +
+ + {cmFormat.format((userHeight * 100) / 0.936)} + +
+
+
diff --git a/gui/src/components/onboarding/pages/body-proportions/autobone-steps/Preparation.tsx b/gui/src/components/onboarding/pages/body-proportions/autobone-steps/Preparation.tsx index 61b0be5ec..6e921fa25 100644 --- a/gui/src/components/onboarding/pages/body-proportions/autobone-steps/Preparation.tsx +++ b/gui/src/components/onboarding/pages/body-proportions/autobone-steps/Preparation.tsx @@ -54,7 +54,7 @@ export function PreparationStep({ {l10n.getString('onboarding-automatic_mounting-prev_step')} diff --git a/gui/src/components/onboarding/pages/mounting/mounting-steps/MountingReset.tsx b/gui/src/components/onboarding/pages/mounting/mounting-steps/MountingReset.tsx index daa34f76d..bdd088188 100644 --- a/gui/src/components/onboarding/pages/mounting/mounting-steps/MountingReset.tsx +++ b/gui/src/components/onboarding/pages/mounting/mounting-steps/MountingReset.tsx @@ -58,7 +58,7 @@ export function MountingResetStep({ {l10n.getString('onboarding-automatic_mounting-prev_step')} diff --git a/gui/src/components/onboarding/pages/mounting/mounting-steps/Preparation.tsx b/gui/src/components/onboarding/pages/mounting/mounting-steps/Preparation.tsx index 81f9300a8..4873091e2 100644 --- a/gui/src/components/onboarding/pages/mounting/mounting-steps/Preparation.tsx +++ b/gui/src/components/onboarding/pages/mounting/mounting-steps/Preparation.tsx @@ -54,7 +54,7 @@ export function PreparationStep({ {l10n.getString('onboarding-automatic_mounting-prev_step')} diff --git a/gui/src/components/widgets/SkeletonVisualizerWidget.tsx b/gui/src/components/widgets/SkeletonVisualizerWidget.tsx index 19725cab0..688df134d 100644 --- a/gui/src/components/widgets/SkeletonVisualizerWidget.tsx +++ b/gui/src/components/widgets/SkeletonVisualizerWidget.tsx @@ -84,9 +84,10 @@ interface SkeletonVisualizerWidgetProps { maxHeight?: number | string; } -export function ToggleableSkeletonVisualizerWidget( - props: SkeletonVisualizerWidgetProps -) { +export function ToggleableSkeletonVisualizerWidget({ + height, + maxHeight, +}: SkeletonVisualizerWidgetProps) { const { l10n } = useLocalization(); const [enabled, setEnabled] = useState(false); @@ -121,17 +122,19 @@ export function ToggleableSkeletonVisualizerWidget( > {l10n.getString('widget-skeleton_visualizer-hide')} - +
+ +
)} ); } -export function SkeletonVisualizerWidget({ - height = '35vh', - maxHeight = 400, -}: SkeletonVisualizerWidgetProps) { +export function SkeletonVisualizerWidget() { const { bones: _bones } = useAppContext(); const { l10n } = useLocalization(); @@ -196,36 +199,31 @@ export function SkeletonVisualizerWidget({ if (!skeleton.current) return <>; return ( -
- - {l10n.getString('tips-failed_webgl')} - - } - > - - - - - - - - - - -
+ + {l10n.getString('tips-failed_webgl')} + + } + > + + + + + + + + + + ); } diff --git a/gui/src/hooks/manual-proportions.ts b/gui/src/hooks/manual-proportions.ts index 90af246db..e4d07fc9c 100644 --- a/gui/src/hooks/manual-proportions.ts +++ b/gui/src/hooks/manual-proportions.ts @@ -6,181 +6,31 @@ import { ChangeSkeletonConfigRequestT, } from 'solarxr-protocol'; import { useWebsocketAPI } from './websocket-api'; -import { useReducer, useEffect, useMemo, useState, useLayoutEffect } from 'react'; +import { useEffect, useMemo, useState } from 'react'; -export type ProportionChange = LinearChange | RatioChange | BoneChange | GroupChange; - -export enum ProportionChangeType { - Linear, - Ratio, - Bone, - Group, -} - -export interface LinearChange { - type: ProportionChangeType.Linear; - value: number; -} - -export interface RatioChange { - type: ProportionChangeType.Ratio; - /** - * This is a number between -1 and 1 [-1; 1] - */ - value: number; -} - -export interface BoneChange { - type: ProportionChangeType.Bone; - bone: SkeletonBone; +type LabelBase = { value: number; label: string; -} +} & ({ unit: 'cm' } | { unit: 'percent'; ratio: number }); -export interface GroupChange { - type: ProportionChangeType.Group; - bones: { - bone: SkeletonBone; - /** - * This is a number between 0 and 1 [0; 1] - */ - value: number; - label: string; - }[]; - value: number; - label: string; - index?: number; - parentLabel: string; -} - -export type ProportionState = BoneState | GroupState; - -export enum BoneType { - Single, - Group, -} - -export interface BoneState { - type: BoneType.Single; +export type BoneLabel = LabelBase & { + type: 'bone'; bone: SkeletonBone; - value: number; - currentLabel: string; -} +}; -export interface GroupState { - type: BoneType.Group; - bones: { - bone: SkeletonBone; - /** - * This is a number between 0 and 1 [0; 1] - */ - value: number; - }[]; - value: number; - currentLabel: string; - index?: number; - parentLabel: string; -} +export type GroupLabel = LabelBase & { + type: 'group'; + bones: GroupPartLabel[]; +}; -function reducer(state: ProportionState, action: ProportionChange): ProportionState { - switch (action.type) { - case ProportionChangeType.Bone: { - return { - ...action, - currentLabel: action.label, - type: BoneType.Single, - }; - } - - case ProportionChangeType.Group: { - return { - ...action, - currentLabel: action.label, - type: BoneType.Group, - }; - } - - case ProportionChangeType.Linear: { - if (action.value > 0) { - return { - ...state, - value: roundedStep(state.value, action.value, true), - }; - } - - return { - ...state, - value: state.value + action.value / 100, - }; - } - - case ProportionChangeType.Ratio: { - if (state.type === BoneType.Single || state.index === undefined) { - throw new Error(`Unexpected increase of bone ${state.currentLabel}`); - } - - const newState: GroupState = JSON.parse(JSON.stringify(state)); - if (newState.index === undefined) throw 'unreachable'; - newState.bones[newState.index].value += action.value; - if (newState.bones[newState.index].value <= 0) return state; - const filtered = newState.bones.filter((_it, index) => newState.index !== index); - const total = filtered.reduce((acc, cur) => acc + cur.value, 0); - - for (const part of filtered) { - part.value += (part.value / total) * action.value * -1; - if (part.value <= 0) return state; - } - - return newState; - } - } -} +export type GroupPartLabel = LabelBase & { + type: 'group-part'; + bone: SkeletonBone; + group: string; +}; export type Label = BoneLabel | GroupLabel | GroupPartLabel; -export enum LabelType { - Bone, - Group, - GroupPart, -} - -export interface BoneLabel { - type: LabelType.Bone; - bone: SkeletonBone; - value: number; - label: string; -} - -export interface GroupLabel { - type: LabelType.Group; - bones: { - bone: SkeletonBone; - /** - * This is a number between 0 and 1 [0; 1] - */ - value: number; - label: string; - }[]; - value: number; - label: string; -} - -export interface GroupPartLabel { - type: LabelType.GroupPart; - bones: { - bone: SkeletonBone; - /** - * This is a number between 0 and 1 [0; 1] - */ - value: number; - label: string; - }[]; - value: number; - label: string; - parentLabel: string; - index: number; -} - const BONE_MAPPING: Map = new Map([ [ 'skeleton_bone-torso_group', @@ -195,100 +45,76 @@ const BONE_MAPPING: Map = new Map([ ['skeleton_bone-arm_group', [SkeletonBone.UPPER_ARM, SkeletonBone.LOWER_ARM]], ]); -export const INVALID_BONE: BoneState = { - type: BoneType.Single, - bone: SkeletonBone.NONE, - value: 0, - currentLabel: 'invalid-bone', -}; +export type UpdateBoneParams = { newValue: number } & ( + | { type: 'bone'; bone: SkeletonBone } + | { type: 'group'; group: string } + | { type: 'group-part'; group: string; bone: SkeletonBone } +); -export function useManualProportions(): { - bodyParts: Label[]; - ratioMode: boolean; - state: ProportionState; - dispatch: (change: ProportionChange) => void; - setRatioMode: (ratio: boolean) => void; +export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): { + bodyPartsGrouped: Label[]; + changeBoneValue: (params: UpdateBoneParams) => void; } { const { useRPCPacket, sendRPCPacket } = useWebsocketAPI(); const [config, setConfig] = useState | null>( null ); - const [ratio, setRatio] = useState(false); - const [state, dispatch] = useReducer(reducer, INVALID_BONE); - - const bodyParts: Label[] = useMemo(() => { + const bodyPartsGrouped: Label[] = useMemo(() => { if (!config) return []; - if (ratio) { - const groups: GroupPartLabel[] = []; - for (const [label, related] of BONE_MAPPING) { - const children = config.skeletonParts.filter((it) => related.includes(it.bone)); - const total = children.reduce((acc, cur) => cur.value + acc, 0); - - const group: GroupPartLabel = { - parentLabel: label, - label, - type: LabelType.GroupPart, - value: total, - bones: children.map((it) => ({ - label: 'skeleton_bone-' + SkeletonBone[it.bone], - value: it.value / total, - bone: it.bone, - })), - index: 0, - }; - groups.push( - ...children.map((_it, index) => ({ - ...group, - index, - label: group.bones[index].label, - })) - ); - } - - return config.skeletonParts.flatMap(({ bone, value }) => { - const part = groups.find((it) => it.bones[it.index].bone === bone); - if (part === undefined) { - return { - type: LabelType.Bone, + if (type === 'linear') { + return config.skeletonParts.map( + ({ bone, value }) => + ({ + type: 'bone', + unit: 'cm', bone, label: 'skeleton_bone-' + SkeletonBone[bone], value, - }; - } - - if (part.index === 0) { - return [ - // For some reason, Typescript can't handle this being a GroupPart - // when specifically inside an array. If I directly return it without part, - // it will work. Surely some typing in flatMap's definition is wrong - { - ...part, - type: LabelType.Group, - label: part.parentLabel, - index: undefined, - } as unknown as GroupPartLabel, - part, - ]; - } - return part; - }); + }) satisfies BoneLabel + ); } - return config.skeletonParts.map(({ bone, value }) => ({ - type: LabelType.Bone, - bone, - label: 'skeleton_bone-' + SkeletonBone[bone], - value, - })); - }, [config, ratio]); - - useLayoutEffect(() => { - dispatch({ - ...INVALID_BONE, - label: INVALID_BONE.currentLabel, - type: ProportionChangeType.Bone, - }); - }, [ratio]); + return [ + ...BONE_MAPPING.keys().map((groupName) => { + const groupBones = BONE_MAPPING.get(groupName); + if (!groupBones) throw 'invalid state - this value should always exits'; + const total = config.skeletonParts + .filter(({ bone }) => groupBones.includes(bone)) + .reduce((acc, cur) => cur.value + acc, 0); + return { + type: 'group', + bones: config.skeletonParts + .filter(({ bone }) => groupBones.includes(bone)) + .map(({ bone, value }) => ({ + type: 'group-part', + group: groupName, + unit: 'percent', + bone, + label: 'skeleton_bone-' + SkeletonBone[bone], + value: value, + ratio: value / total, + })), + unit: 'cm', + label: groupName, + value: total, + } satisfies GroupLabel; + }), + ...config.skeletonParts + .filter( + ({ bone }) => !BONE_MAPPING.values().find((bones) => bones.includes(bone)) + ) + .map( + ({ bone, value }) => + ({ + type: 'bone', + unit: 'cm', + bone, + label: 'skeleton_bone-' + SkeletonBone[bone], + value, + }) satisfies BoneLabel + ), + ]; + }, [config, type]); useRPCPacket(RpcMessage.SkeletonConfigResponse, (data: SkeletonConfigResponseT) => { setConfig(data); @@ -298,70 +124,72 @@ export function useManualProportions(): { sendRPCPacket(RpcMessage.SkeletonConfigRequest, new SkeletonConfigRequestT()); }, []); - useEffect(() => { - const conf = { ...config } as Omit | null; - - if (state.type === BoneType.Single) { - // Just ignore if bone is none (because initial state value) - // and check if we actually changed of value - if ( - state.bone === SkeletonBone.NONE || - bodyParts.find((it) => it.type === LabelType.Bone && it.bone === state.bone) - ?.value === state.value - ) { - return; + return { + bodyPartsGrouped, + changeBoneValue: (params) => { + if (!config) return; + if (params.type === 'group') { + const group = BONE_MAPPING.get(params.group); + if (!group) throw 'invalid state - group should exist'; + const oldGroupTotal = config.skeletonParts + .filter(({ bone }) => group.includes(bone)) + .reduce((acc, cur) => cur.value + acc, 0); + for (const part of group) { + const currentValue = config.skeletonParts.find(({ bone }) => bone === part); + if (!currentValue) throw 'invalid state - the bone should exists'; + const currentRatio = currentValue.value / oldGroupTotal; + sendRPCPacket( + RpcMessage.ChangeSkeletonConfigRequest, + new ChangeSkeletonConfigRequestT(part, params.newValue * currentRatio) + ); + } } - sendRPCPacket( - RpcMessage.ChangeSkeletonConfigRequest, - new ChangeSkeletonConfigRequestT(state.bone, state.value) - ); - const b = conf?.skeletonParts?.find(({ bone }) => bone === state.bone); - if (!b || !conf) return; - b.value = state.value; - } else { - const part = bodyParts.find( - (it) => - it.type === LabelType.Group && - (it.label === state.currentLabel || it.label === state.parentLabel) - ) as GroupLabel | undefined; + if (params.type === 'group-part') { + const group = BONE_MAPPING.get(params.group); + if (!group) throw 'invalid state - group should exist'; + const part = config.skeletonParts.find(({ bone }) => bone === params.bone); + if (!part) throw 'invalid state - the part should exists'; + const oldGroupTotal = config.skeletonParts + .filter(({ bone }) => group.includes(bone)) + .reduce((acc, cur) => cur.value + acc, 0); + let newValue = part.value + oldGroupTotal * params.newValue; // the new ratio is computed from the group size and not the bone + if (newValue <= 0) + // Prevent ratios from getting below zero + newValue = 0; - // Check if we found the group we were looking for - // and check if it even changed of value - // we only need to check one child because changing one - // value propagates to the other children - - if ( - !part || - (part.value === state.value && part.bones[0].value === state.bones[0].value) - ) { - return; - } - - for (const child of state.bones) { sendRPCPacket( RpcMessage.ChangeSkeletonConfigRequest, - new ChangeSkeletonConfigRequestT(child.bone, state.value * child.value) + new ChangeSkeletonConfigRequestT(params.bone, newValue) ); - const b = conf?.skeletonParts?.find(({ bone }) => bone === child.bone); - if (!b || !conf) return; - b.value = state.value * child.value; + // Update percent from other bones ratios so the total stays 100% + // it will remove or add to the other bones proportionally to their current value + const diffValue = Math.abs(newValue - part.value); + const signDiff = Math.sign(newValue - part.value); + for (const part of group) { + if (part === params.bone) continue; + const currentValue = config.skeletonParts.find(({ bone }) => bone === part); + if (!currentValue) throw 'invalid state - the bone should exists'; + sendRPCPacket( + RpcMessage.ChangeSkeletonConfigRequest, + new ChangeSkeletonConfigRequestT( + part, + currentValue.value - (diffValue / (group.length - 1)) * signDiff + ) + ); + } } - } - setConfig(conf); - }, [state]); - - return { bodyParts, ratioMode: ratio, state, dispatch, setRatioMode: setRatio }; -} - -function roundedStep(value: number, step: number, add: boolean): number { - if (!add) { - return (Math.round(value * 200) - step * 2) / 200; - } else { - return (Math.round(value * 200) + step * 2) / 200; - } + if (params.type === 'bone') { + sendRPCPacket( + RpcMessage.ChangeSkeletonConfigRequest, + new ChangeSkeletonConfigRequestT(params.bone, params.newValue) + ); + } + sendRPCPacket(RpcMessage.SkeletonConfigRequest, new SkeletonConfigRequestT()); + }, + }; } export const MIN_HEIGHT = 0.4; diff --git a/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.java b/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.java deleted file mode 100644 index 05bdf4116..000000000 --- a/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.slimevr.protocol.rpc; - -import com.google.flatbuffers.FlatBufferBuilder; -import dev.slimevr.tracking.processor.HumanPoseManager; -import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets; -import solarxr_protocol.rpc.SkeletonConfigResponse; -import solarxr_protocol.rpc.SkeletonPart; - - -public class RPCBuilder { - - public static int createSkeletonConfig( - FlatBufferBuilder fbb, - HumanPoseManager humanPoseManager - ) { - int[] partsOffsets = new int[SkeletonConfigOffsets.values().length]; - - for (int index = 0; index < SkeletonConfigOffsets.values().length; index++) { - SkeletonConfigOffsets val = SkeletonConfigOffsets.values[index]; - int part = SkeletonPart - .createSkeletonPart(fbb, val.id, humanPoseManager.getOffset(val)); - partsOffsets[index] = part; - } - - int parts = SkeletonConfigResponse.createSkeletonPartsVector(fbb, partsOffsets); - return SkeletonConfigResponse.createSkeletonConfigResponse(fbb, parts); - } -} diff --git a/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.kt b/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.kt new file mode 100644 index 000000000..89bb3be93 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCBuilder.kt @@ -0,0 +1,25 @@ +package dev.slimevr.protocol.rpc + +import com.google.flatbuffers.FlatBufferBuilder +import dev.slimevr.tracking.processor.HumanPoseManager +import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets +import solarxr_protocol.rpc.SkeletonConfigResponse +import solarxr_protocol.rpc.SkeletonPart + +fun createSkeletonConfig( + fbb: FlatBufferBuilder, + humanPoseManager: HumanPoseManager, +): Int { + val partsOffsets = IntArray(SkeletonConfigOffsets.entries.size) + + for (index in SkeletonConfigOffsets.entries.toTypedArray().indices) { + val `val` = SkeletonConfigOffsets.values[index] + val part = SkeletonPart + .createSkeletonPart(fbb, `val`.id, humanPoseManager.getOffset(`val`)) + partsOffsets[index] = part + } + + val parts = SkeletonConfigResponse.createSkeletonPartsVector(fbb, partsOffsets) + val userHeight = humanPoseManager.userHeightFromConfig + return SkeletonConfigResponse.createSkeletonConfigResponse(fbb, parts, userHeight) +} diff --git a/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCHandler.kt b/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCHandler.kt index 81d5554a8..9176ff6c0 100644 --- a/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCHandler.kt +++ b/server/core/src/main/java/dev/slimevr/protocol/rpc/RPCHandler.kt @@ -259,7 +259,7 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler