Allocations optimisations

This commit is contained in:
loucass003 committed 2026-08-21 01:04:09 +02:00
1 parent 8f3cd8e3dd
commit 151a6e3021
7 files changed
+135 -30

No files matched your search

@@ -5,6 +5,7 @@ import dev.slimevr.device.Device
import dev.slimevr.device.DeviceActions
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.bodyPartMap
import dev.slimevr.skeleton.forEachBone
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerState
@@ -65,7 +66,7 @@ class DriverOutgoingTrackersBehaviour : DriverBridgeBehaviour {
trackerStateByBodyPart.putIfAbsent(bodyPart, trackerState)
}
computedSkeleton.forEach { (part, state) ->
computedSkeleton.forEachBone { part, state ->
if (enabledBodyParts.contains(part)) {
val closestTracker = bodyPartToNearest[part].orEmpty()
.firstNotNullOfOrNull { fallbackPart -> trackerStateByBodyPart[fallbackPart] }
@@ -83,14 +83,24 @@ inline fun BodyPart.findFirstParent(predicate: (BodyPart) -> Boolean): BodyPart?
return null
}
private suspend fun SequenceScope<Pair<BodyPart?, BodyPart>>.visitBodyPart(parentBone: BodyPart?, bone: BodyPart, onlyChildren: Boolean) {
if (!onlyChildren) {
yield(Pair(parentBone, bone))
private fun buildHierarchy(root: BodyPart, onlyChildren: Boolean): List<Pair<BodyPart?, BodyPart>> {
val result = mutableListOf<Pair<BodyPart?, BodyPart>>()
fun visit(parentBone: BodyPart?, bone: BodyPart, skipSelf: Boolean) {
if (!skipSelf) result += parentBone to bone
val children = BODY_PART_HIERARCHY_MAP[bone] ?: return
for (child in children) visit(bone, child, false)
}
val children = BODY_PART_HIERARCHY_MAP[bone] ?: return
for (child in children) visitBodyPart(bone, child, false)
visit(null, root, onlyChildren)
return result
}
fun iterateBodyPartHierarchy(root: BodyPart = BodyPart.HEAD, onlyChildren: Boolean = false) = sequence {
visitBodyPart(null, root, onlyChildren)
}
// The hierarchy is constant, so every traversal of it is too. Derived once for the same reason
// BODY_PART_PARENTS is: walking it lazily per call cost a continuation and a Pair per bone, and
// BoneYawFallbackProcessor asks for one per active bone per frame.
private val BODY_PART_HIERARCHIES: Array<List<Pair<BodyPart?, BodyPart>>> =
Array(ALL_BODY_PARTS.size * 2) { index -> buildHierarchy(ALL_BODY_PARTS[index / 2], index % 2 == 1) }
fun iterateBodyPartHierarchy(
root: BodyPart = BodyPart.HEAD,
onlyChildren: Boolean = false,
): List<Pair<BodyPart?, BodyPart>> = BODY_PART_HIERARCHIES[root.ordinal * 2 + if (onlyChildren) 1 else 0]
@@ -98,7 +98,7 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?, originPosition: Vector3 =
fun buildBones(
state: Map<BodyPart, BoneInput>,
rootHead: Vector3 = Vector3.NULL,
hierarchy: Sequence<Pair<BodyPart?, BodyPart>> = iterateBodyPartHierarchy(),
hierarchy: List<Pair<BodyPart?, BodyPart>> = iterateBodyPartHierarchy(),
): ComputedSkeleton {
val result = bodyPartMap<BoneState>()
hierarchy.forEach { (parentPart, childPart) ->
@@ -112,7 +112,7 @@ fun buildBones(
fun buildBones(
state: SkeletonState,
rootHead: Vector3 = Vector3.NULL,
hierarchy: Sequence<Pair<BodyPart?, BodyPart>> = iterateBodyPartHierarchy(),
hierarchy: List<Pair<BodyPart?, BodyPart>> = iterateBodyPartHierarchy(),
): ComputedSkeleton = buildBones(state.boneInputs, rootHead, hierarchy)
sealed interface SkeletonActions {
@@ -1,13 +1,12 @@
package dev.slimevr.skeleton.processors
import dev.slimevr.skeleton.BODY_PART_HIERARCHY_MAP
import dev.slimevr.skeleton.SkeletonProcessor
import dev.slimevr.skeleton.SkeletonState
import dev.slimevr.skeleton.forEachBone
import dev.slimevr.skeleton.iterateBodyPartHierarchy
import dev.slimevr.skeleton.mutate
import io.github.axisangles.ktmath.Vector3
import kotlin.collections.set
import kotlin.time.Duration
/**
* Handles replacing rotations of boneInputs that are not actively receiving data by
@@ -18,8 +17,8 @@ class BoneYawFallbackProcessor : SkeletonProcessor {
val boneInputs = state.boneInputs
val updatedFallbackBones = boneInputs.mutate { updated ->
for ((parentPart, parentBone) in boneInputs) {
if (!parentBone.isActive) continue // Parent needs to be active
boneInputs.forEachBone { parentPart, parentBone ->
if (!parentBone.isActive) return@forEachBone // Parent needs to be active
val children = iterateBodyPartHierarchy(parentPart, true)
for (childPart in children) {
@@ -2,22 +2,20 @@ package dev.slimevr.solarxr
import dev.slimevr.config.UserConfig
import dev.slimevr.config.UserConfigActions
import dev.slimevr.skeleton.ALL_BODY_PARTS
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.skeleton.computeAllDefaultProportionsByBone
import dev.slimevr.skeleton.computeDefaultProportionsByBone
import dev.slimevr.skeleton.configToBoneValues
import dev.slimevr.skeleton.height
import dev.slimevr.skeleton.toBoneValues
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.rpc.ChangeSkeletonProportionsRequest
import solarxr_protocol.rpc.ChangeUserHeightRequest
import solarxr_protocol.rpc.SkeletonBone
import solarxr_protocol.rpc.SkeletonPart
import solarxr_protocol.rpc.SkeletonProportionsRequest
import solarxr_protocol.rpc.SkeletonProportionsResetAllRequest
@@ -39,7 +37,7 @@ class SkeletonProportionsBehaviour(
override fun observe(receiver: SolarXRBridge) {
skeleton.context.state
.map { it.boneInputs }
.distinctUntilChangedBy { boneInputs -> boneInputs.entries.map { it.key to it.value.offset } }
.distinctUntilChanged { old, new -> ALL_BODY_PARTS.all { part -> old[part]?.offset == new[part]?.offset } }
.drop(1)
.onEach { boneInputs ->
val configResponse = buildConfigResponse(boneInputs)
@@ -35,6 +35,7 @@ import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
import solarxr_protocol.rpc.RoutingOutput
import solarxr_protocol.rpc.TrackingChecklistNeedCalibration
import solarxr_protocol.rpc.TrackingChecklistPublicNetworks
@@ -57,15 +58,52 @@ private inline fun <C, reified S> allContextStates(
combine(items.map { item -> stateOf(item) }) { states -> states.toList() }
}
private fun trackerStatesFlow(server: VRServer): Flow<List<TrackerState>> = allContextStates(server, { state -> state.trackers.values }) { tracker -> tracker.context.state }
/**
* Everything about a tracker the checklist reasons about, and nothing else.
*
* A tracker emits on every rotation update, hundreds of times a second, while the answers the
* checklist computes change a couple of times a minute. Projecting to this before the combine below
* is what separates the two: rotation does not appear here, so a rotation update projects to an equal
* value and [distinctUntilChanged] drops it before any check runs.
*
* The dependency is declared rather than remembered. A check that needs another field adds it here,
* and the compiler points at every place that has to change. nothing can silently stop updating
* because someone read a field the projection forgot to carry.
*/
data class ChecklistTracker(
val id: Int,
val origin: DeviceOrigin,
val status: TrackerStatus,
val bodyPart: BodyPart?,
val imuType: ImuType?,
val completedRestCalibration: Boolean?,
// Deliberately not the position itself: the checks only ask whether there is one, and carrying the
// value would put this back on the rotation update rate.
val hasPosition: Boolean,
)
internal fun checklistTracker(tracker: TrackerState) = ChecklistTracker(
id = tracker.id,
origin = tracker.origin,
status = tracker.status,
bodyPart = tracker.bodyPart,
imuType = tracker.imuType,
completedRestCalibration = tracker.completedRestCalibration,
hasPosition = tracker.position != null,
)
private fun trackerStatesFlow(server: VRServer): Flow<List<ChecklistTracker>> =
allContextStates(server, { state -> state.trackers.values }) { tracker ->
tracker.context.state.map { state -> checklistTracker(state) }.distinctUntilChanged()
}
private fun deviceStatesFlow(server: VRServer): Flow<List<DeviceState>> = allContextStates(server, { state -> state.devices.values }) { device -> device.context.state }
class HMDCheckBehaviour(private val server: VRServer) : TrackingChecklistBehaviourType {
private fun computeStep(trackers: List<TrackerState>): TrackingChecklistStep {
private fun computeStep(trackers: List<ChecklistTracker>): TrackingChecklistStep {
// FIXME: Most likely incomplete
val hasDriverHMD = trackers.any { tracker -> tracker.origin == DeviceOrigin.DRIVER }
val hmdTracker = trackers.firstOrNull { tracker -> tracker.origin == DeviceOrigin.DRIVER && tracker.position != null }
val hmdTracker = trackers.firstOrNull { tracker -> tracker.origin == DeviceOrigin.DRIVER && tracker.hasPosition }
val isAssigned = hmdTracker?.bodyPart == BodyPart.HEAD
return TrackingChecklistStep(
valid = isAssigned,
@@ -92,7 +130,7 @@ class HMDCheckBehaviour(private val server: VRServer) : TrackingChecklistBehavio
}
class TrackerRestCheckBehaviour(private val server: VRServer) : TrackingChecklistBehaviourType {
private fun computeStep(trackers: List<TrackerState>): TrackingChecklistStep {
private fun computeStep(trackers: List<ChecklistTracker>): TrackingChecklistStep {
val uncalibratedTrackers = trackers.filter { tracker ->
(tracker.origin == DeviceOrigin.UDP || tracker.origin == DeviceOrigin.HID) &&
(tracker.status == TrackerStatus.OK || tracker.status == TrackerStatus.SLEEPING) &&
@@ -101,7 +139,7 @@ class TrackerRestCheckBehaviour(private val server: VRServer) : TrackingChecklis
return TrackingChecklistStep(
valid = uncalibratedTrackers.isEmpty(),
enabled = trackers.isNotEmpty(),
extraData = if (!uncalibratedTrackers.isEmpty()) {
extraData = if (uncalibratedTrackers.isNotEmpty()) {
TrackingChecklistNeedCalibration(
trackersId = uncalibratedTrackers.map { tracker -> tracker.id.toUShort() },
)
@@ -121,7 +159,7 @@ class TrackerRestCheckBehaviour(private val server: VRServer) : TrackingChecklis
}
class TrackerErrorCheckBehaviour(private val server: VRServer) : TrackingChecklistBehaviourType {
private fun computeStep(trackers: List<TrackerState>): TrackingChecklistStep {
private fun computeStep(trackers: List<ChecklistTracker>): TrackingChecklistStep {
val errorTrackers = trackers
.filter { tracker -> tracker.status == TrackerStatus.ERROR && tracker.bodyPart != null }
.toSet()
@@ -154,7 +192,7 @@ class SteamVRHandsCheckBehaviour(
private val HAND_BONES = setOf(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND)
private fun computeStep(
trackers: List<TrackerState>,
trackers: List<ChecklistTracker>,
routes: Routes,
driverConnected: Boolean,
): TrackingChecklistStep {
@@ -242,14 +280,14 @@ class NetworkProfileCheckBehaviour(
}
}
private fun isImuAssigned(tracker: TrackerState): Boolean = (tracker.origin == DeviceOrigin.UDP || tracker.origin == DeviceOrigin.HID) &&
tracker.position == null &&
private fun isImuAssigned(tracker: ChecklistTracker): Boolean = (tracker.origin == DeviceOrigin.UDP || tracker.origin == DeviceOrigin.HID) &&
!tracker.hasPosition &&
tracker.imuType !== null &&
tracker.status != TrackerStatus.ERROR &&
tracker.bodyPart != null
private fun isConnectedAssignedImu(tracker: TrackerState): Boolean = (tracker.origin == DeviceOrigin.UDP || tracker.origin == DeviceOrigin.HID) &&
tracker.position == null &&
private fun isConnectedAssignedImu(tracker: ChecklistTracker): Boolean = (tracker.origin == DeviceOrigin.UDP || tracker.origin == DeviceOrigin.HID) &&
!tracker.hasPosition &&
tracker.imuType !== null &&
(tracker.status == TrackerStatus.OK || tracker.status == TrackerStatus.SLEEPING) &&
tracker.bodyPart != null