Expected TPS

This commit is contained in:
Erimel committed 2026-09-23 17:39:43 -04:00
1 parent a53879be3f
commit b21e50a041
8 files changed
+84 -53

No files matched your search

@@ -67,6 +67,7 @@ internal fun ensureHidTracker(receiver: HIDReceiver, hidId: Int, deviceId: Int,
hardwareId = deviceState.address,
origin = DeviceOrigin.HID,
appContext = receiver.appContext,
expectedTps = 100u, // TODO: receive from firmware
)
receiver.appContext.server.context.dispatch(VRServerActions.NewTracker(trackerId, newTracker))
// HID does not have a rest calibration signal
@@ -66,10 +66,10 @@ class LocalizerResetBehaviour(val settings: Settings) : SkeletonBehaviour {
}
}
class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour {
class YouSpinMeRightRoundBehaviour(val inputHz: Int = 1) : SkeletonBehaviour {
override fun observe(receiver: Skeleton) {
receiver.context.scope.launch {
val intervalMs = (1000f / inputHz).toLong()
val intervalMs = (1000f / inputHz.toFloat()).toLong()
val startTime = timeSource.markNow()
while (true) {
delay(intervalMs)
@@ -77,15 +77,21 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour
val state = receiver.context.state.value
receiver.context.dispatch(
SkeletonActions.SetBoneRotation(
SkeletonActions.SetBonePose(
BodyPart.LOWER_CHEST,
inputHz.toUShort(),
Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)),
Vector3.ZERO,
null,
),
)
receiver.context.dispatch(
SkeletonActions.SetBoneRotation(
SkeletonActions.SetBonePose(
BodyPart.LEFT_LOWER_LEG,
inputHz.toUShort(),
Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)),
Vector3.ZERO,
null,
),
)
@@ -94,8 +100,11 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour
val circleZ = sin(elapsed * 2f) * circleRadius
val jumpHeight = maxOf(0f, sin(elapsed * 3f) * 0.3f)
receiver.context.dispatch(
SkeletonActions.SetBonePosition(
SkeletonActions.SetBonePose(
BodyPart.HEAD,
inputHz.toUShort(),
Quaternion.IDENTITY,
Vector3.ZERO,
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
),
)
@@ -259,7 +268,7 @@ class ComputedSkeletonBehaviour(
var fk = buildBones(boneInputs)
// These write into fk, not the inputs, and the rebuilds below carry their values forward
for (processor in fkComputedProcessors) processor.process(fk)
for (processor in fkComputedProcessors) processor.process(fk, boneInputs)
// Run FK processors. They write into boneInputs, and beforeFk allows figuring out
// which bones changed.
@@ -276,9 +285,9 @@ class ComputedSkeletonBehaviour(
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(bodyPart, boneInput.position, false))
// For head changed position, set the new position in state (for Localizer).
if (bodyPart == BodyPart.HEAD && !boneInput.isPositionActive && boneInput.position != previous?.position) {
receiver.context.dispatch(SkeletonActions.SetHeadPosition(boneInput.position))
}
}
// Inputs changed; re-run FK
@@ -305,7 +314,7 @@ class ComputedSkeletonBehaviour(
)
// Run ik computed processors. These are used to update values for consumers (e.g. drivers wants velocity after IK)
for (processor in ikComputedProcessors) processor.process(ikOutput.bones)
for (processor in ikComputedProcessors) processor.process(ikOutput.bones, boneInputs)
// Updated the computed skeleton with the result
receiver.computed.tryEmit(ikOutput.bones)
@@ -2,18 +2,19 @@ package dev.slimevr.skeleton.computedprocessors
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.InputSkeleton
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.findFirstParent
import dev.slimevr.skeleton.forEachBone
import dev.slimevr.util.inFloatingSeconds
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.rpc.ResetType
import kotlin.time.Duration.Companion.milliseconds
private data class VelocityData(
val rotation: Quaternion,
@@ -29,12 +30,13 @@ private fun computeVelocity(currentVelocityData: VelocityData, lastVelocityData:
)
}
// At least 1. >1 will make it smoother but less reactive.
private const val SMOOTHING_MULTIPLIER = 3f
// We smooth out the velocity since if a tracker is sending at 100tps and skeleton is at 500hz,
// 4 frames out of 5 will have little to no velocity, so we need to smooth at least across those frames.
// TODO: should we try to smooth less for it to be more responsive? Fine tune or find a better solution.
private val SMOOTHING_WINDOW = 40.milliseconds.inFloatingSeconds
private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, deltaTime: Float): Velocity {
val t = (deltaTime / SMOOTHING_WINDOW).coerceAtMost(1f)
private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, deltaTime: Float, expectedTps: UShort): Velocity {
val t = (deltaTime / (SMOOTHING_MULTIPLIER / expectedTps.toFloat())).coerceAtMost(1f)
return Velocity(
linear = lastVelocity.linear.lerp(currentVelocity.linear, t),
angular = lastVelocity.angular.lerp(currentVelocity.angular, t),
@@ -51,25 +53,28 @@ class VelocityComputedProcessor :
private val lastVelocityData: BodyPartMap<VelocityData> = bodyPartMap()
private var lastProcessTime = timeSource.markNow()
override fun process(mutableComputedSkeleton: ComputedSkeleton) {
override fun process(mutableComputedSkeleton: ComputedSkeleton, inputSkeleton: InputSkeleton) {
// One clock read for the whole pass, so every bone shares the same interval
val now = timeSource.markNow()
val deltaTime = (now - lastProcessTime).inFloatingSeconds
lastProcessTime = now
mutableComputedSkeleton.forEachBone { part, bone ->
val lastVelocityData = lastVelocityData[part]
val lastVelocity = lastVelocities[part] ?: ZERO_VELOCITY
// The expected TPS for the bone is its input's or its first parent that has one.
// If there's no available expected TPS, that means there's no movement to derive velocity from anyways.
val expectedTps = inputSkeleton[part]?.expectedTps
?: inputSkeleton[part.findFirstParent { inputSkeleton[it]?.expectedTps != null }]?.expectedTps
?: return@forEachBone
// Compute current velocity
val currentVelocityData = VelocityData(bone.rotation, bone.tailPosition)
val currentVelocity = lastVelocityData?.let { computeVelocity(currentVelocityData, it, deltaTime) } ?: ZERO_VELOCITY
val currentVelocity = lastVelocityData[part]?.let { computeVelocity(currentVelocityData, it, deltaTime) } ?: ZERO_VELOCITY
// Smooth velocity before setting it
val newVelocity = smoothVelocity(currentVelocity, lastVelocity, deltaTime)
val newVelocity = smoothVelocity(currentVelocity, lastVelocities[part] ?: ZERO_VELOCITY, deltaTime, expectedTps)
mutableComputedSkeleton[part] = bone.copy(velocity = newVelocity)
this@VelocityComputedProcessor.lastVelocityData[part] = currentVelocityData
lastVelocityData[part] = currentVelocityData
lastVelocities[part] = newVelocity
}
}
@@ -46,6 +46,7 @@ data class BoneInput(
val bodyPart: BodyPart,
val headOffset: Vector3,
val offset: Vector3,
val expectedTps: UShort?,
val rotation: Quaternion,
val acceleration: Vector3,
val position: Vector3?,
@@ -109,6 +110,7 @@ val DEFAULT_BONE_INPUT = BoneInput(
bodyPart = BodyPart.NONE,
headOffset = Vector3.ZERO,
offset = Vector3.ZERO,
expectedTps = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
position = null,
@@ -170,13 +172,12 @@ fun buildBones(boneInputs: InputSkeleton, changedParts: Set<BodyPart> = headPart
}
sealed interface 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 SetBonePose(val bodyPart: BodyPart, val expectedTps: UShort, val rotation: Quaternion, val acceleration: Vector3, val position: Vector3?) : SkeletonActions
data class DisableBone(val bodyPart: BodyPart) : SkeletonActions
data class SetProportions(val lengths: Map<SkeletonBone, Float>) : SkeletonActions
data class PauseTracking(val pause: Boolean) : SkeletonActions
data class SetPausedBoneInputs(val pausedBoneInputs: InputSkeleton) : SkeletonActions
data class SetHeadPosition(val position: Vector3?) : SkeletonActions
data object ResetHeadPosition : SkeletonActions
data object ResetFloorLevel : SkeletonActions
data class RequestProcessorReset(val resetType: ResetType) : SkeletonActions
@@ -197,7 +198,7 @@ interface SkeletonFkProcessor {
fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float)
}
interface SkeletonComputedProcessor {
fun process(mutableComputedSkeleton: ComputedSkeleton)
fun process(mutableComputedSkeleton: ComputedSkeleton, inputSkeleton: InputSkeleton)
}
typealias IKTargets = BodyPartMap<Vector3>
interface SkeletonTargetProcessor {
@@ -251,7 +252,7 @@ class Skeleton(
ProportionsBehaviour(ctx.config.userConfig),
HeightLogBehaviour(),
LocalizerResetBehaviour(settings),
// YouSpinMeRightRoundBehaviour(inputHz = 50f),
// YouSpinMeRightRoundBehaviour(inputHz = 50),
ComputedSkeletonBehaviour(
hz = hz,
waiter = waiter,
@@ -5,19 +5,21 @@ import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) {
is SkeletonActions.SetBoneRotation -> {
is SkeletonActions.SetBonePose -> {
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.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.bodyPart] ?: return state
state.copy(boneInputs = state.boneInputs.mutateCopy { it[action.bodyPart] = bone.copy(position = action.position, isPositionActive = action.setActive) })
state.copy(
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
expectedTps = bone.expectedTps,
rotation = action.rotation,
isRotationActive = true,
acceleration = action.acceleration,
isAccelerationActive = true,
position = action.position,
isPositionActive = action.position != null,
)
},
)
}
is SkeletonActions.DisableBone -> {
@@ -25,6 +27,7 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
state.copy(
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
expectedTps = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
position = null,
@@ -51,11 +54,15 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
is SkeletonActions.SetPausedBoneInputs -> state.copy(pausedProcessedBoneInputs = action.pausedBoneInputs)
is SkeletonActions.SetHeadPosition -> {
val headBone = state.boneInputs[BodyPart.HEAD] ?: return state
state.copy(boneInputs = state.boneInputs.mutateCopy { it[BodyPart.HEAD] = headBone.copy(position = action.position) })
}
is SkeletonActions.ResetHeadPosition -> {
val boneInputs = state.boneInputs
val headBone = boneInputs[BodyPart.HEAD] ?: return state
val headBone = state.boneInputs[BodyPart.HEAD] ?: return state
if (headBone.isPositionActive) return state
state.copy(boneInputs = boneInputs.mutateCopy { it[BodyPart.HEAD] = headBone.copy(position = null) })
state.copy(boneInputs = state.boneInputs.mutateCopy { it[BodyPart.HEAD] = headBone.copy(position = null) })
}
is SkeletonActions.ResetFloorLevel -> {
@@ -43,21 +43,24 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
.onEach { trackerState ->
trackerState.bodyPart?.let { bodyPart ->
val pendingResets = trackerState.pendingSkeletonResets
val poseActions = listOfNotNull(
SkeletonActions.SetBoneRotation(bodyPart, trackerState.rotation),
SkeletonActions.SetBoneAcceleration(bodyPart, trackerState.acceleration),
if (trackerState.position != null) SkeletonActions.SetBonePosition(bodyPart, trackerState.position) else null,
val bonePoseActions = SkeletonActions.SetBonePose(
bodyPart,
trackerState.expectedTps ?: trackerState.tps,
trackerState.rotation,
trackerState.acceleration,
trackerState.position,
)
receiver.appContext.skeleton.context.dispatchAll(
if (pendingResets.isEmpty()) {
poseActions
} else {
poseActions + pendingResets.map { SkeletonActions.RequestProcessorReset(it) }
},
)
if (pendingResets.isNotEmpty()) {
// Send bone data + resets (if any, to prevent allocation)
if (pendingResets.isEmpty()) {
receiver.appContext.skeleton.context.dispatch(bonePoseActions)
} else {
receiver.appContext.skeleton.context.dispatchAll(
listOf(bonePoseActions) + pendingResets.map { SkeletonActions.RequestProcessorReset(it) },
)
receiver.context.dispatch(TrackerActions.ClearPendingSkeletonResets(pendingResets.size))
}
lastBodyPartSent = trackerState.bodyPart
}
}
@@ -80,6 +80,7 @@ data class TrackerState(
val position: Vector3?,
val imuTemp: Float?,
val accumulatedTicks: UShort,
val expectedTps: UShort?,
val tps: UShort,
val status: TrackerStatus,
val completedRestCalibration: Boolean?,
@@ -138,6 +139,7 @@ class Tracker(
hardwareId: String,
origin: DeviceOrigin,
driverName: String? = null,
expectedTps: UShort? = null,
appContext: AppContextProvider,
): Tracker {
val settings = appContext.config.settings
@@ -154,6 +156,7 @@ class Tracker(
bodyPart = bodyPart,
intendedBodyPart = intendedBodyPart,
stayAlignedData = DEFAULT_STATE.stayAlignedData.copy(enabled = settings.context.state.value.data.stayAlignedConfig.enabled),
expectedTps = expectedTps,
)
val trackerState = if (savedConfig != null) {
TrackerConfigBehaviour.restoreFromConfig(baseState, savedConfig, settings.context.state.value.data.resetsConfig.saveMountingReset)
@@ -212,6 +215,7 @@ class Tracker(
position = null,
imuTemp = null,
accumulatedTicks = 0u,
expectedTps = null,
tps = 0u,
status = TrackerStatus.DISCONNECTED,
completedRestCalibration = false,
@@ -308,6 +308,7 @@ class SensorInfoBehaviour : UDPConnectionBehaviour {
origin = DeviceOrigin.UDP,
scope = receiver.appContext.server.context.scope,
appContext = receiver.appContext,
expectedTps = 100u,
)
receiver.appContext.server.context.dispatch(VRServerActions.NewTracker(trackerId = trackerId, context = newTracker))
receiver.context.dispatch(