Latency aware filtering

This commit is contained in:
Erimel committed 2026-10-30 18:40:50 -04:00
1 parent 5202013cf5
commit 79d8d2f9ce
10 files changed
+80 -26

No files matched your search

@@ -116,8 +116,8 @@ data class SkeletonTogglesConfig(
// Used in SkeletonConfig
@Serializable
data class SkeletonRatiosConfig(
val smoothingStrength: Float = 0.1f,
val predictionStrength: Float = 0.3f,
val smoothingStrength: Float = 0.15f,
val predictionStrength: Float = 0.25f,
val spineCurvature: Float = 0.75f,
val imputeSpineFromUpperToLower: Float = DEFAULT_SPINE_UPPER_LOWER,
val interpolateUpperLegsTwistWithLowerLegs: Float = 0.85f,
@@ -73,7 +73,14 @@ class LocalizerResetBehaviour(val settings: Settings) : SkeletonBehaviour {
* randomPacketLoss and constantPacketLoss are from 0 to 1
* sendPosition is for the head data.
*/
class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f, val randomPacketLoss: Float = 0f, val constantPacketLoss: Float = 0f, val sendPosition: Boolean = false) : SkeletonBehaviour {
class YouSpinMeRightRoundBehaviour(
val inputHz: Int = 100,
val speed: Float = 1f,
val randomPacketLoss: Float = 0f,
val constantPacketLoss: Float = 0f,
val sendPosition: Boolean = false,
val timeAgo: Duration = Duration.ZERO,
) : SkeletonBehaviour {
override fun observe(receiver: Skeleton) {
receiver.context.scope.launch {
val interval = (millisecondsInSecond / inputHz.toFloat()).toLong().milliseconds
@@ -91,6 +98,7 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
SkeletonActions.SetBonePose(
BodyPart.LOWER_CHEST,
Vector3.ZERO,
timeSource.markNow() - timeAgo,
Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)),
Vector3.ZERO,
null,
@@ -100,6 +108,7 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
SkeletonActions.SetBonePose(
BodyPart.LEFT_LOWER_LEG,
Vector3.ZERO,
timeSource.markNow() - timeAgo,
Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)),
Vector3.ZERO,
null,
@@ -115,6 +124,7 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
SkeletonActions.SetBonePose(
BodyPart.HEAD,
Vector3.ZERO,
timeSource.markNow() - timeAgo,
Quaternion.IDENTITY,
Vector3.ZERO,
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
@@ -299,7 +309,7 @@ class ComputedSkeletonBehaviour(
// If 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.SetBonePose(BodyPart.HEAD, Vector3.ZERO, null, null, boneInput.position, false))
receiver.context.dispatch(SkeletonActions.SetBonePose(BodyPart.HEAD, Vector3.ZERO, null, null, null, boneInput.position, false))
}
}
// Inputs changed; re-run FK
@@ -21,14 +21,16 @@ import kotlin.time.Duration.Companion.seconds
// Upsampling
private val UPSAMPLING_EXTRAPOLATION_MAX_DURATION = 0.8.seconds
// Technically Prediction but always on
private const val UPSAMPLING_EXTRAPOLATION_LOG_BASE_MIN = 7.5f
private const val UPSAMPLING_EXTRAPOLATION_LOG_BASE_MAX = 3.5f
// Upsampling (technically Prediction but always on)
private const val UPSAMPLING_EXTRAPOLATION_LOG_BASE_MIN = 7f
private const val UPSAMPLING_EXTRAPOLATION_LOG_BASE_MAX = 3f
// Upsampling (technically Smoothing but always on)
private const val UPSAMPLING_TIME_CARRYOVER_MIN = 0.6f
private const val UPSAMPLING_TIME_CARRYOVER_MAX = 0.9f
// Smoothing
private const val SMOOTHING_TIME_CARRYOVER_MIN = 0.65f
private const val SMOOTHING_TIME_CARRYOVER_MAX = 0.9f
private const val SMOOTHING_MS_MAX = 20.0
private const val SMOOTHING_MS_MAX = 70.0
// Prediction
private const val PREDICTION_MS_MAX = 30.0
@@ -51,6 +53,7 @@ private data class BoneSamples(
val poseTime: ComparableTimeMark,
val timeBetweenSamples: Duration,
val timeBetweenRotations: Duration,
val poseDelay: Duration,
val predictedRotationDelta: Quaternion?,
val predictedRotation: Quaternion,
// Mutable since these get changed every skeleton frame even if no new pose is received
@@ -69,11 +72,10 @@ private fun computeTimeBetweenPoses(
poseTimeDelta: Duration,
timeLeftForLastPose: Duration?,
timeCarryover: Double,
smoothingTime: Duration,
): Duration {
// Use some of last pose's remaining time
val lastPoseCarryoverTime = timeLeftForLastPose?.let { it * timeCarryover } ?: Duration.ZERO
return (lastPoseCarryoverTime + poseTimeDelta).coerceAtLeast(Duration.ZERO) + smoothingTime
return (lastPoseCarryoverTime + poseTimeDelta).coerceAtLeast(Duration.ZERO)
}
private fun computePredictedRotationDelta(
@@ -91,16 +93,16 @@ private fun computePredictedRotationDelta(
}
private fun computeInterpolationRatio(
now: ComparableTimeMark,
poseTime: ComparableTimeMark,
timeSinceLastPose: Duration,
smoothedTimeBetweenPoses: Duration,
extrapolationLogBase: Double,
multiplier: Float = 1f,
): Float {
// Time between now and tracker data.
val timeSinceLastPose = (now - poseTime).coerceAtMost(smoothedTimeBetweenPoses + UPSAMPLING_EXTRAPOLATION_MAX_DURATION)
val clampedTimeSinceLastPose = timeSinceLastPose.coerceAtMost(smoothedTimeBetweenPoses + UPSAMPLING_EXTRAPOLATION_MAX_DURATION)
// Ratio of how close we should be to the next pose.
// 0 = we just got started, 1 = we should have the next one, >1 = we didn't get it yet; packet lost or late
val rawRatio = if (smoothedTimeBetweenPoses > Duration.ZERO) timeSinceLastPose / smoothedTimeBetweenPoses else 1.0
val rawRatio = (if (smoothedTimeBetweenPoses > Duration.ZERO) clampedTimeSinceLastPose / smoothedTimeBetweenPoses else 1.0) * multiplier
// In case the rawRatio is >1, we extrapolate using log to keep some smooth perceived movement.
val extrapolationAmount = log((rawRatio).coerceAtLeast(1.0), extrapolationLogBase)
// Resulting ratio to use for interpolation, including extrapolation if any.
@@ -129,16 +131,23 @@ private fun computeInterpolationRatio(
*
* ----- Prediction -----
* Prediction decides how far away the target rotation is using an average of past rotation deltas.
*
*
* This is human slop. - Erimel
*/
class FilteringInputProcessor(val settings: Settings) :
SkeletonInputProcessor,
ResettableSkeletonProcessor {
private val boneSamples: BodyPartMap<BoneSamples> = bodyPartMap()
var lastProcessTime = timeSource.markNow()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val now = timeSource.markNow()
val deltaTime = now - lastProcessTime
lastProcessTime = now
val skeletonRatios = settings.context.state.value.data.skeletonConfig.ratios
val timeCarryover = FastMath.remapClamped(skeletonRatios.smoothingStrength, 0f, 1f, SMOOTHING_TIME_CARRYOVER_MIN, SMOOTHING_TIME_CARRYOVER_MAX).toDouble()
val timeCarryover = FastMath.remapClamped(skeletonRatios.smoothingStrength, 0f, 1f, UPSAMPLING_TIME_CARRYOVER_MIN, UPSAMPLING_TIME_CARRYOVER_MAX).toDouble()
val extrapolationLogBase = FastMath.remapClamped(skeletonRatios.predictionStrength, 0f, 1f, UPSAMPLING_EXTRAPOLATION_LOG_BASE_MIN, UPSAMPLING_EXTRAPOLATION_LOG_BASE_MAX).toDouble()
val smoothingTime = (skeletonRatios.smoothingStrength * SMOOTHING_MS_MAX).milliseconds
val predictionTime = (skeletonRatios.predictionStrength * PREDICTION_MS_MAX).milliseconds
@@ -165,7 +174,9 @@ class FilteringInputProcessor(val settings: Settings) :
val poseTimeDelta = computePoseTimeDelta(samples?.poseTime, bone.poseTime)
// The time we'll take to interpolate to the new pose
val timeBetweenRotations = computeTimeBetweenPoses(poseTimeDelta, samples?.timeLeftForLastPose, timeCarryover, smoothingTime)
val timeBetweenSamples = computeTimeBetweenPoses(poseTimeDelta, samples?.timeLeftForLastPose, timeCarryover)
val timeBetweenRotations = timeBetweenSamples + smoothingTime
val poseDelay = now - bone.poseTime
// The predicted target rotation change
val predictedRotationDelta = if (predictionEnabled) {
@@ -183,19 +194,23 @@ class FilteringInputProcessor(val settings: Settings) :
val predictedRotation = predictedRotationDelta?.let { targetSample.rotation * it } ?: targetSample.rotation
// New samples
samples = BoneSamples(fromSample, targetSample, bone.poseTime, poseTimeDelta, timeBetweenRotations, predictedRotationDelta, predictedRotation, null, Duration.ZERO)
samples = BoneSamples(fromSample, targetSample, bone.poseTime, timeBetweenSamples, timeBetweenRotations, poseDelay, predictedRotationDelta, predictedRotation, null, Duration.ZERO)
}
// Filtering
if (samples.fromSample != null && samples.targetSample != null) {
val upsamplingRatio = computeInterpolationRatio(now, bone.poseTime, samples.timeBetweenSamples, extrapolationLogBase)
// Calculate the delay multiplier using the ratio math to prevent it being too big
val delayMultiplier = 1f + computeInterpolationRatio(samples.poseDelay, samples.timeBetweenSamples, extrapolationLogBase)
// Add deltaTime because else it'd be 0 on the frame we get a new pose
val timeSinceLastPose = now - (bone.poseTime + samples.poseDelay - deltaTime)
val upsamplingRatio = computeInterpolationRatio(timeSinceLastPose, samples.timeBetweenSamples, extrapolationLogBase, delayMultiplier)
// Rotation
val rotation = if (bone.isRotationActive) {
val smoothingRatio = if (smoothingEnabled) {
// Compute ratio with smoothing time.
// timeBetweenRotations has some carry over from previous poses
computeInterpolationRatio(now, bone.poseTime, samples.timeBetweenRotations + smoothingTime, extrapolationLogBase)
computeInterpolationRatio(timeSinceLastPose, samples.timeBetweenRotations + smoothingTime, extrapolationLogBase, delayMultiplier)
} else {
upsamplingRatio
}
@@ -225,8 +240,10 @@ class FilteringInputProcessor(val settings: Settings) :
// Update running sample so that we resume from where we left off if we get a new pose next frame
samples.runningSample = BoneSample.fromBone(newBone)
// Time left for this pose, using the ratio to account for non-linear extrapolation
samples.timeLeftForLastPose = samples.timeBetweenSamples - (samples.timeBetweenSamples * upsamplingRatio.toDouble())
val timeLeftRatio = computeInterpolationRatio(timeSinceLastPose, samples.timeBetweenSamples, extrapolationLogBase).toDouble()
samples.timeLeftForLastPose = samples.timeBetweenSamples - (samples.timeBetweenSamples * timeLeftRatio)
}
// Save updated samples
@@ -236,5 +253,6 @@ class FilteringInputProcessor(val settings: Settings) :
override fun reset(resetType: ResetType) {
boneSamples.clear()
lastProcessTime = timeSource.markNow()
}
}
@@ -32,6 +32,8 @@ import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.SkeletonBone
import kotlin.time.ComparableTimeMark
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
data class Velocity(
/** In meters/s */
@@ -181,6 +183,7 @@ sealed interface SkeletonActions {
data class SetBonePose(
val bodyPart: BodyPart,
val boneOffset: Vector3?,
val poseTime: ComparableTimeMark?,
val rotation: Quaternion?,
val acceleration: Vector3?,
val position: Vector3?,
@@ -266,7 +269,7 @@ class Skeleton(
ProportionsBehaviour(ctx.config.userConfig),
HeightLogBehaviour(),
LocalizerResetBehaviour(settings),
// YouSpinMeRightRoundBehaviour(inputHz = 100, speed = 1f, randomPacketLoss = 0.9f, constantPacketLoss = 0f, sendPosition = false),
// YouSpinMeRightRoundBehaviour(inputHz = 100, speed = 1f, randomPacketLoss = 0f, constantPacketLoss = 0f, sendPosition = false, 10.milliseconds),
ComputedSkeletonBehaviour(
hz = hz,
waiter = waiter,
@@ -4,6 +4,7 @@ import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import kotlin.time.Duration.Companion.milliseconds
fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) {
is SkeletonActions.SetBonePose -> {
@@ -12,7 +13,7 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = action.boneOffset ?: bone.boneOffset,
poseTime = timeSource.markNow(),
poseTime = action.poseTime ?: bone.poseTime,
rotation = action.rotation ?: bone.rotation,
acceleration = action.acceleration ?: bone.acceleration,
position = action.position ?: bone.position,
@@ -24,6 +24,8 @@ import solarxr_protocol.driver_protocol.UpdateTrackerBattery
import solarxr_protocol.driver_protocol.UpdateTrackerPosition
import solarxr_protocol.driver_protocol.UpdateTrackerStatus
import kotlin.time.ComparableTimeMark
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.to
// These are all only defaults and the user can edit any and they will save.
@@ -210,6 +212,7 @@ class DriverIncomingTrackersBehaviour(
rotation = event.rotation?.toQuaternion()?.times(rotationOffset),
acceleration = acceleration,
position = event.position?.toVector3(),
poseTime = timeSource.markNow() - 5.milliseconds, // TODO can we get this from driver?
),
)
}.launchIn(receiver.context.scope)
@@ -23,6 +23,13 @@ class TrackerRotationRefreshBehaviour : TrackerBehaviour {
}
companion object {
fun getRotationRefreshAction(trackerState: TrackerState) = TrackerActions.SetRotation(trackerState.rawRotation, trackerState.rawAcceleration, trackerState.rawMagnetometer, trackerState.position, false)
fun getRotationRefreshAction(trackerState: TrackerState) = TrackerActions.SetRotation(
trackerState.rawRotation,
trackerState.rawAcceleration,
trackerState.rawMagnetometer,
trackerState.position,
_root_ide_package_.dev.slimevr.util.timeSource.markNow(),
false,
)
}
}
@@ -4,7 +4,9 @@ import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.tracker.TrackerState
import dev.slimevr.util.isActive
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -13,7 +15,10 @@ import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
import kotlin.time.ComparableTimeMark
import kotlin.time.Duration.Companion.milliseconds
class TrackerToSkeletonBehaviour : TrackerBehaviour {
var lastBodyPartSent: BodyPart? = null
@@ -47,6 +52,7 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
val bonePoseActions = SkeletonActions.SetBonePose(
bodyPart,
trackerState.boneOffsets[bodyPart],
trackerState.lastPoseTime,
trackerState.rotation,
trackerState.acceleration,
trackerState.position,
@@ -18,6 +18,7 @@ import dev.slimevr.tracker.behaviours.TrackerToSkeletonBehaviour
import dev.slimevr.tracker.behaviours.TrackerTpsBehaviour
import dev.slimevr.tracker.behaviours.TrackerYawResetSmoothingBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
@@ -29,6 +30,7 @@ import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
import solarxr_protocol.datatypes.hardware_info.TrackerDataType
import solarxr_protocol.rpc.ResetType
import kotlin.time.ComparableTimeMark
import kotlin.time.Duration
// A tracker is initialized as ROTATING to prevent TapDetection and Stay Aligned from running immediately.
@@ -81,6 +83,7 @@ data class TrackerState(
val imuTemp: Float?,
val accumulatedTicks: UShort,
val tps: UShort,
val lastPoseTime: ComparableTimeMark,
val status: TrackerStatus,
val completedRestCalibration: Boolean?,
val magStatus: MagnetometerStatus,
@@ -109,7 +112,7 @@ sealed interface TrackerActions {
data class SetMagStatus(val status: MagnetometerStatus) : TrackerActions
data class SetStatus(val status: TrackerStatus) : TrackerActions
data class SetDriverName(val driverName: String?) : TrackerActions
data class SetRotation(val rotation: Quaternion? = null, val acceleration: Vector3? = null, val magnetometer: Vector3? = null, val position: Vector3? = null, val increaseTps: Boolean = true) : TrackerActions
data class SetRotation(val rotation: Quaternion? = null, val acceleration: Vector3? = null, val magnetometer: Vector3? = null, val position: Vector3? = null, val poseTime: ComparableTimeMark = timeSource.markNow(), val increaseTps: Boolean = true) : TrackerActions
data class SetMountingOrientation(val mountingOrientation: HeadingAlignment) : TrackerActions
data class FullReset(val referenceRotation: Quaternion?, val resetHmdAttitude: Boolean = false) : TrackerActions
data class YawReset(val referenceRotation: Quaternion?, val smoothTime: Duration = Duration.ZERO) : TrackerActions
@@ -224,6 +227,7 @@ class Tracker(
imuTemp = null,
accumulatedTicks = 0u,
tps = 0u,
lastPoseTime = timeSource.markNow(),
status = TrackerStatus.DISCONNECTED,
completedRestCalibration = null,
magStatus = MagnetometerStatus.NOT_SUPPORTED,
@@ -1,5 +1,6 @@
package dev.slimevr.tracker
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.rpc.ResetType
@@ -76,6 +77,7 @@ fun reduce(
position = position,
accumulatedTicks = accumulatedTicks,
rotationDirty = false,
lastPoseTime = action.poseTime,
lastReference = null,
)
}