mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-30 13:52:47 -08:00
use cool TimeSource instead of System.nanoTime
This commit is contained in:
1 parent
484a65c1b2
commit
5d7cd5dfaf
14 files changed
+102
-70
No files matched your search
@@ -5,14 +5,15 @@ import dev.slimevr.device.Device
|
||||
import dev.slimevr.device.DeviceActions
|
||||
import dev.slimevr.device.DeviceOrigin
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.timeSource
|
||||
import dev.slimevr.tracker.Tracker
|
||||
import dev.slimevr.tracker.TrackerActions
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.launch
|
||||
import solarxr_protocol.datatypes.TrackerStatus
|
||||
import kotlin.time.TimeSource
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class HIDRegistrationBehaviour : HIDReceiverBehaviour {
|
||||
override fun reduce(state: HIDReceiverState, action: HIDReceiverActions) = when (action) {
|
||||
@@ -173,14 +174,14 @@ class HIDBatteryBehaviour : HIDReceiverBehaviour {
|
||||
}
|
||||
}
|
||||
|
||||
private const val HID_TIMEOUT_MS = 2_000L
|
||||
private val hidTimeout = 2.seconds
|
||||
|
||||
class HIDSleepBehaviour : HIDReceiverBehaviour {
|
||||
override fun observe(receiver: HIDReceiver) {
|
||||
val startedAt = TimeSource.Monotonic.markNow()
|
||||
val startedAt = timeSource.markNow()
|
||||
val sleepJobs = mutableMapOf<Int, Job>()
|
||||
val idleJobs = mutableMapOf<Int, Job>()
|
||||
val lastSeen = mutableMapOf<Int, Long>()
|
||||
val lastSeen = mutableMapOf<Int, Duration>()
|
||||
|
||||
fun scheduleSleep(hidId: Int, timeoutMs: Int) {
|
||||
if (timeoutMs == 0) return
|
||||
@@ -196,13 +197,13 @@ class HIDSleepBehaviour : HIDReceiverBehaviour {
|
||||
}
|
||||
|
||||
fun armIdleTimeout(hidId: Int) {
|
||||
lastSeen[hidId] = startedAt.elapsedNow().inWholeMilliseconds
|
||||
lastSeen[hidId] = startedAt.elapsedNow()
|
||||
if (idleJobs[hidId]?.isActive == true) return
|
||||
idleJobs[hidId] = receiver.context.scope.launch {
|
||||
var remaining = HID_TIMEOUT_MS
|
||||
while (remaining > 0) {
|
||||
var remaining = hidTimeout
|
||||
while (remaining > Duration.ZERO) {
|
||||
delay(remaining)
|
||||
remaining = (lastSeen[hidId] ?: 0L) + HID_TIMEOUT_MS - startedAt.elapsedNow().inWholeMilliseconds
|
||||
remaining = (lastSeen[hidId] ?: Duration.ZERO) + hidTimeout - startedAt.elapsedNow()
|
||||
}
|
||||
receiver.getTracker(hidId)?.context?.dispatch(TrackerActions.SetStatus(TrackerStatus.TIMED_OUT))
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package dev.slimevr.resets
|
||||
|
||||
import dev.slimevr.timeSource
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.distinctUntilChangedBy
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.mapLatest
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class ResetsBasicBehaviour : ResetsBehaviour {
|
||||
override fun reduce(state: ResetsState, action: ResetsActions) = when (action) {
|
||||
@@ -20,7 +22,7 @@ class ResetsBasicBehaviour : ResetsBehaviour {
|
||||
// Whenever a reset is finished
|
||||
is ResetsActions.EndReset -> {
|
||||
if (action.resetType == ResetType.FULL) {
|
||||
state.copy(canDoYawReset = true, canDoMountingReset = true, lastFullResetTime = System.nanoTime())
|
||||
state.copy(canDoYawReset = true, canDoMountingReset = true, lastFullResetTime = timeSource.markNow())
|
||||
} else {
|
||||
state.copy()
|
||||
}
|
||||
@@ -29,18 +31,16 @@ class ResetsBasicBehaviour : ResetsBehaviour {
|
||||
}
|
||||
|
||||
class ResetsMountingTimeoutBehaviour : ResetsBehaviour {
|
||||
val mountingResetTimeout = 120.seconds
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override fun observe(receiver: ResetsManager) {
|
||||
receiver.context.state
|
||||
.distinctUntilChangedBy { it.lastFullResetTime }
|
||||
.mapLatest {
|
||||
delay(MOUNTING_RESET_TIMEOUT)
|
||||
delay(mountingResetTimeout)
|
||||
receiver.context.dispatch(ResetsActions.ClearResets(listOf(ResetType.MOUNTING)))
|
||||
}
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MOUNTING_RESET_TIMEOUT = 120 * 1000L // 120 seconds
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,7 @@ import dev.slimevr.config.SettingsActions
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.tracker.Tracker
|
||||
import dev.slimevr.tracker.TrackerActions
|
||||
import io.github.axisangles.ktmath.EulerAngles
|
||||
import io.github.axisangles.ktmath.EulerOrder
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -28,11 +25,12 @@ import solarxr_protocol.rpc.ResetStatus
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import kotlin.collections.contains
|
||||
import kotlin.collections.listOf
|
||||
import kotlin.time.TimeMark
|
||||
|
||||
data class ResetsState(
|
||||
val canDoYawReset: Boolean,
|
||||
val canDoMountingReset: Boolean,
|
||||
val lastFullResetTime: Long,
|
||||
val lastFullResetTime: TimeMark?,
|
||||
)
|
||||
|
||||
sealed interface ResetsActions {
|
||||
@@ -166,7 +164,7 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin
|
||||
initialState = ResetsState(
|
||||
canDoYawReset = false,
|
||||
canDoMountingReset = false,
|
||||
lastFullResetTime = 0,
|
||||
lastFullResetTime = null,
|
||||
),
|
||||
scope = scope,
|
||||
behaviours = listOf(ResetsBasicBehaviour(), ResetsMountingTimeoutBehaviour()),
|
||||
|
||||
@@ -2,6 +2,7 @@ package dev.slimevr.skeleton
|
||||
|
||||
import dev.slimevr.config.UserConfig
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import io.ktor.utils.io.CancellationException
|
||||
@@ -15,6 +16,7 @@ import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.time.Duration.Companion.nanoseconds
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class BoneTransformBehaviour : SkeletonBehaviour {
|
||||
override fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) {
|
||||
@@ -78,10 +80,10 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour
|
||||
override fun observe(receiver: Skeleton) {
|
||||
receiver.context.scope.launch {
|
||||
val intervalMs = (1000f / inputHz).toLong()
|
||||
val startTime = System.currentTimeMillis()
|
||||
val startTime = timeSource.markNow()
|
||||
while (true) {
|
||||
delay(intervalMs)
|
||||
val elapsed = (System.currentTimeMillis() - startTime) / 1000f
|
||||
val elapsed = startTime.elapsedNow().inWholeMilliseconds / 1000f
|
||||
val state = receiver.context.state.value
|
||||
|
||||
receiver.context.dispatch(
|
||||
@@ -120,17 +122,24 @@ class PauseTrackingBehaviour : SkeletonBehaviour {
|
||||
}
|
||||
|
||||
class ComputedSkeletonBehaviour(
|
||||
val hz: Long,
|
||||
val hz: Int,
|
||||
val processors: List<SkeletonProcessor> = emptyList(),
|
||||
) : SkeletonBehaviour {
|
||||
val logSpamWaitDuration = 10.seconds
|
||||
val minimumDelay = 1.nanoseconds
|
||||
|
||||
override fun observe(receiver: Skeleton) {
|
||||
val intervalNs = 1_000_000_000L / hz
|
||||
val intervalDuration = (1.0 / hz).seconds
|
||||
var nextLogTime = timeSource.markNow()
|
||||
|
||||
receiver.context.scope.launch {
|
||||
while (true) {
|
||||
try {
|
||||
val startTime = System.nanoTime()
|
||||
val startTime = timeSource.markNow()
|
||||
|
||||
val targetState = receiver.context.state.value
|
||||
|
||||
// Run processors
|
||||
val processed = processors
|
||||
.fold(targetState) { state, processor -> processor.process(state) } // TODO: Add a constrain processor (maybe not needed)
|
||||
|
||||
@@ -139,6 +148,7 @@ class ComputedSkeletonBehaviour(
|
||||
?.let { Vector3(it.rawPosition.x, it.rawPosition.y, it.rawPosition.z) }
|
||||
?: Vector3(0f, targetState.skeletonHeight, 0f)
|
||||
|
||||
// Run FK
|
||||
val fk = buildBones(processed, rootHead = rootHead)
|
||||
|
||||
// val targetProcessors = [FloorClip, FloorSkating, ToePlant, FootPlant]
|
||||
@@ -149,14 +159,22 @@ class ComputedSkeletonBehaviour(
|
||||
//
|
||||
// val ikOutput = solver.solve(fk, targets)
|
||||
|
||||
// receiver.computed.value = ikOutput
|
||||
|
||||
// FIXME bones should still follow the head when paused
|
||||
if (!targetState.paused) {
|
||||
receiver.computed.value = fk
|
||||
// receiver.computed.value = ikOutput
|
||||
}
|
||||
|
||||
// TODO log when we can't reach `hz`
|
||||
delay((intervalNs - (System.nanoTime() - startTime)).nanoseconds)
|
||||
val processTime = startTime.elapsedNow()
|
||||
val delayDuration = (intervalDuration - processTime).coerceAtLeast(minimumDelay)
|
||||
|
||||
// Warn if the process took too long to reach the target hz.
|
||||
if (delayDuration <= minimumDelay && nextLogTime.hasPassedNow()) {
|
||||
AppLogger.skeleton.warn("Can't reach target hz ($hz), process time = $processTime")
|
||||
nextLogTime = timeSource.markNow() + logSpamWaitDuration
|
||||
}
|
||||
|
||||
delay(delayDuration)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -127,7 +127,7 @@ class Skeleton(
|
||||
|
||||
companion object {
|
||||
fun create(scope: CoroutineScope, ctx: Phase1ContextProvider): Skeleton {
|
||||
val skeletonRefreshRate = 300L
|
||||
val skeletonRefreshRate = 300
|
||||
val behaviours = listOf(
|
||||
PauseTrackingBehaviour(),
|
||||
BoneTransformBehaviour(),
|
||||
|
||||
@@ -13,7 +13,9 @@ import solarxr_protocol.rpc.FilteringType
|
||||
/**
|
||||
* Running average of bones to smooth them out.
|
||||
*/
|
||||
class BoneSmoothingProcessor(val settings: Settings, val skeletonRefreshRate: Long) : SkeletonProcessor {
|
||||
// TODO checking skeletonRefreshRate is not good enough
|
||||
// since we're never gonna get that in practice. Need something more robust.
|
||||
class BoneSmoothingProcessor(val settings: Settings, val skeletonRefreshRate: Int) : SkeletonProcessor {
|
||||
private var smoothedRotations: BodyPartMap<Quaternion> = bodyPartMap()
|
||||
private var smoothedLengths: BodyPartMap<Vector3> = bodyPartMap()
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package dev.slimevr.skeleton
|
||||
|
||||
import dev.slimevr.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.ComparableTimeMark
|
||||
import kotlin.time.DurationUnit
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
// TODO We should probably just have globally available velocity on the whole skeleton,
|
||||
// we could do that as a processing step
|
||||
@@ -87,7 +87,7 @@ class SkatingCorrectionProcessor : SkeletonProcessor {
|
||||
var comState: COMState? = null
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
val curTime = TimeSource.Monotonic.markNow()
|
||||
val curTime = timeSource.markNow()
|
||||
|
||||
val lastComState = comState
|
||||
val com = centerOfMass(curPositions)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.slimevr.tapdetection
|
||||
|
||||
import dev.slimevr.config.TapDetectionConfig
|
||||
import dev.slimevr.timeSource
|
||||
import dev.slimevr.tracker.Tracker
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
@@ -17,17 +18,18 @@ import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.datatypes.TrackerStatus
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import solarxr_protocol.rpc.TapDetectionSetupNotification
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeMark
|
||||
|
||||
class TapDetectionBasicBehaviour : TapDetectionBehaviour {
|
||||
|
||||
data class TrackerTapDetectionState(
|
||||
var trackerId: Int,
|
||||
var numberTrackersOverThreshold: Int = 1,
|
||||
var resetType: ResetType? = null,
|
||||
var tapsNeeded: Int = 2,
|
||||
var actionDelay: Float = 0f,
|
||||
val accelList: ArrayDeque<Pair<Float, Long>> = ArrayDeque(),
|
||||
val tapTimestamps: ArrayDeque<Long> = ArrayDeque(),
|
||||
val accelList: ArrayDeque<Pair<Float, TimeMark>> = ArrayDeque(),
|
||||
val tapTimestamps: ArrayDeque<TimeMark> = ArrayDeque(),
|
||||
var waitForLowAccel: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -92,7 +94,7 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
|
||||
.distinctUntilChanged()
|
||||
.onEach {
|
||||
val tapTriggered = runTapDetection(
|
||||
System.nanoTime(),
|
||||
timeSource.markNow(),
|
||||
trackersOverThreshold,
|
||||
trackerTapDetectionState,
|
||||
it,
|
||||
@@ -168,21 +170,21 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
|
||||
|
||||
// Logic loop for tap detection
|
||||
fun runTapDetection(
|
||||
now: Long,
|
||||
now: TimeMark,
|
||||
trackersOverThreshold: MutableSet<Int>,
|
||||
trackerTapDetectionState: TrackerTapDetectionState,
|
||||
trackerAcceleration: Vector3,
|
||||
): Boolean {
|
||||
// Get the acceleration of the tracker and store it
|
||||
trackerTapDetectionState.accelList.add(trackerAcceleration.len() to now)
|
||||
|
||||
// Remove old stored accelerations (if they are too old)
|
||||
while (trackerTapDetectionState.accelList.isNotEmpty() && now - trackerTapDetectionState.accelList.first().second > ACCEL_WINDOW_NS) {
|
||||
while (trackerTapDetectionState.accelList.isNotEmpty() && (trackerTapDetectionState.accelList.first().second + accelWindow).hasPassedNow()) {
|
||||
trackerTapDetectionState.accelList.removeFirst()
|
||||
}
|
||||
|
||||
val max = trackerTapDetectionState.accelList.maxOfOrNull { it.first } ?: 0f
|
||||
val min = trackerTapDetectionState.accelList.minOfOrNull { it.first } ?: 0f
|
||||
// Get the acceleration of the tracker and store it
|
||||
trackerTapDetectionState.accelList.add(trackerAcceleration.len() to now)
|
||||
|
||||
val max = trackerTapDetectionState.accelList.maxOf { it.first }
|
||||
val min = trackerTapDetectionState.accelList.minOf { it.first }
|
||||
val accelDelta = max - min
|
||||
|
||||
// Is this tracker over threshold for false positive prevention?
|
||||
@@ -207,8 +209,8 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
|
||||
|
||||
if (trackerTapDetectionState.tapTimestamps.isNotEmpty()) {
|
||||
// Remove old stored taps (if they are too old)
|
||||
val totalTapWindowNs = (TAP_WINDOW_PER_TAP_NS * trackerTapDetectionState.tapTimestamps.size).toLong()
|
||||
while (trackerTapDetectionState.tapTimestamps.isNotEmpty() && now - trackerTapDetectionState.tapTimestamps.first() > totalTapWindowNs) {
|
||||
val totalTapWindow = tapWindowPerTap * trackerTapDetectionState.tapTimestamps.size
|
||||
while (trackerTapDetectionState.tapTimestamps.isNotEmpty() && (trackerTapDetectionState.tapTimestamps.first() + totalTapWindow).hasPassedNow()) {
|
||||
trackerTapDetectionState.tapTimestamps.removeFirst()
|
||||
}
|
||||
|
||||
@@ -231,11 +233,10 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NS_CONVERTER = 1.0e9f
|
||||
const val ACCEL_WINDOW_NS = 0.06f * NS_CONVERTER
|
||||
const val TAP_WINDOW_PER_TAP_NS = 0.3f * NS_CONVERTER
|
||||
const val NEEDED_ACCEL_DELTA = 6.0f
|
||||
const val ALLOWED_BODY_ACCEL = 2.5f
|
||||
const val ALLOWED_BODY_ACCEL_SQUARED = ALLOWED_BODY_ACCEL * ALLOWED_BODY_ACCEL
|
||||
val accelWindow = 0.06.seconds
|
||||
val tapWindowPerTap = 0.3.seconds
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.slimevr
|
||||
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
/**
|
||||
* We use Monotonic timesource, which is the most precise (`System.nanoTime()`)
|
||||
*/
|
||||
val timeSource = TimeSource.Monotonic
|
||||
@@ -8,6 +8,7 @@ import dev.slimevr.resets.LEFT_FINGER_PARTS
|
||||
import dev.slimevr.resets.RIGHT_ARM_PARTS
|
||||
import dev.slimevr.resets.RIGHT_FINGER_PARTS
|
||||
import dev.slimevr.skeleton.SkeletonActions
|
||||
import dev.slimevr.timeSource
|
||||
import io.github.axisangles.ktmath.EulerAngles
|
||||
import io.github.axisangles.ktmath.EulerOrder
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
@@ -31,7 +32,7 @@ import solarxr_protocol.rpc.ArmsResetMode
|
||||
import kotlin.concurrent.atomics.AtomicInt
|
||||
import kotlin.concurrent.atomics.ExperimentalAtomicApi
|
||||
import kotlin.concurrent.atomics.incrementAndFetch
|
||||
import kotlin.time.TimeSource
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class TrackerBasicBehaviour : TrackerBehaviour {
|
||||
override fun reduce(state: TrackerState, action: TrackerActions) = when (action) {
|
||||
@@ -229,14 +230,14 @@ class TrackerTPSBehaviour : TrackerBehaviour {
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.context.scope.launch {
|
||||
var mark = TimeSource.Monotonic.markNow()
|
||||
var mark = timeSource.markNow()
|
||||
while (isActive) {
|
||||
try {
|
||||
delay(1000)
|
||||
val elapsed = mark.elapsedNow()
|
||||
val tps = count.exchange(0) * 1000L / elapsed.inWholeMilliseconds
|
||||
receiver.context.dispatch(TrackerActions.Update { copy(tps = tps.toUShort()) })
|
||||
mark = TimeSource.Monotonic.markNow()
|
||||
mark = timeSource.markNow()
|
||||
} catch (e: Exception) {
|
||||
AppLogger.coroutines.error(e, "Error in TrackerTPSBehaviour")
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ class UdpServer(val context: UdpServerContext, private val addressResolver: (Ine
|
||||
}
|
||||
}
|
||||
if (took.inWholeMilliseconds > 2) {
|
||||
AppLogger.udp.warn("Packet processing took too long ${took.inWholeMilliseconds}")
|
||||
AppLogger.udp.warn("Packet processing took too long (${took.inWholeMilliseconds}ms)")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.udp.error(e, "Error processing UDP packet")
|
||||
|
||||
Reference in new issue
Block a user