From 0b235e66695e4fb672528fc007fcf5528c2ac2d0 Mon Sep 17 00:00:00 2001 From: loucass003 Date: Thu, 3 Sep 2026 06:42:09 +0200 Subject: [PATCH] Velocity optimisations --- .../java/dev/slimevr/skeleton/behaviours.kt | 5 ++ .../velocity.kt | 24 ++++----- .../main/java/dev/slimevr/skeleton/module.kt | 21 +++++--- .../dev/slimevr/solarxr/datafeed/datafeed.kt | 19 +++++-- .../java/dev/slimevr/solarxr/DataFeedTest.kt | 52 ++++++------------- 5 files changed, 61 insertions(+), 60 deletions(-) rename server/core/src/main/java/dev/slimevr/skeleton/{fkprocessors => computedprocessors}/velocity.kt (65%) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt index 674a711d1..a4efcd231 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt @@ -165,6 +165,7 @@ private class TickTimings(private val hz: Int, private val window: Duration, pri class ComputedSkeletonBehaviour( val hz: Int, val inputProcessors: List = emptyList(), + val computedProcessors: List = emptyList(), val fkProcessors: List = emptyList(), val targetProcessors: List = emptyList(), val waiter: PreciseWaiter @@ -243,6 +244,10 @@ class ComputedSkeletonBehaviour( // Run initial FK var fk = buildBones(boneInputs) + // These write into fk, not the inputs, so the rebuilds below carry their + // values forward + for (processor in computedProcessors) processor.process(fk, targetState.floorLevel) + // Run FK processors. They write into boneInputs, and beforeFk allows figuring out // which bones changed. val beforeFk = BodyPartMap(boneInputs) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/velocity.kt b/server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt similarity index 65% rename from server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/velocity.kt rename to server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt index bd02034f4..bc29bbc7c 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/velocity.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/computedprocessors/velocity.kt @@ -1,10 +1,9 @@ -package dev.slimevr.skeleton.fkprocessors +package dev.slimevr.skeleton.computedprocessors import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.ComputedSkeleton -import dev.slimevr.skeleton.InputSkeleton -import dev.slimevr.skeleton.SkeletonFkProcessor +import dev.slimevr.skeleton.SkeletonComputedProcessor import dev.slimevr.skeleton.Velocity import dev.slimevr.skeleton.bodyPartMap import dev.slimevr.skeleton.forEachBone @@ -12,7 +11,6 @@ import dev.slimevr.util.inFloatingSeconds import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 -import kotlin.time.ComparableTimeMark data class VelocityBoneData( val rotation: Quaternion, @@ -22,11 +20,10 @@ data class VelocityBoneData( fun computeVelocity( currentBone: BoneState, lastVelocityData: VelocityBoneData, - lastTime: ComparableTimeMark, + deltaTime: Float, ): Velocity { val deltaPosition = currentBone.tailPosition - lastVelocityData.tailPosition val deltaRotation = currentBone.rotation / lastVelocityData.rotation - val deltaTime = (timeSource.markNow() - lastTime).inFloatingSeconds return Velocity( linear = deltaPosition / deltaTime, angular = deltaRotation.toRotationVector() / deltaTime, @@ -36,20 +33,23 @@ fun computeVelocity( /** * Computes linear (m/s) and angular (rad/s) velocity for the bones. */ -class VelocityFkProcessor : SkeletonFkProcessor { +class VelocityComputedProcessor : SkeletonComputedProcessor { private val lastVelocityBoneData: BodyPartMap = bodyPartMap() private var lastProcessTime = timeSource.markNow() - override fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { - fk.forEachBone { part, bone -> + override fun process(mutableComputedSkeleton: ComputedSkeleton, floorLevel: Float) { + // 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 = lastVelocityBoneData[part] if (lastVelocityData != null) { - val velocity = computeVelocity(bone, lastVelocityData, lastProcessTime) - mutableInputSkeleton[part] = mutableInputSkeleton[part]?.copy(velocity = velocity) + mutableComputedSkeleton[part] = bone.copy(velocity = computeVelocity(bone, lastVelocityData, deltaTime)) } lastVelocityBoneData[part] = VelocityBoneData(bone.rotation, bone.tailPosition) } - lastProcessTime = timeSource.markNow() } } 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 624f5b340..48e7094e5 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/module.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/module.kt @@ -4,9 +4,9 @@ import dev.slimevr.Phase1ContextProvider import dev.slimevr.config.Settings import dev.slimevr.context.Behaviour import dev.slimevr.context.Context +import dev.slimevr.skeleton.computedprocessors.VelocityComputedProcessor import dev.slimevr.skeleton.fkprocessors.FootPlantFkProcessor import dev.slimevr.skeleton.fkprocessors.ToeSnapFkProcessor -import dev.slimevr.skeleton.fkprocessors.VelocityFkProcessor import dev.slimevr.skeleton.inputprocessors.BoneActiveLinkInputProcessor import dev.slimevr.skeleton.inputprocessors.BoneDirectLinkInputProcessor import dev.slimevr.skeleton.inputprocessors.BonePredictionInputProcessor @@ -33,6 +33,8 @@ data class Velocity( val angular: Vector3, ) +val ZERO_VELOCITY = Velocity(Vector3.NULL, Vector3.NULL) + /** Pre-FK */ data class BoneInput( val bodyPart: BodyPart, @@ -43,7 +45,6 @@ data class BoneInput( val isRotationActive: Boolean, val isAccelerationActive: Boolean, val isPositionActive: Boolean, - val velocity: Velocity, ) /** Post-FK */ @@ -96,7 +97,6 @@ val DEFAULT_BONE_INPUT = BoneInput( isRotationActive = false, isAccelerationActive = false, isPositionActive = false, - velocity = Velocity(Vector3.NULL, Vector3.NULL), ) val DEFAULT_SKELETON_STATE = SkeletonState( @@ -112,7 +112,7 @@ val DEFAULT_SKELETON_STATE = SkeletonState( pausedProcessedBoneInputs = null, ) -fun buildBone(bone: BoneInput, parentBone: BoneState?): BoneState { +fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO_VELOCITY): BoneState { // Raw position of the bone input is used for BodyPart.HEAD since it has no parent val headPosition = parentBone?.tailPosition ?: bone.position ?: Vector3.NULL return BoneState( @@ -123,7 +123,7 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?): BoneState { acceleration = bone.acceleration, headPosition = headPosition, tailPosition = headPosition + bone.rotation.sandwich(bone.offset), - velocity = bone.velocity, + velocity = velocity, ) } @@ -138,7 +138,9 @@ fun buildBones(boneInputs: InputSkeleton, changedParts: Set = headPart iterateBodyPartHierarchy(parentOf(bodyPart) ?: bodyPart, bodyPart != BodyPart.HEAD).forEach { (parentPart, childPart) -> val rawBone = boneInputs[childPart] ?: return@forEach val parentBone = parentPart?.let { result[it] } - result[childPart] = buildBone(rawBone, parentBone) + // Velocity is written onto the computed bones, not the inputs, so a rebuilt bone + // keeps what the last pass measured + result[childPart] = buildBone(rawBone, parentBone, result[childPart]?.velocity ?: ZERO_VELOCITY) } } } @@ -164,6 +166,9 @@ interface SkeletonInputProcessor { interface SkeletonFkProcessor { fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) } +interface SkeletonComputedProcessor { + fun process(mutableComputedSkeleton: ComputedSkeleton, floorLevel: Float) +} typealias IKTargets = BodyPartMap interface SkeletonTargetProcessor { fun process(mutableIkTargets: IKTargets, fk: ComputedSkeleton, floorLevel: Float) @@ -203,8 +208,10 @@ class Skeleton( BoneDirectLinkInputProcessor(), FingerImputeInputProcessor(), ), + computedProcessors = listOf( + VelocityComputedProcessor(), + ), fkProcessors = listOf( - VelocityFkProcessor(), // LocalizerFkProcessor(settings), FootPlantFkProcessor(settings), ToeSnapFkProcessor(settings), diff --git a/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt b/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt index da85f17d3..cee1e6de1 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/datafeed/datafeed.kt @@ -15,6 +15,8 @@ import dev.slimevr.solarxr.createBone import dev.slimevr.tracker.Motion import dev.slimevr.tracker.TrackerState import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import solarxr_protocol.data_feed.DataFeedConfig import solarxr_protocol.data_feed.DataFeedMessageHeader @@ -38,6 +40,7 @@ import solarxr_protocol.datatypes.hardware_info.HardwareStatus import solarxr_protocol.datatypes.hardware_info.ImuType import solarxr_protocol.datatypes.math.Quat import solarxr_protocol.datatypes.math.Vec3f +import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.TimeSource @@ -209,10 +212,7 @@ class DataFeedInitBehaviour( val interval = config.minimumTimeSinceLast.toLong().milliseconds var nextSend = timeSource.markNow() - skeleton.computed.collect { - val now = timeSource.markNow() - if (now < nextSend) return@collect - + while (isActive) { try { receiver.sendDataFeed( createDatafeedFrame( @@ -228,8 +228,17 @@ class DataFeedInitBehaviour( AppLogger.solarxr.error(e, "Error sending data feed") } + // Sleeping to an absolute deadline takes the send's own duration out of the + // gap instead of adding it on top nextSend += interval - if (nextSend < now) nextSend = now + interval + val remaining = -nextSend.elapsedNow() + if (remaining > Duration.ZERO) { + delay(remaining) + } else { + // A send that outran the interval gives up the slots it missed rather + // than firing back to back to catch up + nextSend = timeSource.markNow() + } } } } diff --git a/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt b/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt index c8cd60e7a..033c30222 100644 --- a/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt +++ b/server/core/src/test/java/dev/slimevr/solarxr/DataFeedTest.kt @@ -9,7 +9,6 @@ import dev.slimevr.buildTestSkeleton import dev.slimevr.buildTestUserConfig import dev.slimevr.buildTestVrServer import dev.slimevr.context.Context -import dev.slimevr.skeleton.Skeleton import dev.slimevr.solarxr.datafeed.DataFeedInitBehaviour import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope @@ -22,13 +21,9 @@ import solarxr_protocol.data_feed.PollDataFeed import solarxr_protocol.data_feed.StartDataFeed import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds - -private class TestConn(val bridge: SolarXRBridge, val skeleton: Skeleton) @OptIn(ExperimentalCoroutinesApi::class) -private fun TestScope.testConn(onSend: suspend (ByteArray) -> Unit): TestConn { +private fun TestScope.testConn(onSend: suspend (ByteArray) -> Unit): SolarXRBridge { val server = buildTestVrServer(backgroundScope) val skeleton = buildTestSkeleton(backgroundScope) val settings = buildTestSettings(backgroundScope) @@ -61,26 +56,11 @@ private fun TestScope.testConn(onSend: suspend (ByteArray) -> Unit): TestConn { // launchIn registers the handler synchronously, but the dispatcher's own drain loop still has to // start before anything emitted here can reach it. runCurrent() - return TestConn(bridge, skeleton) + return bridge } private fun config(intervalMs: Int) = DataFeedConfig(minimumTimeSinceLast = intervalMs.toUShort()) -/** Drives [Skeleton.computed] the way the 500Hz loop does, so the feed's gate has a clock to ride */ -@OptIn(ExperimentalCoroutinesApi::class) -private fun TestScope.tickSkeleton(conn: TestConn, duration: Duration, tick: Duration = 2.milliseconds) { - // Let a freshly started feed subscribe and take the replayed frame before the clock moves - runCurrent() - val frame = conn.skeleton.currentComputed - var elapsed = Duration.ZERO - while (elapsed < duration) { - advanceTimeBy(tick) - conn.skeleton.computed.tryEmit(frame) - runCurrent() - elapsed += tick - } -} - @OptIn(ExperimentalCoroutinesApi::class) class DataFeedTest { @@ -89,10 +69,10 @@ class DataFeedTest { var sendCount = 0 val conn = testConn { sendCount++ } - conn.bridge.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) + conn.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) // fires at t=0, t=100, t=200 - tickSkeleton(conn, 250.milliseconds) + advanceTimeBy(250) assertEquals(3, sendCount) } @@ -101,11 +81,11 @@ class DataFeedTest { var sendCount = 0 val conn = testConn { sendCount++ } - conn.bridge.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100), config(200)))) + conn.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100), config(200)))) // 100ms feed: t=0, t=100, t=200 -> 3 sends // 200ms feed: t=0, t=200 -> 2 sends - tickSkeleton(conn, 250.milliseconds) + advanceTimeBy(250) assertEquals(5, sendCount) } @@ -114,9 +94,9 @@ class DataFeedTest { var sendCount = 0 val conn = testConn { sendCount++ } - conn.bridge.dataFeedDispatcher.emit(PollDataFeed(config = config(100))) + conn.dataFeedDispatcher.emit(PollDataFeed(config = config(100))) - tickSkeleton(conn, 500.milliseconds) + advanceTimeBy(500) assertEquals(1, sendCount) } @@ -125,14 +105,14 @@ class DataFeedTest { var sendCount = 0 val conn = testConn { sendCount++ } - conn.bridge.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) - tickSkeleton(conn, 250.milliseconds) + conn.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) + advanceTimeBy(250) assertEquals(3, sendCount) - conn.bridge.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) + conn.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) sendCount = 0 - tickSkeleton(conn, 250.milliseconds) + advanceTimeBy(250) assertEquals(3, sendCount) } @@ -141,14 +121,14 @@ class DataFeedTest { var sendCount = 0 val conn = testConn { sendCount++ } - conn.bridge.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) - tickSkeleton(conn, 250.milliseconds) + conn.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = listOf(config(100)))) + advanceTimeBy(250) assertEquals(3, sendCount) - conn.bridge.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = emptyList())) + conn.dataFeedDispatcher.emit(StartDataFeed(dataFeeds = emptyList())) sendCount = 0 - tickSkeleton(conn, 500.milliseconds) + advanceTimeBy(500) assertEquals(0, sendCount) }