mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-24 02:51:20 -08:00
Cleanned up VMC / VRCOSC code + Status for VMC
This commit is contained in:
1 parent
02378c43b3
commit
3aa621ffc1
27 files changed
+1292
-559
No files matched your search
@@ -51,17 +51,22 @@ class OscReceiver(private val port: Int) {
|
||||
val s = socket()
|
||||
running = true
|
||||
while (running) {
|
||||
try {
|
||||
val packet = s.receive().packet
|
||||
val bundle = try {
|
||||
readBundle(packet)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
OscBundle(1, listOf(OscContent.Message(readMessage(packet))))
|
||||
}
|
||||
onBundle(bundle)
|
||||
} catch (_: Exception) {
|
||||
val packet = try {
|
||||
s.receive().packet
|
||||
} catch (e: Exception) {
|
||||
if (!running) break
|
||||
throw e
|
||||
}
|
||||
val bundle = try {
|
||||
readBundle(packet)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
try {
|
||||
OscBundle(1, listOf(OscContent.Message(readMessage(packet))))
|
||||
} catch (_: Exception) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onBundle(bundle)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,3 +47,12 @@ sealed interface OscContent {
|
||||
data class Message(val msg: OscMessage) : OscContent
|
||||
data class Bundle(val bundle: OscBundle) : OscContent
|
||||
}
|
||||
|
||||
fun forEachOscMessage(bundle: OscBundle, action: (OscMessage) -> Unit) {
|
||||
for (content in bundle.contents) {
|
||||
when (content) {
|
||||
is OscContent.Message -> action(content.msg)
|
||||
is OscContent.Bundle -> forEachOscMessage(content.bundle, action)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ class SolarXRBridge(
|
||||
add(ResetsBehaviour(appContext.config.settings))
|
||||
add(TapDetectionBehaviour(appContext.config.settings, appContext.tapDetectionManager))
|
||||
add(VrcOscBehaviour(appContext.config.settings, appContext.vrcOscManager))
|
||||
add(VmcBehaviour(appContext.config.settings))
|
||||
add(VmcBehaviour(appContext.config.settings, appContext.vmcManager))
|
||||
add(HeightCalibrationBehaviour(appContext.heightCalibrationManager))
|
||||
add(ProvisioningBehaviour(appContext.server, appContext.provisioningManager))
|
||||
add(BoneRoutingBehaviour(appContext))
|
||||
|
||||
@@ -2,18 +2,39 @@ package dev.slimevr.solarxr
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.config.SettingsActions
|
||||
import dev.slimevr.vmc.VMCManager
|
||||
import dev.slimevr.vmc.VMCStatus
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.sample
|
||||
import solarxr_protocol.rpc.ChangeVMCOSCSettingsRequest
|
||||
import solarxr_protocol.rpc.ChangeVRMSettingsRequest
|
||||
import solarxr_protocol.rpc.VMCOSCSettingsRequest
|
||||
import solarxr_protocol.rpc.VMCOSCSettingsResponse
|
||||
import solarxr_protocol.rpc.VMCOSCStatusChangeResponse
|
||||
import solarxr_protocol.rpc.VMCOSCStatusRequest
|
||||
import solarxr_protocol.rpc.VRMSettingsRequest
|
||||
import solarxr_protocol.rpc.VRMSettingsResponse
|
||||
|
||||
private const val STATUS_SAMPLE_MS = 300L
|
||||
|
||||
class VmcBehaviour(
|
||||
private val settings: Settings,
|
||||
private val vmcManager: VMCManager,
|
||||
) : SolarXRBridgeBehaviour {
|
||||
@OptIn(FlowPreview::class)
|
||||
override fun observe(receiver: SolarXRBridge) {
|
||||
|
||||
vmcManager.context.state
|
||||
.map { state -> state.status }
|
||||
.drop(1)
|
||||
.sample(STATUS_SAMPLE_MS)
|
||||
.onEach { status -> receiver.sendRpc(buildStatusResponse(status)) }
|
||||
.launchIn(receiver.context.scope)
|
||||
|
||||
// Send VMC config
|
||||
receiver.rpcDispatcher.on<VMCOSCSettingsRequest> {
|
||||
val config = settings.context.state.value.data.vmcConfig
|
||||
@@ -29,6 +50,10 @@ class VmcBehaviour(
|
||||
)
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.rpcDispatcher.on<VMCOSCStatusRequest> {
|
||||
receiver.sendRpc(buildStatusResponse(vmcManager.context.state.value.status))
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
// Send VRM json
|
||||
receiver.rpcDispatcher.on<VRMSettingsRequest> {
|
||||
val config = settings.context.state.value.data.vmcConfig
|
||||
@@ -68,4 +93,18 @@ class VmcBehaviour(
|
||||
)
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private fun buildStatusResponse(status: VMCStatus) = VMCOSCStatusChangeResponse(
|
||||
inputState = status.inputState,
|
||||
inputPort = status.inputPort?.toUShort(),
|
||||
inputError = status.inputError,
|
||||
lastReceivedInputMillis = status.lastReceivedInputMillis?.toULong(),
|
||||
outputState = status.outputState,
|
||||
outputError = status.outputError,
|
||||
targetAddress = status.targetAddress,
|
||||
targetPort = status.targetPort?.toUShort(),
|
||||
lastFrameSentMillis = status.lastFrameSentMillis?.toULong(),
|
||||
vrmState = status.vrmState,
|
||||
vrmError = status.vrmError,
|
||||
)
|
||||
}
|
||||
@@ -34,7 +34,7 @@ internal class VrcOscBehaviour(
|
||||
.map { state -> state.status }
|
||||
.drop(1)
|
||||
.sample(STATUS_SAMPLE_MS)
|
||||
.onEach { status -> receiver.sendRpc(buildStatusResponse(status, settings.context.state.value.data.vrcOscConfig.enabled)) }
|
||||
.onEach { status -> receiver.sendRpc(buildStatusResponse(status)) }
|
||||
.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.rpcDispatcher.on<VRCOSCSettingsRequest> {
|
||||
@@ -51,9 +51,7 @@ internal class VrcOscBehaviour(
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.rpcDispatcher.on<VRCOSCStatusRequest> {
|
||||
val state = vrcOscManager.context.state.value
|
||||
val config = settings.context.state.value.data.vrcOscConfig
|
||||
receiver.sendRpc(buildStatusResponse(state.status, config.enabled))
|
||||
receiver.sendRpc(buildStatusResponse(vrcOscManager.context.state.value.status))
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.rpcDispatcher.on<ChangeVRCOSCSettingsRequest> { req ->
|
||||
@@ -73,8 +71,7 @@ internal class VrcOscBehaviour(
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private fun buildStatusResponse(status: VRCOSCStatus, enabled: Boolean) = VRCOSCStatusChangeResponse(
|
||||
enabled = enabled,
|
||||
private fun buildStatusResponse(status: VRCOSCStatus) = VRCOSCStatusChangeResponse(
|
||||
inputState = status.inputState,
|
||||
inputPort = status.inputPort?.toUShort(),
|
||||
inputError = status.inputError,
|
||||
|
||||
@@ -41,3 +41,9 @@ fun installUncaughtExceptionReporting() {
|
||||
previous?.uncaughtException(thread, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
fun formatExceptionMessage(prefix: String, throwable: Throwable): String {
|
||||
val detail = throwable.message?.takeIf { it.isNotBlank() }
|
||||
?: throwable::class.simpleName.orEmpty()
|
||||
return if (detail.isBlank()) prefix else "$prefix: $detail"
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
package dev.slimevr.vmc
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.config.VMCConfig
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.osc.OscArg
|
||||
import dev.slimevr.osc.OscBundle
|
||||
import dev.slimevr.osc.OscContent
|
||||
import dev.slimevr.osc.OscMessage
|
||||
import dev.slimevr.osc.OscReceiver
|
||||
import dev.slimevr.osc.OscSender
|
||||
import dev.slimevr.routing.BoneRoutingManager
|
||||
import dev.slimevr.skeleton.BoneState
|
||||
import dev.slimevr.skeleton.Skeleton
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.RoutingOutput
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class VMCOutputBehaviour(
|
||||
private val skeleton: Skeleton,
|
||||
private val settings: Settings,
|
||||
private val boneRouting: BoneRoutingManager,
|
||||
) : VMCBehaviourType {
|
||||
private val logSpamWaitDuration = 1.seconds
|
||||
private val initTime = System.currentTimeMillis()
|
||||
|
||||
override fun observe(receiver: VMCManager) {
|
||||
var nextLogTime = timeSource.markNow()
|
||||
var sender: OscSender? = null
|
||||
var vrmGeometry: VrmGeometry? = null
|
||||
|
||||
settings.context.state
|
||||
.map { it.data.vmcConfig.vrmJson }
|
||||
.distinctUntilChanged()
|
||||
.onEach { vrmJson ->
|
||||
vrmGeometry = vrmJson?.takeIf { value -> value.isNotEmpty() }?.let { value ->
|
||||
try {
|
||||
buildVrmGeometry(VrmReader(value))
|
||||
} catch (e: Exception) {
|
||||
AppLogger.vmc.error("Failed to parse VRM JSON", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
settings.context.state
|
||||
.map { Triple(it.data.vmcConfig.enabled, it.data.vmcConfig.portOut, it.data.vmcConfig.address) }
|
||||
.distinctUntilChanged()
|
||||
.onEach { (enabled, port, addr) ->
|
||||
sender?.close()
|
||||
sender = null
|
||||
if (enabled) {
|
||||
sender = OscSender(addr, port)
|
||||
AppLogger.vmc.info("VMC output started: $addr:$port")
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
sender?.send(OscMessage("/VMC/Ext/Req", emptyList()))
|
||||
} catch (e: Exception) {
|
||||
AppLogger.vmc.error("Failed to send init Req", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
val routedBonesFlow = boneRouting.context.state
|
||||
.map { state -> state.routes.filterValues { RoutingOutput.VMC in it }.keys }
|
||||
.distinctUntilChanged()
|
||||
|
||||
combine(skeleton.computed, routedBonesFlow, ::Pair)
|
||||
.onEach { (computedSkeleton, routedBones) ->
|
||||
val s = sender ?: return@onEach
|
||||
val config = settings.context.state.value.data.vmcConfig
|
||||
val currentTime = System.currentTimeMillis()
|
||||
val vrm = vrmGeometry
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
s.send(buildBundle(computedSkeleton, config, currentTime, vrm, routedBones))
|
||||
} catch (e: Exception) {
|
||||
if (nextLogTime.hasPassedNow()) {
|
||||
AppLogger.vmc.error("Failed to send VMC frame", e)
|
||||
nextLogTime = timeSource.markNow() + logSpamWaitDuration
|
||||
}
|
||||
}
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private fun buildBundle(bones: Map<BodyPart, BoneState>, config: VMCConfig, currentTime: Long, vrm: VrmGeometry?, routedBones: Set<BodyPart>): OscBundle = OscBundle(1L, buildMessages(bones, config, currentTime, vrm, routedBones).map { msg -> OscContent.Message(msg) }.toList())
|
||||
|
||||
private fun transformMessage(address: String, name: String, pos: Vector3, rot: Quaternion): OscMessage = OscMessage(
|
||||
address,
|
||||
listOf(
|
||||
OscArg.String(name),
|
||||
OscArg.Float(pos.x),
|
||||
OscArg.Float(pos.y),
|
||||
OscArg.Float(-pos.z),
|
||||
OscArg.Float(rot.x),
|
||||
OscArg.Float(rot.y),
|
||||
OscArg.Float(-rot.z),
|
||||
OscArg.Float(-rot.w),
|
||||
),
|
||||
)
|
||||
|
||||
private fun buildMessages(bones: Map<BodyPart, BoneState>, config: VMCConfig, currentTime: Long, vrm: VrmGeometry?, routedBones: Set<BodyPart>): Sequence<OscMessage> = sequence {
|
||||
val time = (currentTime - initTime) / 1000f
|
||||
yield(OscMessage("/VMC/Ext/T", listOf(OscArg.Float(time))))
|
||||
yield(OscMessage("/VMC/Ext/OK", listOf(OscArg.Int(1))))
|
||||
|
||||
// Send the origin as root
|
||||
yield(transformMessage("/VMC/Ext/Root/Pos", "root", Vector3.NULL, Quaternion.IDENTITY))
|
||||
|
||||
// TODO UpperChest + shoulders affecting arms local rot
|
||||
for ((targetBodyPart, unityName) in BODY_PART_TO_UNITY_BONE) {
|
||||
if (targetBodyPart !in routedBones) continue
|
||||
|
||||
val targetParentBodyPart = VMC_BONE_PARENTS[targetBodyPart]
|
||||
val trackingBodyPart = if (config.mirrorTracking) vmcMirrorSource(targetBodyPart) else targetBodyPart
|
||||
val trackingBone = bones[trackingBodyPart] ?: continue
|
||||
|
||||
if (targetParentBodyPart == null) {
|
||||
// TODO anchorHip https://github.com/SlimeVR/SlimeVR-Server/blob/main/server/core/src/main/java/dev/slimevr/osc/VMCHandler.kt#L371
|
||||
val pos = vrm?.hipLocalPosition ?: Vector3.NULL
|
||||
val rot = vmcLocalRotation(trackingBone, null, targetBodyPart, null, config.mirrorTracking)
|
||||
yield(transformMessage("/VMC/Ext/Bone/Pos", unityName, pos, rot))
|
||||
continue
|
||||
}
|
||||
|
||||
val trackingParentBodyPart = if (config.mirrorTracking) {
|
||||
vmcMirrorSource(targetParentBodyPart)
|
||||
} else {
|
||||
targetParentBodyPart
|
||||
}
|
||||
val trackingParent = bones[trackingParentBodyPart] ?: continue
|
||||
|
||||
val pos = if (vrm != null) {
|
||||
vrm.bindOffsets[targetBodyPart] ?: Vector3.NULL
|
||||
} else {
|
||||
vmcLocalPosition(trackingBone, trackingParent, targetParentBodyPart, config.mirrorTracking)
|
||||
}
|
||||
val rot = vmcLocalRotation(
|
||||
trackingBone,
|
||||
trackingParent,
|
||||
targetBodyPart,
|
||||
targetParentBodyPart,
|
||||
config.mirrorTracking,
|
||||
)
|
||||
yield(transformMessage("/VMC/Ext/Bone/Pos", unityName, pos, rot))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class VMCInputBehaviour(private val settings: Settings) : Behaviour<VMCState, VMCActions, VMCManager> {
|
||||
override fun observe(receiver: VMCManager) {
|
||||
var oscReceiver: OscReceiver? = null
|
||||
|
||||
settings.context.state
|
||||
.map { it.data.vmcConfig.portIn }
|
||||
.distinctUntilChanged()
|
||||
.onEach { portIn ->
|
||||
oscReceiver?.close()
|
||||
oscReceiver = null
|
||||
if (settings.context.state.value.data.vmcConfig.enabled) {
|
||||
oscReceiver = OscReceiver(portIn)
|
||||
AppLogger.vmc.info("VMC input listening on port $portIn")
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
oscReceiver?.listenBundles { bundle ->
|
||||
for (content in bundle.contents) {
|
||||
when (content) {
|
||||
is OscContent.Message -> handleMessage(content.msg)
|
||||
|
||||
is OscContent.Bundle -> content.bundle.contents.forEach {
|
||||
if (it is OscContent.Message) handleMessage(it.msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.vmc.error("VMC receiver error: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private fun handleMessage(msg: OscMessage) {
|
||||
when (msg.address) {
|
||||
"/VMC/Ext/Bone/Pos" -> { /* TODO: Handle incoming bone rotation data */ }
|
||||
"/VMC/Ext/Hmd/Pos" -> { /* TODO: Handle incoming HMD position + rotation */ }
|
||||
"/VMC/Ext/Con/Pos" -> { /* TODO: Handle incoming controller position + rotation */ }
|
||||
"/VMC/Ext/Tra/Pos" -> { /* TODO: Handle incoming tracker position + rotation */ }
|
||||
"/VMC/Ext/Root/Pos" -> { /* TODO: Handle incoming root position/rotation offset */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package dev.slimevr.vmc
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.osc.OscMessage
|
||||
import dev.slimevr.osc.OscReceiver
|
||||
import dev.slimevr.osc.forEachOscMessage
|
||||
import dev.slimevr.util.formatExceptionMessage
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import solarxr_protocol.rpc.VMCOSCInputState
|
||||
|
||||
class VMCInputBehaviour(private val settings: Settings) : VMCBehaviour {
|
||||
override fun reduce(state: VMCState, action: VMCActions) = when (action) {
|
||||
is VMCActions.SetInput -> state.copy(
|
||||
status = state.status.copy(
|
||||
inputState = action.state,
|
||||
inputPort = action.port,
|
||||
inputError = action.error,
|
||||
),
|
||||
)
|
||||
|
||||
is VMCActions.SetLastReceivedInput -> state.copy(
|
||||
status = state.status.copy(lastReceivedInputMillis = action.millis),
|
||||
)
|
||||
|
||||
else -> state
|
||||
}
|
||||
|
||||
override fun observe(receiver: VMCManager) {
|
||||
var oscReceiver: OscReceiver? = null
|
||||
|
||||
settings.context.state
|
||||
.map { Pair(it.data.vmcConfig.enabled, it.data.vmcConfig.portIn) }
|
||||
.distinctUntilChanged()
|
||||
.onEach { (enabled, portIn) ->
|
||||
oscReceiver?.close()
|
||||
oscReceiver = null
|
||||
|
||||
if (!enabled) {
|
||||
receiver.context.dispatch(VMCActions.SetInput(state = VMCOSCInputState.IDLE))
|
||||
return@onEach
|
||||
}
|
||||
|
||||
val newReceiver = try {
|
||||
OscReceiver(portIn)
|
||||
} catch (e: Exception) {
|
||||
dispatchInputError(
|
||||
receiver = receiver,
|
||||
port = portIn,
|
||||
message = "Failed to start VMC receiver",
|
||||
throwable = e,
|
||||
)
|
||||
return@onEach
|
||||
}
|
||||
oscReceiver = newReceiver
|
||||
receiver.context.dispatch(
|
||||
VMCActions.SetInput(state = VMCOSCInputState.LISTENING, port = portIn),
|
||||
)
|
||||
AppLogger.vmc.info("VMC input listening on port $portIn")
|
||||
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
newReceiver.listenBundles { bundle ->
|
||||
forEachOscMessage(bundle) { msg -> handleMessage(msg, receiver, portIn) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
dispatchInputError(
|
||||
receiver = receiver,
|
||||
port = portIn,
|
||||
message = "VMC receiver error",
|
||||
throwable = e,
|
||||
)
|
||||
}
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private suspend fun dispatchInputError(
|
||||
receiver: VMCManager,
|
||||
port: Int?,
|
||||
message: String,
|
||||
throwable: Throwable,
|
||||
) {
|
||||
AppLogger.vmc.error(message, throwable)
|
||||
receiver.context.dispatch(
|
||||
VMCActions.SetInput(
|
||||
state = VMCOSCInputState.ERROR,
|
||||
port = port,
|
||||
error = formatExceptionMessage(message, throwable),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun handleMessage(msg: OscMessage, receiver: VMCManager, portIn: Int) {
|
||||
when (msg.address) {
|
||||
"/VMC/Ext/Bone/Pos" -> { /* TODO: Handle incoming bone rotation data */ }
|
||||
"/VMC/Ext/Hmd/Pos" -> { /* TODO: Handle incoming HMD position + rotation */ }
|
||||
"/VMC/Ext/Con/Pos" -> { /* TODO: Handle incoming controller position + rotation */ }
|
||||
"/VMC/Ext/Tra/Pos" -> { /* TODO: Handle incoming tracker position + rotation */ }
|
||||
"/VMC/Ext/Root/Pos" -> { /* TODO: Handle incoming root position/rotation offset */ }
|
||||
else -> return
|
||||
}
|
||||
|
||||
receiver.context.dispatchAll(
|
||||
listOf(
|
||||
VMCActions.SetInput(state = VMCOSCInputState.LISTENING, port = portIn),
|
||||
VMCActions.SetLastReceivedInput(System.currentTimeMillis()),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,54 @@ import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import solarxr_protocol.rpc.VMCOSCInputState
|
||||
import solarxr_protocol.rpc.VMCOSCOutputState
|
||||
import solarxr_protocol.rpc.VMCOSCVrmState
|
||||
|
||||
object VMCState
|
||||
data class VMCStatus(
|
||||
val inputState: VMCOSCInputState = VMCOSCInputState.IDLE,
|
||||
val inputPort: Int? = null,
|
||||
val inputError: String? = null,
|
||||
val lastReceivedInputMillis: Long? = null,
|
||||
|
||||
sealed interface VMCActions
|
||||
val outputState: VMCOSCOutputState = VMCOSCOutputState.IDLE,
|
||||
val outputError: String? = null,
|
||||
val targetAddress: String? = null,
|
||||
val targetPort: Int? = null,
|
||||
val lastFrameSentMillis: Long? = null,
|
||||
|
||||
val vrmState: VMCOSCVrmState = VMCOSCVrmState.NONE,
|
||||
val vrmError: String? = null,
|
||||
)
|
||||
|
||||
data class VMCState(
|
||||
val status: VMCStatus = VMCStatus(),
|
||||
)
|
||||
|
||||
sealed interface VMCActions {
|
||||
data class SetInput(
|
||||
val state: VMCOSCInputState,
|
||||
val port: Int? = null,
|
||||
val error: String? = null,
|
||||
) : VMCActions
|
||||
data class SetLastReceivedInput(val millis: Long) : VMCActions
|
||||
|
||||
data class SetOutput(
|
||||
val state: VMCOSCOutputState,
|
||||
val targetAddress: String? = null,
|
||||
val targetPort: Int? = null,
|
||||
val error: String? = null,
|
||||
) : VMCActions
|
||||
data class SetLastFrameSent(val millis: Long) : VMCActions
|
||||
|
||||
data class SetVrm(
|
||||
val state: VMCOSCVrmState,
|
||||
val error: String? = null,
|
||||
) : VMCActions
|
||||
}
|
||||
|
||||
typealias VMCContext = Context<VMCState, VMCActions>
|
||||
typealias VMCBehaviourType = Behaviour<VMCState, VMCActions, VMCManager>
|
||||
typealias VMCBehaviour = Behaviour<VMCState, VMCActions, VMCManager>
|
||||
|
||||
class VMCManager(val context: VMCContext) {
|
||||
fun startObserving(appContext: AppContextProvider) {
|
||||
@@ -27,9 +68,9 @@ class VMCManager(val context: VMCContext) {
|
||||
companion object {
|
||||
fun create(scope: CoroutineScope): VMCManager {
|
||||
val context = Context.create(
|
||||
initialState = VMCState,
|
||||
initialState = VMCState(),
|
||||
scope = scope,
|
||||
behaviours = emptyList<VMCBehaviourType>(),
|
||||
behaviours = emptyList<VMCBehaviour>(),
|
||||
name = "VMC",
|
||||
)
|
||||
return VMCManager(context)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package dev.slimevr.vmc
|
||||
|
||||
import dev.slimevr.config.VMCConfig
|
||||
import dev.slimevr.osc.OscArg
|
||||
import dev.slimevr.osc.OscBundle
|
||||
import dev.slimevr.osc.OscContent
|
||||
import dev.slimevr.osc.OscMessage
|
||||
import dev.slimevr.skeleton.BoneState
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.Duration
|
||||
|
||||
internal fun buildOutgoingBundle(
|
||||
bones: Map<BodyPart, BoneState>,
|
||||
routedBones: Set<BodyPart>,
|
||||
config: VMCConfig,
|
||||
vrm: VrmGeometry?,
|
||||
elapsed: Duration,
|
||||
): OscBundle {
|
||||
val contents = buildList {
|
||||
add(OscContent.Message(OscMessage("/VMC/Ext/T", listOf(OscArg.Float(elapsed.inWholeMilliseconds / 1000f)))))
|
||||
add(OscContent.Message(OscMessage("/VMC/Ext/OK", listOf(OscArg.Int(1)))))
|
||||
|
||||
// Send the origin as root
|
||||
add(OscContent.Message(transformMessage("/VMC/Ext/Root/Pos", "root", Vector3.NULL, Quaternion.IDENTITY)))
|
||||
|
||||
// TODO UpperChest + shoulders affecting arms local rot
|
||||
for ((targetBodyPart, unityName) in BODY_PART_TO_UNITY_BONE) {
|
||||
if (targetBodyPart !in routedBones) continue
|
||||
|
||||
val targetParentBodyPart = VMC_BONE_PARENTS[targetBodyPart]
|
||||
val trackingBodyPart = if (config.mirrorTracking) vmcMirrorSource(targetBodyPart) else targetBodyPart
|
||||
val trackingBone = bones[trackingBodyPart] ?: continue
|
||||
|
||||
if (targetParentBodyPart == null) {
|
||||
// TODO anchorHip https://github.com/SlimeVR/SlimeVR-Server/blob/main/server/core/src/main/java/dev/slimevr/osc/VMCHandler.kt#L371
|
||||
val pos = vrm?.hipLocalPosition ?: Vector3.NULL
|
||||
val rot = vmcLocalRotation(trackingBone, null, targetBodyPart, null, config.mirrorTracking)
|
||||
add(OscContent.Message(transformMessage("/VMC/Ext/Bone/Pos", unityName, pos, rot)))
|
||||
continue
|
||||
}
|
||||
|
||||
val trackingParentBodyPart = if (config.mirrorTracking) {
|
||||
vmcMirrorSource(targetParentBodyPart)
|
||||
} else {
|
||||
targetParentBodyPart
|
||||
}
|
||||
val trackingParent = bones[trackingParentBodyPart] ?: continue
|
||||
|
||||
val pos = if (vrm != null) {
|
||||
vrm.bindOffsets[targetBodyPart] ?: Vector3.NULL
|
||||
} else {
|
||||
vmcLocalPosition(trackingBone, trackingParent, targetParentBodyPart, config.mirrorTracking)
|
||||
}
|
||||
val rot = vmcLocalRotation(
|
||||
trackingBone,
|
||||
trackingParent,
|
||||
targetBodyPart,
|
||||
targetParentBodyPart,
|
||||
config.mirrorTracking,
|
||||
)
|
||||
add(OscContent.Message(transformMessage("/VMC/Ext/Bone/Pos", unityName, pos, rot)))
|
||||
}
|
||||
}
|
||||
|
||||
return OscBundle(1L, contents)
|
||||
}
|
||||
|
||||
internal fun buildInitRequestMessage(): OscMessage = OscMessage("/VMC/Ext/Req", emptyList())
|
||||
|
||||
private fun transformMessage(address: String, name: String, pos: Vector3, rot: Quaternion): OscMessage = OscMessage(
|
||||
address,
|
||||
listOf(
|
||||
OscArg.String(name),
|
||||
OscArg.Float(pos.x),
|
||||
OscArg.Float(pos.y),
|
||||
OscArg.Float(-pos.z),
|
||||
OscArg.Float(rot.x),
|
||||
OscArg.Float(rot.y),
|
||||
OscArg.Float(-rot.z),
|
||||
OscArg.Float(-rot.w),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,249 @@
|
||||
package dev.slimevr.vmc
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.config.VMCConfig
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.osc.OscSender
|
||||
import dev.slimevr.routing.BoneRoutingManager
|
||||
import dev.slimevr.skeleton.BoneState
|
||||
import dev.slimevr.skeleton.Skeleton
|
||||
import dev.slimevr.util.formatExceptionMessage
|
||||
import dev.slimevr.util.timeSource
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.RoutingOutput
|
||||
import solarxr_protocol.rpc.VMCOSCOutputState
|
||||
import solarxr_protocol.rpc.VMCOSCVrmState
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
private val FRAME_RETRY_DELAY = 2.seconds
|
||||
|
||||
private val RECOVERY_CONFIRM_DELAY = 2.seconds
|
||||
|
||||
class VMCOutputBehaviour(
|
||||
private val skeleton: Skeleton,
|
||||
private val settings: Settings,
|
||||
private val boneRouting: BoneRoutingManager,
|
||||
) : VMCBehaviour {
|
||||
private class OutputRuntime {
|
||||
var sender: OscSender? = null
|
||||
var vrm: VrmGeometry? = null
|
||||
var sendFailing = false
|
||||
var nextFrameRetryAt: TimeSource.Monotonic.ValueTimeMark? = null
|
||||
|
||||
/** Start of the current unbroken run of successful sends, null while sends are failing. */
|
||||
var healthySince: TimeSource.Monotonic.ValueTimeMark? = null
|
||||
}
|
||||
|
||||
override fun reduce(state: VMCState, action: VMCActions) = when (action) {
|
||||
is VMCActions.SetOutput -> state.copy(
|
||||
status = state.status.copy(
|
||||
outputState = action.state,
|
||||
targetAddress = action.targetAddress,
|
||||
targetPort = action.targetPort,
|
||||
outputError = action.error,
|
||||
),
|
||||
)
|
||||
|
||||
is VMCActions.SetLastFrameSent -> state.copy(
|
||||
status = state.status.copy(lastFrameSentMillis = action.millis),
|
||||
)
|
||||
|
||||
is VMCActions.SetVrm -> state.copy(
|
||||
status = state.status.copy(vrmState = action.state, vrmError = action.error),
|
||||
)
|
||||
|
||||
else -> state
|
||||
}
|
||||
|
||||
override fun observe(receiver: VMCManager) {
|
||||
val runtime = OutputRuntime()
|
||||
|
||||
observeVrm(receiver, runtime)
|
||||
observeTargetChanges(receiver, runtime)
|
||||
observeFrames(receiver, runtime)
|
||||
}
|
||||
|
||||
private fun observeVrm(receiver: VMCManager, runtime: OutputRuntime) {
|
||||
settings.context.state
|
||||
.map { it.data.vmcConfig.vrmJson }
|
||||
.distinctUntilChanged()
|
||||
.onEach { vrmJson ->
|
||||
val json = vrmJson?.takeIf { it.isNotEmpty() }
|
||||
if (json == null) {
|
||||
runtime.vrm = null
|
||||
receiver.context.dispatch(VMCActions.SetVrm(state = VMCOSCVrmState.NONE))
|
||||
return@onEach
|
||||
}
|
||||
|
||||
try {
|
||||
runtime.vrm = buildVrmGeometry(VrmReader(json))
|
||||
receiver.context.dispatch(VMCActions.SetVrm(state = VMCOSCVrmState.LOADED))
|
||||
} catch (e: Exception) {
|
||||
runtime.vrm = null
|
||||
val message = "Failed to parse VRM JSON"
|
||||
AppLogger.vmc.error(message, e)
|
||||
receiver.context.dispatch(
|
||||
VMCActions.SetVrm(state = VMCOSCVrmState.ERROR, error = formatExceptionMessage(message, e)),
|
||||
)
|
||||
}
|
||||
}
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private fun observeTargetChanges(receiver: VMCManager, runtime: OutputRuntime) {
|
||||
settings.context.state
|
||||
.map { Triple(it.data.vmcConfig.enabled, it.data.vmcConfig.address, it.data.vmcConfig.portOut) }
|
||||
.distinctUntilChanged()
|
||||
.onEach { (enabled, address, port) -> applyTarget(receiver, runtime, enabled, address, port) }
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
// TODO: VSeeFace used to crash if we send data too fast. idk if that still apply so lets try without for now
|
||||
private fun observeFrames(receiver: VMCManager, runtime: OutputRuntime) {
|
||||
val startedAt = timeSource.markNow()
|
||||
|
||||
val routedBones = boneRouting.context.state
|
||||
.map { state -> state.routes.filterValues { RoutingOutput.VMC in it }.keys }
|
||||
.distinctUntilChanged()
|
||||
|
||||
val config = settings.context.state
|
||||
.map { it.data.vmcConfig }
|
||||
.distinctUntilChanged()
|
||||
|
||||
combine(skeleton.computed, routedBones, config, ::Triple)
|
||||
.onEach { (computedSkeleton, bones, vmcConfig) ->
|
||||
sendFrame(receiver, runtime, computedSkeleton, bones, vmcConfig, startedAt)
|
||||
}
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private suspend fun applyTarget(
|
||||
receiver: VMCManager,
|
||||
runtime: OutputRuntime,
|
||||
enabled: Boolean,
|
||||
address: String,
|
||||
port: Int,
|
||||
) {
|
||||
runtime.sender?.close()
|
||||
runtime.sender = null
|
||||
runtime.sendFailing = false
|
||||
runtime.nextFrameRetryAt = null
|
||||
runtime.healthySince = null
|
||||
|
||||
if (!enabled) {
|
||||
receiver.context.dispatch(VMCActions.SetOutput(state = VMCOSCOutputState.IDLE))
|
||||
return
|
||||
}
|
||||
|
||||
val sender = try {
|
||||
OscSender(address, port).also {
|
||||
AppLogger.vmc.info("VMC output started: $address:$port")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
dispatchOutputError(
|
||||
receiver = receiver,
|
||||
message = "Failed to create VMC sender",
|
||||
throwable = e,
|
||||
targetAddress = address,
|
||||
targetPort = port,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
runtime.sender = sender
|
||||
// Opening a UDP socket proves nothing about the target, so the output stays idle until a
|
||||
// frame has actually gone out without error.
|
||||
receiver.context.dispatch(
|
||||
VMCActions.SetOutput(state = VMCOSCOutputState.IDLE, targetAddress = address, targetPort = port),
|
||||
)
|
||||
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
sender.send(buildInitRequestMessage())
|
||||
} catch (e: Exception) {
|
||||
dispatchOutputError(
|
||||
receiver = receiver,
|
||||
message = "Failed to send VMC init request",
|
||||
throwable = e,
|
||||
targetAddress = address,
|
||||
targetPort = port,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun sendFrame(
|
||||
receiver: VMCManager,
|
||||
runtime: OutputRuntime,
|
||||
bones: Map<BodyPart, BoneState>,
|
||||
routedBones: Set<BodyPart>,
|
||||
config: VMCConfig,
|
||||
startedAt: TimeSource.Monotonic.ValueTimeMark,
|
||||
) {
|
||||
val sender = runtime.sender ?: return
|
||||
val status = receiver.context.state.value.status
|
||||
if (runtime.sendFailing && runtime.nextFrameRetryAt?.hasPassedNow() == false) return
|
||||
|
||||
val bundle = buildOutgoingBundle(bones, routedBones, config, runtime.vrm, startedAt.elapsedNow())
|
||||
|
||||
try {
|
||||
sender.send(bundle)
|
||||
receiver.context.dispatch(VMCActions.SetLastFrameSent(System.currentTimeMillis()))
|
||||
runtime.sendFailing = false
|
||||
runtime.nextFrameRetryAt = null
|
||||
|
||||
val healthySince = runtime.healthySince ?: timeSource.markNow().also { runtime.healthySince = it }
|
||||
if (status.outputState == VMCOSCOutputState.READY) return
|
||||
if (healthySince.elapsedNow() < RECOVERY_CONFIRM_DELAY) return
|
||||
|
||||
AppLogger.vmc.info("VMC frames reaching ${status.targetAddress}:${status.targetPort}")
|
||||
receiver.context.dispatch(
|
||||
VMCActions.SetOutput(
|
||||
state = VMCOSCOutputState.READY,
|
||||
targetAddress = status.targetAddress,
|
||||
targetPort = status.targetPort,
|
||||
),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
runtime.healthySince = null
|
||||
runtime.nextFrameRetryAt = timeSource.markNow() + FRAME_RETRY_DELAY
|
||||
runtime.sendFailing = true
|
||||
// Report once per transition. The refusal is only raised every other send, so gating
|
||||
// on the previous attempt instead would log again on each one that fails.
|
||||
if (status.outputState == VMCOSCOutputState.ERROR) return
|
||||
|
||||
dispatchOutputError(
|
||||
receiver = receiver,
|
||||
message = "Failed to send VMC frame",
|
||||
throwable = e,
|
||||
targetAddress = status.targetAddress,
|
||||
targetPort = status.targetPort,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun dispatchOutputError(
|
||||
receiver: VMCManager,
|
||||
message: String,
|
||||
throwable: Throwable,
|
||||
targetAddress: String?,
|
||||
targetPort: Int?,
|
||||
) {
|
||||
AppLogger.vmc.error(message, throwable)
|
||||
receiver.context.dispatch(
|
||||
VMCActions.SetOutput(
|
||||
state = VMCOSCOutputState.ERROR,
|
||||
targetAddress = targetAddress,
|
||||
targetPort = targetPort,
|
||||
error = formatExceptionMessage(message, throwable),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,17 @@ package dev.slimevr.vrcosc
|
||||
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.VRServerActions
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.device.Device
|
||||
import dev.slimevr.device.DeviceActions
|
||||
import dev.slimevr.device.DeviceOrigin
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.osc.OscBundle
|
||||
import dev.slimevr.osc.OscContent
|
||||
import dev.slimevr.osc.OscMessage
|
||||
import dev.slimevr.osc.OscReceiver
|
||||
import dev.slimevr.osc.forEachOscMessage
|
||||
import dev.slimevr.tracker.Tracker
|
||||
import dev.slimevr.tracker.TrackerActions
|
||||
import dev.slimevr.util.formatExceptionMessage
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -111,6 +112,7 @@ private class VRSystemTrackerRegistry(
|
||||
|
||||
class VRCOSCInputBehaviour(
|
||||
private val appContext: AppContextProvider,
|
||||
private val settings: Settings,
|
||||
) : VRCOSCBehaviour {
|
||||
override fun reduce(state: VRCOSCState, action: VRCOSCActions) = when (action) {
|
||||
is VRCOSCActions.SetInput -> state.copy(
|
||||
@@ -132,8 +134,8 @@ class VRCOSCInputBehaviour(
|
||||
val registry = VRSystemTrackerRegistry(appContext, receiver)
|
||||
var oscReceiver: OscReceiver? = null
|
||||
|
||||
receiver.settings.context.state
|
||||
.map { state -> Pair(state.data.vrcOscConfig.enabled, vrcOscPortIn(state.data.vrcOscConfig)) }
|
||||
settings.context.state
|
||||
.map { state -> Pair(state.data.vrcOscConfig.enabled, state.data.vrcOscConfig.portIn) }
|
||||
.distinctUntilChanged()
|
||||
.onEach { (enabled, portIn) ->
|
||||
oscReceiver?.close()
|
||||
@@ -164,7 +166,9 @@ class VRCOSCInputBehaviour(
|
||||
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
newReceiver.listenBundles { bundle -> handleBundle(bundle, registry, receiver, portIn) }
|
||||
newReceiver.listenBundles { bundle ->
|
||||
forEachOscMessage(bundle) { msg -> handleIncomingMessage(msg, registry, receiver, portIn) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
dispatchInputError(
|
||||
receiver = receiver,
|
||||
@@ -193,29 +197,6 @@ class VRCOSCInputBehaviour(
|
||||
)
|
||||
}
|
||||
|
||||
private fun handleBundle(
|
||||
bundle: OscBundle,
|
||||
registry: VRSystemTrackerRegistry,
|
||||
receiver: VRCOSCManager,
|
||||
portIn: Int,
|
||||
) {
|
||||
handleBundleContents(bundle.contents, registry, receiver, portIn)
|
||||
}
|
||||
|
||||
private fun handleBundleContents(
|
||||
contents: List<OscContent>,
|
||||
registry: VRSystemTrackerRegistry,
|
||||
receiver: VRCOSCManager,
|
||||
portIn: Int,
|
||||
) {
|
||||
for (content in contents) {
|
||||
when (content) {
|
||||
is OscContent.Message -> handleIncomingMessage(content.msg, registry, receiver, portIn)
|
||||
is OscContent.Bundle -> handleBundleContents(content.bundle.contents, registry, receiver, portIn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleIncomingMessage(
|
||||
message: OscMessage,
|
||||
registry: VRSystemTrackerRegistry,
|
||||
|
||||
@@ -2,8 +2,6 @@ package dev.slimevr.vrcosc
|
||||
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.EventDispatcher
|
||||
import dev.slimevr.Phase1ContextProvider
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
@@ -94,15 +92,15 @@ typealias VRCOSCBehaviour = Behaviour<VRCOSCState, VRCOSCActions, VRCOSCManager>
|
||||
class VRCOSCManager(
|
||||
val context: VRCOSCContext,
|
||||
val oscQueryAddress: String,
|
||||
val settings: Settings,
|
||||
) {
|
||||
val events: EventDispatcher<VRCOSCEvent> = EventDispatcher("VRCOSC", context.scope, capacity = 32)
|
||||
|
||||
fun startObserving(appContext: AppContextProvider) {
|
||||
val settings = appContext.config.settings
|
||||
val behaviours = listOf(
|
||||
VRCOSCOutputBehaviour(appContext.skeleton, appContext.boneRouting),
|
||||
VRCOSCInputBehaviour(appContext),
|
||||
VRCOSCOscQueryBehaviour(localIp = oscQueryAddress),
|
||||
VRCOSCOutputBehaviour(appContext.skeleton, settings, appContext.boneRouting),
|
||||
VRCOSCInputBehaviour(appContext, settings),
|
||||
VRCOSCOscQueryBehaviour(settings, localIp = oscQueryAddress),
|
||||
)
|
||||
|
||||
context.behaviours.addAll(behaviours)
|
||||
@@ -117,20 +115,16 @@ class VRCOSCManager(
|
||||
|
||||
companion object {
|
||||
fun create(
|
||||
ctx: Phase1ContextProvider,
|
||||
scope: CoroutineScope,
|
||||
oscQueryAddress: String,
|
||||
): VRCOSCManager {
|
||||
val settings = ctx.config.settings
|
||||
val context = Context.create(
|
||||
initialState = VRCOSCState(
|
||||
status = VRCOSCStatus(),
|
||||
),
|
||||
initialState = VRCOSCState(),
|
||||
behaviours = emptyList<VRCOSCBehaviour>(),
|
||||
scope = scope,
|
||||
name = "VRCOSC",
|
||||
)
|
||||
return VRCOSCManager(context, oscQueryAddress, settings)
|
||||
return VRCOSCManager(context, oscQueryAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
package dev.slimevr.vrcosc
|
||||
|
||||
import dev.slimevr.config.DEFAULT_VRC_OSC_PORT_OUT
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.oscquery.OscQueryAccess
|
||||
import dev.slimevr.oscquery.OscQueryDiscovery
|
||||
import dev.slimevr.oscquery.OscQueryNode
|
||||
import dev.slimevr.oscquery.OscQueryServer
|
||||
import dev.slimevr.util.formatExceptionMessage
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
@@ -18,6 +20,7 @@ import solarxr_protocol.rpc.VRCOSCOscQueryState
|
||||
private const val VRCHAT_SERVICE_PREFIX = "VRChat-Client"
|
||||
|
||||
class VRCOSCOscQueryBehaviour(
|
||||
private val settings: Settings,
|
||||
private val localIp: String,
|
||||
) : VRCOSCBehaviour {
|
||||
private class OscQueryRuntime(
|
||||
@@ -47,8 +50,8 @@ class VRCOSCOscQueryBehaviour(
|
||||
override fun observe(receiver: VRCOSCManager) {
|
||||
val runtime = OscQueryRuntime(localIp)
|
||||
|
||||
receiver.settings.context.state
|
||||
.map { state -> Triple(state.data.vrcOscConfig.enabled, state.data.vrcOscConfig.useManualNetwork, vrcOscPortIn(state.data.vrcOscConfig)) }
|
||||
settings.context.state
|
||||
.map { state -> Triple(state.data.vrcOscConfig.enabled, state.data.vrcOscConfig.useManualNetwork, state.data.vrcOscConfig.portIn) }
|
||||
.distinctUntilChanged()
|
||||
.onEach { (enabled, useManualNetwork, portIn) ->
|
||||
if (!enabled || useManualNetwork) {
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package dev.slimevr.vrcosc
|
||||
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.config.VRCOSCConfig
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.osc.OscSender
|
||||
import dev.slimevr.routing.BoneRoutingManager
|
||||
import dev.slimevr.skeleton.BoneState
|
||||
import dev.slimevr.skeleton.Skeleton
|
||||
import dev.slimevr.util.formatExceptionMessage
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
@@ -16,17 +19,26 @@ import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.RoutingOutput
|
||||
import solarxr_protocol.rpc.VRCOSCOutputState
|
||||
import solarxr_protocol.rpc.VRCOSCTargetSource
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
private const val FRAME_RETRY_DELAY_MS = 5_000L
|
||||
private val FRAME_RETRY_DELAY = 2.seconds
|
||||
|
||||
// UDP reports a target with nothing listening through an ICMP refusal that surfaces on a later
|
||||
// send and is cleared once read, so sends alternate between failing and succeeding. A single
|
||||
// success is therefore no proof of recovery; require an uninterrupted run of them.
|
||||
private val RECOVERY_CONFIRM_DELAY = 2.seconds
|
||||
|
||||
class VRCOSCOutputBehaviour(
|
||||
private val skeleton: Skeleton,
|
||||
private val settings: Settings,
|
||||
private val boneRouting: BoneRoutingManager,
|
||||
) : VRCOSCBehaviour {
|
||||
private class OutputRuntime {
|
||||
var sender: OscSender? = null
|
||||
var frameSendFailureActive = false
|
||||
var nextFrameRetryAt = 0L
|
||||
var sendFailing = false
|
||||
var nextFrameRetryAt: TimeSource.Monotonic.ValueTimeMark? = null
|
||||
var healthySince: TimeSource.Monotonic.ValueTimeMark? = null
|
||||
}
|
||||
|
||||
override fun reduce(state: VRCOSCState, action: VRCOSCActions) = when (action) {
|
||||
@@ -56,15 +68,12 @@ class VRCOSCOutputBehaviour(
|
||||
}
|
||||
|
||||
private fun observeTargetChanges(receiver: VRCOSCManager, runtime: OutputRuntime) {
|
||||
val configFlow = receiver.settings.context.state.map { it.data.vrcOscConfig }.distinctUntilChanged()
|
||||
val configFlow = settings.context.state.map { it.data.vrcOscConfig }.distinctUntilChanged()
|
||||
val discoveredFlow = receiver.context.state.map { state -> state.status.discoveredTargets }.distinctUntilChanged()
|
||||
|
||||
configFlow.combine(discoveredFlow) { config, discoveredTargets ->
|
||||
Triple(
|
||||
config.enabled,
|
||||
resolveTarget(config, discoveredTargets),
|
||||
resolveTargetSource(config, discoveredTargets),
|
||||
)
|
||||
val (target, source) = resolveTarget(config, discoveredTargets)
|
||||
Triple(config.enabled, target, source)
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
.onEach { (enabled, target, source) ->
|
||||
@@ -98,8 +107,9 @@ class VRCOSCOutputBehaviour(
|
||||
) {
|
||||
runtime.sender?.close()
|
||||
runtime.sender = null
|
||||
runtime.frameSendFailureActive = false
|
||||
runtime.nextFrameRetryAt = 0L
|
||||
runtime.sendFailing = false
|
||||
runtime.nextFrameRetryAt = null
|
||||
runtime.healthySince = null
|
||||
|
||||
if (!enabled || target == null) {
|
||||
receiver.context.dispatch(
|
||||
@@ -133,7 +143,7 @@ class VRCOSCOutputBehaviour(
|
||||
runtime.sender = sender
|
||||
receiver.context.dispatch(
|
||||
VRCOSCActions.SetOutput(
|
||||
state = VRCOSCOutputState.READY,
|
||||
state = VRCOSCOutputState.IDLE,
|
||||
targetAddress = target.address,
|
||||
targetPort = target.port,
|
||||
targetSource = source,
|
||||
@@ -150,36 +160,39 @@ class VRCOSCOutputBehaviour(
|
||||
) {
|
||||
val sender = runtime.sender ?: return
|
||||
val state = receiver.context.state.value
|
||||
val vrcOscConfig = receiver.settings.context.state.value.data.vrcOscConfig
|
||||
if (!vrcOscConfig.enabled) return
|
||||
if (!settings.context.state.value.data.vrcOscConfig.enabled) return
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
if (runtime.frameSendFailureActive && now < runtime.nextFrameRetryAt) return
|
||||
if (runtime.sendFailing && runtime.nextFrameRetryAt?.hasPassedNow() == false) return
|
||||
|
||||
val bundle = buildOutgoingBundle(bones, routedBones) ?: return
|
||||
|
||||
try {
|
||||
sender.send(bundle)
|
||||
receiver.context.dispatch(VRCOSCActions.SetLastFrameSent(System.currentTimeMillis()))
|
||||
if (runtime.frameSendFailureActive) {
|
||||
runtime.frameSendFailureActive = false
|
||||
runtime.nextFrameRetryAt = 0L
|
||||
AppLogger.vrc.info("VRChat OSC frame send recovered")
|
||||
receiver.context.dispatch(
|
||||
VRCOSCActions.SetOutput(
|
||||
state = VRCOSCOutputState.READY,
|
||||
targetAddress = state.status.targetAddress,
|
||||
targetPort = state.status.targetPort,
|
||||
targetSource = state.status.targetSource,
|
||||
error = null,
|
||||
),
|
||||
)
|
||||
}
|
||||
runtime.sendFailing = false
|
||||
runtime.nextFrameRetryAt = null
|
||||
|
||||
val healthySince = runtime.healthySince ?: timeSource.markNow().also { runtime.healthySince = it }
|
||||
if (state.status.outputState == VRCOSCOutputState.READY) return
|
||||
if (healthySince.elapsedNow() < RECOVERY_CONFIRM_DELAY) return
|
||||
|
||||
AppLogger.vrc.info("VRChat OSC frames reaching ${state.status.targetAddress}:${state.status.targetPort}")
|
||||
receiver.context.dispatch(
|
||||
VRCOSCActions.SetOutput(
|
||||
state = VRCOSCOutputState.READY,
|
||||
targetAddress = state.status.targetAddress,
|
||||
targetPort = state.status.targetPort,
|
||||
targetSource = state.status.targetSource,
|
||||
error = null,
|
||||
),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
runtime.nextFrameRetryAt = System.currentTimeMillis() + FRAME_RETRY_DELAY_MS
|
||||
if (runtime.frameSendFailureActive) return
|
||||
runtime.healthySince = null
|
||||
runtime.nextFrameRetryAt = timeSource.markNow() + FRAME_RETRY_DELAY
|
||||
runtime.sendFailing = true
|
||||
|
||||
if (state.status.outputState == VRCOSCOutputState.ERROR) return
|
||||
|
||||
runtime.frameSendFailureActive = true
|
||||
dispatchOutputError(
|
||||
receiver = receiver,
|
||||
message = "Failed to send VRChat OSC frame",
|
||||
@@ -235,24 +248,15 @@ class VRCOSCOutputBehaviour(
|
||||
private fun resolveTarget(
|
||||
config: VRCOSCConfig,
|
||||
discoveredTargets: List<VRCOSCDiscoveredTargetInfo>,
|
||||
): OscSenderTarget? {
|
||||
): Pair<OscSenderTarget?, VRCOSCTargetSource> {
|
||||
if (config.useManualNetwork) {
|
||||
return OscSenderTarget(address = config.address, port = config.portOut)
|
||||
return OscSenderTarget(address = config.address, port = config.portOut) to VRCOSCTargetSource.MANUAL
|
||||
}
|
||||
|
||||
val discoveredTarget = discoveredTargets.firstOrNull() ?: return null
|
||||
val discoveredTarget = discoveredTargets.firstOrNull() ?: return null to VRCOSCTargetSource.NONE
|
||||
return OscSenderTarget(
|
||||
address = discoveredTarget.address,
|
||||
port = discoveredTarget.portOut,
|
||||
)
|
||||
}
|
||||
|
||||
private fun resolveTargetSource(
|
||||
config: VRCOSCConfig,
|
||||
discoveredTargets: List<VRCOSCDiscoveredTargetInfo>,
|
||||
): VRCOSCTargetSource = when {
|
||||
config.useManualNetwork -> VRCOSCTargetSource.MANUAL
|
||||
discoveredTargets.isNotEmpty() -> VRCOSCTargetSource.DISCOVERED
|
||||
else -> VRCOSCTargetSource.NONE
|
||||
) to VRCOSCTargetSource.DISCOVERED
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package dev.slimevr.vrcosc
|
||||
|
||||
import dev.slimevr.config.VRCOSCConfig
|
||||
import dev.slimevr.osc.OscArg
|
||||
import io.github.axisangles.ktmath.EulerAngles
|
||||
import io.github.axisangles.ktmath.EulerOrder
|
||||
@@ -10,8 +9,6 @@ import kotlin.math.PI
|
||||
|
||||
internal const val TRACKING_VRSYSTEM_PATH: String = "/tracking/vrsystem"
|
||||
|
||||
internal fun vrcOscPortIn(config: VRCOSCConfig): Int = config.portIn
|
||||
|
||||
internal fun parsePosition(args: List<OscArg>, startIndex: Int = 0): Vector3? {
|
||||
val x = args.getOrNull(startIndex)?.asFloatOrNull() ?: return null
|
||||
val y = args.getOrNull(startIndex + 1)?.asFloatOrNull() ?: return null
|
||||
@@ -31,9 +28,3 @@ internal fun parseVrcEulerRotation(args: List<OscArg>, startIndex: Int = 0): Qua
|
||||
).toQuaternion()
|
||||
return Quaternion(w, -rx, -ry, rz)
|
||||
}
|
||||
|
||||
internal fun formatExceptionMessage(prefix: String, throwable: Throwable): String {
|
||||
val detail = throwable.message?.takeIf { it.isNotBlank() }
|
||||
?: throwable::class.simpleName.orEmpty()
|
||||
return if (detail.isBlank()) prefix else "$prefix: $detail"
|
||||
}
|
||||
Reference in new issue
Block a user