diff --git a/server/core/src/main/java/dev/slimevr/config/user.kt b/server/core/src/main/java/dev/slimevr/config/user.kt index fd85b3bf6..0796a6ff0 100644 --- a/server/core/src/main/java/dev/slimevr/config/user.kt +++ b/server/core/src/main/java/dev/slimevr/config/user.kt @@ -18,6 +18,7 @@ private const val USER_CONFIG_VERSION = 1 @Serializable data class UserConfigData( val userHeight: Float = 1.6f, + val proportions: Map = emptyMap(), val version: Int = USER_CONFIG_VERSION, ) 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 db57446f7..1fb1a9178 100644 --- a/server/core/src/main/java/dev/slimevr/heightcalibration/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/heightcalibration/behaviours.kt @@ -2,6 +2,9 @@ package dev.slimevr.heightcalibration +import dev.slimevr.config.UserConfig +import dev.slimevr.config.UserConfigActions +import dev.slimevr.skeleton.computeDefaultProportionsByBone import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.flow.sample import kotlinx.coroutines.flow.takeWhile @@ -62,6 +65,7 @@ object CalibrationBehaviour : HeightCalibrationBehaviourType { internal suspend fun runCalibrationSession( context: HeightCalibrationContext, + userConfig: UserConfig, hmdUpdates: kotlinx.coroutines.flow.Flow, controllerUpdates: kotlinx.coroutines.flow.Flow, clock: () -> Long = System::nanoTime, @@ -178,7 +182,13 @@ internal suspend fun runCalibrationSession( } dispatch(finalStatus, relativeY) - // TODO (when DONE): persist height to config, update user proportions, clear mounting reset flags + if (finalStatus == UserHeightCalibrationStatus.DONE) { + userConfig.context.dispatch( + UserConfigActions.Update { + copy(userHeight = relativeY, proportions = computeDefaultProportionsByBone(relativeY)) + } + ) + } } } } ?: dispatch(UserHeightCalibrationStatus.ERROR_TIMEOUT) 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 b5fcbf87c..fa80e9256 100644 --- a/server/core/src/main/java/dev/slimevr/heightcalibration/module.kt +++ b/server/core/src/main/java/dev/slimevr/heightcalibration/module.kt @@ -3,6 +3,7 @@ package dev.slimevr.heightcalibration import dev.slimevr.VRServer +import dev.slimevr.config.UserConfig import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import io.github.axisangles.ktmath.Quaternion @@ -40,6 +41,7 @@ val INITIAL_HEIGHT_CALIBRATION_STATE = HeightCalibrationState( class HeightCalibrationManager( val context: HeightCalibrationContext, val serverContext: VRServer, + private val userConfig: UserConfig, ) { private var sessionJob: Job? = null @@ -76,7 +78,7 @@ class HeightCalibrationManager( fun start() { sessionJob?.cancel() - sessionJob = context.scope.launch { runCalibrationSession(context, hmdUpdates, controllerUpdates) } + sessionJob = context.scope.launch { runCalibrationSession(context, userConfig, hmdUpdates, controllerUpdates) } } fun cancel() { @@ -88,6 +90,7 @@ class HeightCalibrationManager( companion object { fun create( serverContext: VRServer, + userConfig: UserConfig, scope: CoroutineScope, ): HeightCalibrationManager { val behaviours = listOf(CalibrationBehaviour) @@ -96,7 +99,7 @@ class HeightCalibrationManager( scope = scope, behaviours = behaviours, ) - return HeightCalibrationManager(context = context, serverContext = serverContext) + return HeightCalibrationManager(context = context, serverContext = serverContext, userConfig = userConfig) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt new file mode 100644 index 000000000..67d47da12 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt @@ -0,0 +1,130 @@ +package dev.slimevr.skeleton + +import dev.slimevr.config.UserConfig +import io.github.axisangles.ktmath.Quaternion +import io.github.axisangles.ktmath.Vector3 +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import solarxr_protocol.datatypes.BodyPart +import kotlin.math.cos +import kotlin.math.sin +import kotlin.random.Random + +class ProportionsBehaviour : SkeletonBehaviour { + override fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) { + is SkeletonActions.SetProportions -> { + val newBones = state.bones.mapValues { (bodyPart, bone) -> + bone.copy(length = action.lengths[bodyPart] ?: bone.length) + } + state.copy(bones = newBones, userHeight = computeUserHeight(newBones.mapValues { (_, bone) -> bone.length })) + } + else -> state + } +} + +class ScaledProportionsBehaviour(private val userConfig: UserConfig) : SkeletonBehaviour { + override fun observe(receiver: Skeleton) { + userConfig.context.state + .map { state -> state.data.proportions } + .distinctUntilChanged() + .onEach { proportions -> + if (proportions.isNotEmpty()) { + receiver.context.dispatch(SkeletonActions.SetProportions(expandProportions(proportions))) + } + } + .launchIn(receiver.context.scope) + } +} + +class HeightLogBehaviour : SkeletonBehaviour { + override fun observe(receiver: Skeleton) { + receiver.context.scope.launch { + receiver.context.state + .map { state -> state.userHeight } + .distinctUntilChanged() + .collect { height -> println("User height changed: ${"%.2f".format(height)}m") } + } + } +} + +class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour { + + override fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState { + val bones = state.bones.toMutableMap() + return when (action) { + is SkeletonActions.SetBoneRotation -> { + val bone = bones[action.bodyPart] ?: return state + bones[action.bodyPart] = bone.copy(rotation = action.rotation) + state.copy(bones = bones) + } + else -> state + } + } + + override fun observe(receiver: Skeleton) { + receiver.context.scope.launch { + val intervalMs = (1000f / inputHz).toLong() + val startTime = System.currentTimeMillis() + while (true) { + delay(intervalMs) + val elapsed = (System.currentTimeMillis() - startTime) / 1000f + receiver.context.dispatch( + SkeletonActions.SetBoneRotation( + BodyPart.CHEST, + Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)), + ) + ) + receiver.context.dispatch( + SkeletonActions.SetBoneRotation( + BodyPart.LEFT_LOWER_LEG, + Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)), + ) + ) + } + } + } +} + +class RandomProportionsBehaviour(val intervalMs: Long) : SkeletonBehaviour { + private val targets = listOf( + BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG, + BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG, + BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM, + ) + + override fun observe(receiver: Skeleton) { + receiver.context.scope.launch { + while (true) { + delay(intervalMs) + receiver.context.dispatch( + SkeletonActions.SetProportions( + targets.associateWith { Random.nextFloat() * 0.4f + 0.2f } + ) + ) + } + } + } +} + +class ComputedSkeletonBehaviour( + val hz: Float = 100f, + val processors: List = emptyList() +) : SkeletonBehaviour { + override fun observe(receiver: Skeleton) { + val intervalMs = (1000f / hz).toLong() + receiver.context.scope.launch { + while (true) { + delay(intervalMs) + val targetState = receiver.context.state.value + val processed = processors + .filter { processor -> processor.enabled } + .fold(targetState) { state, processor -> processor.process(state) } + receiver.computed.value = buildBones(processed) + } + } + } +} \ No newline at end of file diff --git a/server/core/src/main/java/dev/slimevr/skeleton/bonegeometry.kt b/server/core/src/main/java/dev/slimevr/skeleton/bonegeometry.kt new file mode 100644 index 000000000..d8b1eea01 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/skeleton/bonegeometry.kt @@ -0,0 +1,70 @@ +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 + +internal val BONE_TAIL_OFFSETS: Map = run { + val offsets = mutableMapOf() + iterateBodyPartHierarchy().forEach { (_, child) -> + val length = when (child) { + BodyPart.HEAD, BodyPart.NECK -> 0.1f + + BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER -> 0.175f + + BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM, + BodyPart.LEFT_LOWER_ARM, BodyPart.RIGHT_LOWER_ARM, + -> 0.26f + + BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND -> 0.13f + + BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL, + BodyPart.LEFT_INDEX_DISTAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_PROXIMAL, + BodyPart.LEFT_MIDDLE_DISTAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_PROXIMAL, + BodyPart.LEFT_RING_DISTAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_PROXIMAL, + BodyPart.LEFT_LITTLE_DISTAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_PROXIMAL, + + BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL, + BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL, + BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL, + BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL, + BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL, + -> 0.025f + + BodyPart.UPPER_CHEST, BodyPart.CHEST -> 0.16f + + BodyPart.WAIST -> 0.2f + + BodyPart.HIP -> 0.04f + + BodyPart.LEFT_HIP, BodyPart.RIGHT_HIP -> 0.13f + + BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG -> 0.42f + + BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG -> 0.5f + + BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT -> 0.05f + + else -> 0.1f + } + val restRotation = when (child) { + BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT -> Quaternion.rotationAroundXAxis(FastMath.HALF_PI) + else -> Quaternion.IDENTITY + } + val offset = when (child) { + BodyPart.HEAD -> Vector3(0f, 0f, length) + BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND -> Vector3(0f, 0f, -length) + BodyPart.LEFT_SHOULDER -> Vector3(-length, -0.08f, 0f) + BodyPart.RIGHT_SHOULDER -> Vector3(length, -0.08f, 0f) + BodyPart.LEFT_HIP -> Vector3(-length, 0f, 0f) + BodyPart.RIGHT_HIP -> Vector3(length, 0f, 0f) + else -> Vector3(0f, -length, 0f) + } + offsets[child] = restRotation.inv().sandwich(offset) + } + offsets +} + +internal val BONE_TAIL_DIRECTIONS: Map = + BONE_TAIL_OFFSETS.mapValues { (_, offset) -> offset.unit() } 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 f282936a2..7daeabcca 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/module.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/module.kt @@ -1,20 +1,14 @@ package dev.slimevr.skeleton import com.jme3.math.FastMath +import dev.slimevr.config.UserConfig import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.launch import solarxr_protocol.datatypes.BodyPart -import kotlin.math.cos -import kotlin.math.sin -import kotlin.random.Random data class BoneState( val bodyPart: BodyPart, @@ -32,94 +26,6 @@ data class BoneState( get() = tailPosition - headPosition } -private val BONE_TAIL_OFFSETS: Map = run { - val offsets = mutableMapOf() - iterateBodyPartHierarchy().forEach { (_, child) -> - val length = when (child) { - BodyPart.HEAD, BodyPart.NECK -> 0.1f - - BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER -> 0.175f - - BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM, - BodyPart.LEFT_LOWER_ARM, BodyPart.RIGHT_LOWER_ARM, - -> 0.26f - - BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND -> 0.13f - - BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL, - BodyPart.LEFT_INDEX_DISTAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_PROXIMAL, - BodyPart.LEFT_MIDDLE_DISTAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_PROXIMAL, - BodyPart.LEFT_RING_DISTAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_PROXIMAL, - BodyPart.LEFT_LITTLE_DISTAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_PROXIMAL, - - BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL, - BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL, - BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL, - BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL, - BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL, - -> 0.025f - - BodyPart.UPPER_CHEST, BodyPart.CHEST -> 0.16f - - BodyPart.WAIST -> 0.2f - - BodyPart.HIP -> 0.04f - - BodyPart.LEFT_HIP, BodyPart.RIGHT_HIP -> 0.13f - - BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG -> 0.42f - - BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG -> 0.5f - - BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT -> 0.05f - - else -> 0.1f - } - val restRotation = when (child) { - BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT -> Quaternion.rotationAroundXAxis(FastMath.HALF_PI) - else -> Quaternion.IDENTITY - } - val offset = when (child) { - BodyPart.HEAD -> Vector3(0f, 0f, length) - BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND -> Vector3(0f, 0f, -length) - BodyPart.LEFT_SHOULDER -> Vector3(-length, -0.08f, 0f) - BodyPart.RIGHT_SHOULDER -> Vector3(length, -0.08f, 0f) - BodyPart.LEFT_HIP -> Vector3(-length, 0f, 0f) - BodyPart.RIGHT_HIP -> Vector3(length, 0f, 0f) - else -> Vector3(0f, -length, 0f) - } - offsets[child] = restRotation.inv().sandwich(offset) - } - offsets -} - -private val BONE_TAIL_DIRECTIONS: Map = - BONE_TAIL_OFFSETS.mapValues { (_, offset) -> offset.unit() } - -private val SPINE_CHAIN = listOf( - BodyPart.NECK, - BodyPart.UPPER_CHEST, - BodyPart.CHEST, - BodyPart.WAIST, - BodyPart.HIP, -) - -private val LEG_PAIRS = listOf( - BodyPart.LEFT_UPPER_LEG to BodyPart.RIGHT_UPPER_LEG, - BodyPart.LEFT_LOWER_LEG to BodyPart.RIGHT_LOWER_LEG, -) - -private fun computeUserHeight(bones: Map): Double { - val spineHeight = SPINE_CHAIN.sumOf { part -> - (bones[part]?.length ?: error("$part should exist")).toDouble() - } - val legHeight = LEG_PAIRS.sumOf { (left, right) -> - val leftLen = (bones[left]?.length ?: error("$left should exist")).toDouble() - val rightLen = (bones[right]?.length ?: error("$right should exist")).toDouble() - maxOf(leftLen, rightLen) - } - return spineHeight + legHeight -} data class SkeletonState(val bones: Map, val userHeight: Double) @@ -131,7 +37,7 @@ val DEFAULT_SKELETON_STATE: SkeletonState = run { } bodyPart to BoneState(bodyPart = bodyPart, length = tailOffset.len(), rotation = restRotation) } - SkeletonState(bones = bones, userHeight = computeUserHeight(bones)) + SkeletonState(bones = bones, userHeight = computeUserHeight(bones.mapValues { (_, bone) -> bone.length })) } fun buildBones(state: SkeletonState, rootHead: Vector3 = Vector3.NULL): Map { @@ -158,193 +64,20 @@ sealed interface SkeletonActions { typealias SkeletonContext = Context typealias SkeletonBehaviour = Behaviour -class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour { - - override fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState { - val bones = state.bones.toMutableMap() - return when (action) { - is SkeletonActions.SetBoneRotation -> { - val bone = bones[action.bodyPart] ?: return state - bones[action.bodyPart] = bone.copy(rotation = action.rotation) - state.copy(bones = bones) - } - is SkeletonActions.SetProportions -> state - } - } - - override fun observe(receiver: Skeleton) { - receiver.context.scope.launch { - val intervalMs = (1000f / inputHz).toLong() - val startTime = System.currentTimeMillis() - while (true) { - delay(intervalMs) - val elapsed = (System.currentTimeMillis() - startTime) / 1000f - receiver.context.dispatch( - SkeletonActions.SetBoneRotation( - BodyPart.CHEST, - Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)), - ) - ) - receiver.context.dispatch( - SkeletonActions.SetBoneRotation( - BodyPart.LEFT_LOWER_LEG, - Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)), - ) - ) - } - } - } -} - -class RandomProportionsBehaviour(val intervalMs: Long) : SkeletonBehaviour { - private val targets = listOf( - BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG, - BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG, - BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM, - ) - - override fun observe(receiver: Skeleton) { - receiver.context.scope.launch { - while (true) { - delay(intervalMs) - receiver.context.dispatch( - SkeletonActions.SetProportions( - targets.associateWith { Random.nextFloat() * 0.4f + 0.2f } - ) - ) - } - } - } -} - -class HeightLogBehaviour : SkeletonBehaviour { - override fun observe(receiver: Skeleton) { - receiver.context.scope.launch { - receiver.context.state - .map { state -> state.userHeight } - .distinctUntilChanged() - .collect { height -> println("User height changed: ${"%.2f".format(height)}m") } - } - } -} - -class ProportionsBehaviour : SkeletonBehaviour { - override fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) { - is SkeletonActions.SetProportions -> { - val newBones = state.bones.mapValues { (bodyPart, bone) -> - bone.copy(length = action.lengths[bodyPart] ?: bone.length) - } - state.copy(bones = newBones, userHeight = computeUserHeight(newBones)) - } - else -> state - } -} - -interface SkeletonProcessor { - var enabled: Boolean - fun process(state: SkeletonState): SkeletonState -} - -class SmoothingProcessor(var smoothing: Float) : SkeletonProcessor { - override var enabled: Boolean = true - private var smoothedRotations: Map = emptyMap() - private var smoothedLengths: Map = emptyMap() - - override fun process(state: SkeletonState): SkeletonState { - val alpha = 1f - smoothing.coerceAtMost(0.99f) - smoothedRotations = state.bones.mapValues { (bodyPart, bone) -> - (smoothedRotations[bodyPart] ?: bone.rotation).lerpR(bone.rotation, alpha).unit() - } - smoothedLengths = state.bones.mapValues { (bodyPart, bone) -> - val prev = smoothedLengths[bodyPart] ?: bone.length - prev + (bone.length - prev) * alpha - } - return state.copy( - bones = state.bones.mapValues { (bodyPart, bone) -> - bone.copy( - rotation = smoothedRotations[bodyPart] ?: bone.rotation, - length = smoothedLengths[bodyPart] ?: bone.length, - ) - } - ) - } -} - -class PredictionProcessor(var predictionAmount: Float) : SkeletonProcessor { - override var enabled: Boolean = true - - private data class BoneVelocity( - val lastRotation: Quaternion, - val rotationDelta: Quaternion, - val lastLength: Float, - val lengthDelta: Float, - ) - - private var velocities: Map = emptyMap() - - override fun process(state: SkeletonState): SkeletonState { - val newVelocities = mutableMapOf() - val newBones = state.bones.mapValues { (bodyPart, bone) -> - val prev = velocities[bodyPart] - if (prev == null) { - newVelocities[bodyPart] = BoneVelocity(bone.rotation, Quaternion.IDENTITY, bone.length, 0f) - return@mapValues bone - } - val rotationDelta = if (bone.rotation !== prev.lastRotation) { - bone.rotation * prev.lastRotation.inv() - } else { - prev.rotationDelta - } - val lengthDelta = if (bone.length != prev.lastLength) { - bone.length - prev.lastLength - } else { - prev.lengthDelta - } - newVelocities[bodyPart] = BoneVelocity(bone.rotation, rotationDelta, bone.length, lengthDelta) - val scaledDelta = Quaternion.IDENTITY.lerpR(rotationDelta, predictionAmount).unit() - bone.copy( - rotation = (scaledDelta * bone.rotation).unit(), - length = bone.length + lengthDelta * predictionAmount, - ) - } - velocities = newVelocities - return state.copy(bones = newBones) - } -} - -class ComputedSkeletonBehaviour( - val hz: Float = 100f, - val processors: List = emptyList() -) : SkeletonBehaviour { - override fun observe(receiver: Skeleton) { - val intervalMs = (1000f / hz).toLong() - receiver.context.scope.launch { - while (true) { - delay(intervalMs) - val targetState = receiver.context.state.value - val processed = processors - .filter { processor -> processor.enabled } - .fold(targetState) { state, processor -> processor.process(state) } - receiver.computed.value = buildBones(processed) - } - } - } -} - class Skeleton( val context: SkeletonContext, val computed: MutableStateFlow>, ) { companion object { - fun create(scope: CoroutineScope): Skeleton { + fun create(scope: CoroutineScope, userConfig: UserConfig): Skeleton { val behaviours = listOf( ProportionsBehaviour(), + ScaledProportionsBehaviour(userConfig), HeightLogBehaviour(), - RandomProportionsBehaviour(intervalMs = 3000L), - YouSpinMeRightRoundBehaviour(inputHz = 1f), + YouSpinMeRightRoundBehaviour(inputHz = 10f), ComputedSkeletonBehaviour(processors = listOf( -// PredictionProcessor(predictionAmount = 0.3f), - SmoothingProcessor(smoothing = 1f) +// PredictionProcessor(predictionAmount = 0.3f), + SmoothingProcessor(smoothing = 0.3f) )), ) @@ -360,4 +93,4 @@ class Skeleton( return skeleton } } -} +} \ No newline at end of file diff --git a/server/core/src/main/java/dev/slimevr/skeleton/processors.kt b/server/core/src/main/java/dev/slimevr/skeleton/processors.kt new file mode 100644 index 000000000..51edb41d2 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/skeleton/processors.kt @@ -0,0 +1,76 @@ +package dev.slimevr.skeleton + +import io.github.axisangles.ktmath.Quaternion +import solarxr_protocol.datatypes.BodyPart + +interface SkeletonProcessor { + var enabled: Boolean + fun process(state: SkeletonState): SkeletonState +} + +class SmoothingProcessor(var smoothing: Float) : SkeletonProcessor { + override var enabled: Boolean = true + private var smoothedRotations: Map = emptyMap() + private var smoothedLengths: Map = emptyMap() + + override fun process(state: SkeletonState): SkeletonState { + val alpha = 1f - smoothing.coerceAtMost(0.99f) + smoothedRotations = state.bones.mapValues { (bodyPart, bone) -> + (smoothedRotations[bodyPart] ?: bone.rotation).lerpR(bone.rotation, alpha).unit() + } + smoothedLengths = state.bones.mapValues { (bodyPart, bone) -> + val prev = smoothedLengths[bodyPart] ?: bone.length + prev + (bone.length - prev) * alpha + } + return state.copy( + bones = state.bones.mapValues { (bodyPart, bone) -> + bone.copy( + rotation = smoothedRotations[bodyPart] ?: bone.rotation, + length = smoothedLengths[bodyPart] ?: bone.length, + ) + } + ) + } +} + +class PredictionProcessor(var predictionAmount: Float) : SkeletonProcessor { + override var enabled: Boolean = true + + private data class BoneVelocity( + val lastRotation: Quaternion, + val rotationDelta: Quaternion, + val lastLength: Float, + val lengthDelta: Float, + ) + + private var velocities: Map = emptyMap() + + override fun process(state: SkeletonState): SkeletonState { + val newVelocities = mutableMapOf() + val newBones = state.bones.mapValues { (bodyPart, bone) -> + val prev = velocities[bodyPart] + if (prev == null) { + newVelocities[bodyPart] = BoneVelocity(bone.rotation, Quaternion.IDENTITY, bone.length, 0f) + return@mapValues bone + } + val rotationDelta = if (bone.rotation !== prev.lastRotation) { + bone.rotation * prev.lastRotation.inv() + } else { + prev.rotationDelta + } + val lengthDelta = if (bone.length != prev.lastLength) { + bone.length - prev.lastLength + } else { + prev.lengthDelta + } + newVelocities[bodyPart] = BoneVelocity(bone.rotation, rotationDelta, bone.length, lengthDelta) + val scaledDelta = Quaternion.IDENTITY.lerpR(rotationDelta, predictionAmount).unit() + bone.copy( + rotation = (scaledDelta * bone.rotation).unit(), + length = bone.length + lengthDelta * predictionAmount, + ) + } + velocities = newVelocities + return state.copy(bones = newBones) + } +} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt b/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt new file mode 100644 index 000000000..3eb029f32 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/skeleton/proportions.kt @@ -0,0 +1,79 @@ +package dev.slimevr.skeleton + +import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.rpc.SkeletonBone + +// Sum of default bone lengths for height-contributing bones (from Drillis and Contini 1966). +// Used to normalize HEIGHT_SCALED_BONE_RATIOS. +private const val DEFAULT_HEIGHT = 0.1f + 0.16f + 0.16f + 0.20f + 0.04f + 0.42f + 0.50f // = 1.58f + +// Maps each solarxr SkeletonBone to the BodyPart(s) it controls in the skeleton. +// Symmetric bones (legs, arms) map to both left and right sides. +val SKELETON_BONE_TO_BODY_PARTS: Map> = mapOf( + SkeletonBone.HEAD to listOf(BodyPart.HEAD), + SkeletonBone.NECK to listOf(BodyPart.NECK), + SkeletonBone.UPPER_CHEST to listOf(BodyPart.UPPER_CHEST), + SkeletonBone.CHEST to listOf(BodyPart.CHEST), + SkeletonBone.WAIST to listOf(BodyPart.WAIST), + SkeletonBone.HIP to listOf(BodyPart.HIP), + SkeletonBone.UPPER_LEG to listOf(BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG), + SkeletonBone.LOWER_LEG to listOf(BodyPart.LEFT_LOWER_LEG, BodyPart.RIGHT_LOWER_LEG), + SkeletonBone.FOOT_LENGTH to listOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT), + SkeletonBone.UPPER_ARM to listOf(BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM), + SkeletonBone.LOWER_ARM to listOf(BodyPart.LEFT_LOWER_ARM, BodyPart.RIGHT_LOWER_ARM), +) + +// Per-bone fraction of total standing height, derived from Drillis and Contini (1966). +// Includes spine, legs, and arms, all bones whose length scales with user height. +// Non-height bones (HEAD, FOOT_LENGTH) are absent; they keep fixed defaults from DEFAULT_SKELETON_STATE. +private val HEIGHT_SCALED_BONE_RATIOS: Map = mapOf( + SkeletonBone.NECK to 0.1f / DEFAULT_HEIGHT, + SkeletonBone.UPPER_CHEST to 0.16f / DEFAULT_HEIGHT, + SkeletonBone.CHEST to 0.16f / DEFAULT_HEIGHT, + SkeletonBone.WAIST to 0.20f / DEFAULT_HEIGHT, + SkeletonBone.HIP to 0.04f / DEFAULT_HEIGHT, + SkeletonBone.UPPER_LEG to 0.42f / DEFAULT_HEIGHT, + SkeletonBone.LOWER_LEG to 0.50f / DEFAULT_HEIGHT, + SkeletonBone.UPPER_ARM to 0.26f / DEFAULT_HEIGHT, + SkeletonBone.LOWER_ARM to 0.26f / DEFAULT_HEIGHT, +) + +// Subset of HEIGHT_SCALED_BONE_RATIOS whose lengths actually sum to standing height (spine + legs). +// Arms are excluded: they scale with height but are not part of the height measurement. +// For symmetric bones (UPPER_LEG, LOWER_LEG) computeUserHeight takes the larger side. +private val HEIGHT_CONTRIBUTING_BONES: Set = + HEIGHT_SCALED_BONE_RATIOS.keys - setOf(SkeletonBone.UPPER_ARM, SkeletonBone.LOWER_ARM) + +// Sums the HEIGHT_CONTRIBUTING_BONES lengths to derive standing height. +// For symmetric bones (legs) the larger side is used. +fun computeUserHeight(lengths: Map): Double = + HEIGHT_CONTRIBUTING_BONES.sumOf { bone -> + val bodyParts = SKELETON_BONE_TO_BODY_PARTS[bone] ?: return@sumOf 0.0 + bodyParts.maxOfOrNull { lengths[it] ?: 0f }?.toDouble() ?: 0.0 + } + +// Returns proportions keyed by SkeletonBone.name for config storage. +// Only height-scaled bones are included. +fun computeDefaultProportionsByBone(height: Float): Map = + HEIGHT_SCALED_BONE_RATIOS.mapKeys { (bone, _) -> bone.name } + .mapValues { (_, ratio) -> height * ratio } + +// Returns proportions for all tracked bones: height-scaled + default lengths for the rest. +fun computeAllDefaultProportionsByBone(height: Float): Map { + val heightScaled = computeDefaultProportionsByBone(height) + val nonScaled = SKELETON_BONE_TO_BODY_PARTS + .filter { (bone, _) -> bone !in HEIGHT_SCALED_BONE_RATIOS } + .mapNotNull { (bone, bodyParts) -> + val length = bodyParts + .mapNotNull { DEFAULT_SKELETON_STATE.bones[it]?.length } + .average().takeIf { !it.isNaN() }?.toFloat() ?: return@mapNotNull null + bone.name to length + }.toMap() + return heightScaled + nonScaled +} + +fun expandProportions(proportions: Map): Map = + proportions.entries.flatMap { (boneName, length) -> + val bone = SkeletonBone.entries.firstOrNull { it.name == boneName } ?: return@flatMap emptyList() + (SKELETON_BONE_TO_BODY_PARTS[bone] ?: return@flatMap emptyList()).map { bodyPart -> bodyPart to length } + }.toMap() diff --git a/server/core/src/main/java/dev/slimevr/solarxr/skeletonconfig.kt b/server/core/src/main/java/dev/slimevr/solarxr/skeletonconfig.kt new file mode 100644 index 000000000..de54cfdf0 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/solarxr/skeletonconfig.kt @@ -0,0 +1,80 @@ +package dev.slimevr.solarxr + +import dev.slimevr.config.UserConfig +import dev.slimevr.config.UserConfigActions +import dev.slimevr.skeleton.SKELETON_BONE_TO_BODY_PARTS +import dev.slimevr.skeleton.Skeleton +import dev.slimevr.skeleton.computeAllDefaultProportionsByBone +import dev.slimevr.skeleton.computeDefaultProportionsByBone +import dev.slimevr.skeleton.computeUserHeight +import dev.slimevr.skeleton.expandProportions +import solarxr_protocol.rpc.ChangeSettingsRequest +import solarxr_protocol.rpc.ChangeSkeletonConfigRequest +import solarxr_protocol.rpc.SkeletonConfigRequest +import solarxr_protocol.rpc.SkeletonConfigResponse +import solarxr_protocol.rpc.SkeletonPart +import solarxr_protocol.rpc.SkeletonResetAllRequest + +private const val MIN_HEIGHT = 1.0f + +class SkeletonBehaviour( + private val userConfig: UserConfig, + private val skeleton: Skeleton, +) : SolarXRConnectionBehaviour { + + private fun buildConfigResponse(): SkeletonConfigResponse { + val proportions = userConfig.context.state.value.data.proportions + val bones = skeleton.context.state.value.bones + val skeletonParts = SKELETON_BONE_TO_BODY_PARTS.mapNotNull { (skeletonBone, bodyParts) -> + val length = proportions[skeletonBone.name] + ?: bodyParts.mapNotNull { bones[it]?.length }.average().takeIf { !it.isNaN() }?.toFloat() + ?: return@mapNotNull null + SkeletonPart(bone = skeletonBone, value = length) + } + val expanded = expandProportions(proportions) + val userHeight = if (expanded.isNotEmpty()) { + computeUserHeight(expanded).toFloat() + } else { + skeleton.context.state.value.userHeight.toFloat() + } + return SkeletonConfigResponse(skeletonParts = skeletonParts, userHeight = userHeight) + } + + override fun observe(receiver: SolarXRConnection) { + receiver.rpcDispatcher.on { + receiver.sendRpc(buildConfigResponse()) + } + + receiver.rpcDispatcher.on { req -> + req.modelSettings?.skeletonHeight?.let { skeletonHeight -> + val hmdHeight = skeletonHeight.hmdHeight ?: return@let + val floorHeight = skeletonHeight.floorHeight ?: 0f + val height = hmdHeight - floorHeight + if (height >= MIN_HEIGHT) { + userConfig.context.dispatch( + UserConfigActions.Update { + copy(userHeight = height, proportions = computeDefaultProportionsByBone(height)) + } + ) + } + } + } + + receiver.rpcDispatcher.on { + val height = userConfig.context.state.value.data.userHeight + if (height >= MIN_HEIGHT) { + val defaults = computeAllDefaultProportionsByBone(height) + userConfig.context.dispatch(UserConfigActions.Update { copy(proportions = defaults) }) + } + receiver.sendRpc(buildConfigResponse()) + } + + receiver.rpcDispatcher.on { req -> + val bone = req.bone ?: return@on + userConfig.context.dispatch( + UserConfigActions.Update { copy(proportions = proportions + (bone.name to req.value)) } + ) + receiver.sendRpc(buildConfigResponse()) + } + } +} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt index 8df0fe797..5ec21502a 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -18,6 +18,7 @@ import dev.slimevr.solarxr.FirmwareBehaviour import dev.slimevr.solarxr.HeightCalibrationBehaviour import dev.slimevr.solarxr.ProvisioningBehaviour import dev.slimevr.solarxr.SerialBehaviour +import dev.slimevr.solarxr.SkeletonBehaviour import dev.slimevr.solarxr.VrcBehaviour import dev.slimevr.solarxr.createSolarXRWebsocketServer import dev.slimevr.udp.createUDPTrackerServer @@ -33,10 +34,10 @@ fun main(args: Array) = runBlocking { val firmwareManager = FirmwareManager.create(serialServer = serialServer, scope = this) val vrcConfigManager = createDesktopVRCConfigManager(config = config, scope = this) - val heightCalibrationManager = HeightCalibrationManager.create(serverContext = server, scope = this) + val heightCalibrationManager = HeightCalibrationManager.create(serverContext = server, userConfig = config.userConfig, scope = this) val provisioningManager = ProvisioningManager.create(serialServer, this) - val skeleton = Skeleton.create(this) + val skeleton = Skeleton.create(this, config.userConfig) launch { createUDPTrackerServer(server, config) @@ -49,9 +50,10 @@ fun main(args: Array) = runBlocking { DataFeedInitBehaviour(server, skeleton), SerialBehaviour(serialServer), FirmwareBehaviour(server, firmwareManager), - VrcBehaviour(vrcConfigManager, server, userHeight = { config.userConfig.context.state.value.data.userHeight.toDouble() }), + VrcBehaviour(vrcConfigManager, server, userHeight = { skeleton.context.state.value.userHeight }), HeightCalibrationBehaviour(heightCalibrationManager), - ProvisioningBehaviour(server, provisioningManager) + ProvisioningBehaviour(server, provisioningManager), + SkeletonBehaviour(config.userConfig, skeleton), ) launch { createSolarXRWebsocketServer(solarXRBehaviours) } launch { createIpcServers(server, solarXRBehaviours) }