From 43af2a24bde879292dc72585fa64db6a37695dd3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 12 Jun 2026 14:20:28 +0100 Subject: [PATCH] Add calibrated Move pose fusion stream --- docs/implementation-plan.md | 11 + docs/perfect-machine-module-library.md | 14 +- src/Mimir.BufferSmoke/Program.cs | 156 +++++++++ .../Synchronization/MimirMoveFusion.cs | 307 ++++++++++++++++++ .../Synchronization/MimirMovePoseStream.cs | 71 ++++ state/evidence.jsonl | 1 + state/map.yaml | 10 + 7 files changed, 566 insertions(+), 4 deletions(-) create mode 100644 src/Mimir.Runtime/Synchronization/MimirMoveFusion.cs create mode 100644 src/Mimir.Runtime/Synchronization/MimirMovePoseStream.cs diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 9a6bfd1..da82fc0 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -56,6 +56,17 @@ a named invariant that the native runtime cannot protect yet. Mimir owns calibration, association, triangulation, IMU fusion, prediction, confidence, and latency accounting for those poses before Fensalir consumes them as interactive controller input. +- `MimirMoveFusion` is the first calibrated fusion owner for Move tracking: + it consumes native Muninn Move evidence samples, requires calibrated camera + witnesses before publishing a pose, associates marker candidates with the + USB controller state, triangulates multi-camera orb position, demotes + single-ray fallbacks through confidence, carries buttons/trigger/gyro into + `mimir.move_controller_pose.v1`, and marks orientation as + `orientation:imu-unresolved` until the IMU/prediction pass earns full 6DoF. +- `MimirMovePoseStream` frames resolved Move poses as + `mimir.move_controller_pose_stream_frame.v1` over CultMesh shared-memory + bytes streams so Fensalir and other consumers have a realtime stream contract + for Mimir-fused controller input. - `scripts/start-nightwing-move-tracking.ps1` is the narrow live Nightwing bring-up path: it starts the `/eve/periwinkle` receiver/recorder on Starfire, stages the Nightwing Eye/Move Python worker, keeps a heartbeat for field diff --git a/docs/perfect-machine-module-library.md b/docs/perfect-machine-module-library.md index d5c3df0..3f5b5d8 100644 --- a/docs/perfect-machine-module-library.md +++ b/docs/perfect-machine-module-library.md @@ -14,7 +14,7 @@ job-interview answer for why it belongs in the body of the machine. | Alignment actuator | `Mimir.Runtime` + Faust | Converts sync state into bounded fractional-delay, gain, and sample-rate-offset controls; Faust moves samples. | `src/Mimir.Runtime/Synchronization/MimirAudioAlignmentActuator.cs` | | Audio actuator strategies | `Mimir.Runtime` + Faust | Integer baseline, Farrow fractional delay, variable ASRC, and hybrid delay/ASRC strategy profiles. | `src/Mimir.Runtime/Synchronization/MimirAudioActuatorConfiguration.cs` | | CultMesh contracts | `Mimir.Runtime` | Typed codebook, decoder, acoustic path, actuator, program, Move evidence, and Mimir-fused Move controller pose documents for distributed Mimir nodes. | `src/Mimir.Runtime/Synchronization/MimirCultMeshContracts.cs`, `src/Mimir.Runtime/Synchronization/MimirTrackingObservation.cs` | -| Move controller fusion | `Mimir.Runtime` + native reservoir + Fensalir | Mimir admits Muninn marker candidates plus controller/IMU/button feeds into native `move_evidence` buffers, fuses them into `mimir.move_controller_pose.v1`, and Fensalir consumes the resolved pose stream for interactive environments. | `src/Mimir.Runtime/Synchronization/MimirTrackingObservation.cs`, `src/Mimir.Runtime/Synchronization/MimirMuninnMoveEvidence.cs`, `src/Mimir.Runtime/Synchronization/MimirNativeReservoirRuntime.cs`, `native/reservoir/src/lib.rs` | +| Move controller fusion | `Mimir.Runtime` + native reservoir + Fensalir | Mimir admits Muninn marker candidates plus controller/IMU/button feeds into native `move_evidence` buffers. `MimirMoveFusion` now publishes calibrated `mimir.move_controller_pose.v1` position/button/gyro poses only when camera witnesses are calibrated, and `MimirMovePoseStream` carries those poses over a realtime CultMesh frame. IMU orientation/prediction remains the next earned 6DoF step before Fensalir treats the stream as VR-grade controller input. | `src/Mimir.Runtime/Synchronization/MimirTrackingObservation.cs`, `src/Mimir.Runtime/Synchronization/MimirMuninnMoveEvidence.cs`, `src/Mimir.Runtime/Synchronization/MimirMoveFusion.cs`, `src/Mimir.Runtime/Synchronization/MimirMovePoseStream.cs`, `src/Mimir.Runtime/Synchronization/MimirNativeReservoirRuntime.cs`, `native/reservoir/src/lib.rs` | | Acoustic path learning | `Mimir.Runtime` | Calibration stages for usable bands, confusion, global delay, group delay, and codebook adaptation. | `src/Mimir.Runtime/Synchronization/MimirAcousticPathLearningConfiguration.cs` | | Acoustic localization | `Mimir.Runtime` + Fensalir | Pairwise TDOA, SRP-PHAT grid, sparse source, and visual-constrained localization profiles plus a small SRP/TDOA scorer. | `src/Mimir.Runtime/Synchronization/MimirAcousticLocalizationConfiguration.cs`, `src/Mimir.Runtime/Synchronization/MimirAcousticLocalizationSolver.cs` | | Benchmark panels | `Mimir.Runtime` | Decoder golf and meatspace acceptance degradation panels with receipt roots and thresholds. | `src/Mimir.Runtime/Synchronization/MimirBenchmarkPanelConfiguration.cs` | @@ -46,9 +46,14 @@ job-interview answer for why it belongs in the body of the machine. - USB-attached Moves on Starfire and Nightwing publish source-local Muninn evidence streams: glowing-orb marker candidates and controller/IMU/button state. Odin discovers/projects those streams. Mimir owns native evidence - buffer admission/layout, calibration, association, triangulation, IMU fusion, - prediction, and `mimir.move_controller_pose.v1` publication. Fensalir - consumes that resolved pose stream for interactive environments. + buffer admission/layout, calibration, association, triangulation, confidence, + and `mimir.move_controller_pose.v1` publication. The current fusion pass + resolves calibrated optical position and controller state; orientation remains + explicitly unresolved until IMU fusion/prediction lands. Fensalir consumes the + resolved pose stream for interactive environments once that contract is wired. +- Resolved Move poses are framed as + `mimir.move_controller_pose_stream_frame.v1` on CultMesh shared-memory bytes + streams; the stream is a Mimir output surface, not a new fusion owner. - OBS may receive compatibility program surfaces and stems. It does not own calibration, composition, preview/control, or publication. @@ -65,6 +70,7 @@ dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --move-native-reservoir-smoke --native-reservoir .\native\reservoir\target\debug\localcast_reservoir.dll dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --muninn-move-evidence-smoke --native-reservoir .\native\reservoir\target\debug\localcast_reservoir.dll dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --muninn-move-cultmesh-stream-smoke --native-reservoir .\native\reservoir\target\debug\localcast_reservoir.dll +dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --move-fusion-smoke dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --perfect-machine-manifest dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --bioacoustic-actuator-self-test ``` diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index e438bc3..ed4ac45 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -115,6 +115,11 @@ if (args.Any(arg => string.Equals(arg, "--muninn-move-cultmesh-stream-smoke", St ParseStringOption(args, "--native-reservoir", DefaultNativeReservoirPath())); } +if (args.Any(arg => string.Equals(arg, "--move-fusion-smoke", StringComparison.OrdinalIgnoreCase))) +{ + return RunMoveFusionSmoke(); +} + if (args.Any(arg => string.Equals(arg, "--import-obs-program-scene", StringComparison.OrdinalIgnoreCase))) { return await ImportObsProgramSceneAsync( @@ -1712,6 +1717,157 @@ static int RunMuninnMoveCultMeshStreamSmoke(string nativeReservoirPath) : 1; } +static int RunMoveFusionSmoke() +{ + const ulong leftWitnessHash = 0x00000000000A11CE; + const ulong rightWitnessHash = 0x0000000000000B0B; + var observedAt = "2026-06-11T18:30:00.0040000Z"; + var markers = new[] + { + new MuninnMoveMarkerCandidateDocument( + StreamId: "nightwing:ps3-eye-0:move-marker-candidates", + HostId: "nightwing", + CameraId: "ps3-eye-0", + FrameSequence: 9101, + SourceIdHash: leftWitnessHash, + TileX: 10, + TileY: 10, + CenterXPx: 170.0f, + CenterYPx: 120.0f, + RadiusPx: 12.0f, + AreaPx: 452, + MeanLuma: 0.64f, + PeakLuma: 252, + Score: 0.90f, + ObservedAt: observedAt), + new MuninnMoveMarkerCandidateDocument( + StreamId: "starfire:ps3-eye-1:move-marker-candidates", + HostId: "starfire", + CameraId: "ps3-eye-1", + FrameSequence: 9102, + SourceIdHash: rightWitnessHash, + TileX: 11, + TileY: 10, + CenterXPx: 150.0f, + CenterYPx: 120.0f, + RadiusPx: 12.0f, + AreaPx: 449, + MeanLuma: 0.62f, + PeakLuma: 250, + Score: 0.86f, + ObservedAt: observedAt) + }; + var controllers = new[] + { + new MuninnMoveControllerStateDocument( + StreamId: "nightwing:move-usb:move-controller-state", + HostId: "nightwing", + MoveId: "move-usb", + Sequence: 79, + SourceTimestampNs: 1_781_202_600_004_000_000, + AccelerometerXyz: [-0.01f, 0.10f, 0.99f], + GyroscopeXyz: [0.02f, -0.01f, 0.04f], + MagnetometerXyz: [0.0f, 0.0f, 0.0f], + TriggerValue: 0.5f, + Buttons: ["move", "trigger"], + Battery01: 0.72f, + ObservedAt: observedAt) + }; + var calibration = new MimirMoveFusionRigCalibration( + CalibrationId: "mimir-move-stage-calibration-smoke", + TrackingSpaceId: "mimir-stage-space", + Cameras: + [ + new MimirMoveFusionCameraCalibration( + CameraId: "nightwing:ps3-eye-0", + WitnessIdHash: leftWitnessHash, + PositionMeters: new MimirVector3Snapshot(-0.1, 0.0, 0.0), + Orientation: new MimirQuaternionSnapshot(0.0, 0.0, 0.0, 1.0), + FocalLengthXPx: 100.0, + FocalLengthYPx: 100.0, + PrincipalPointXPx: 160.0, + PrincipalPointYPx: 120.0), + new MimirMoveFusionCameraCalibration( + CameraId: "starfire:ps3-eye-1", + WitnessIdHash: rightWitnessHash, + PositionMeters: new MimirVector3Snapshot(0.1, 0.0, 0.0), + Orientation: new MimirQuaternionSnapshot(0.0, 0.0, 0.0, 1.0), + FocalLengthXPx: 100.0, + FocalLengthYPx: 100.0, + PrincipalPointXPx: 160.0, + PrincipalPointYPx: 120.0) + ], + MaximumAssociationSkewMilliseconds: 20.0); + + var samples = MimirMuninnMoveEvidenceAdapter.BuildNativeSamples(markers, controllers); + var fused = MimirMoveFusion.Fuse(samples, calibration); + var uncalibrated = MimirMoveFusion.Fuse(samples, calibration with { Cameras = [] }); + var pose = fused.Poses.SingleOrDefault(); + var streamId = "mimir:starfire:move-controller-poses"; + var catalog = CultMesh.CreateStreamCatalog(); + catalog.Declare(MimirMovePoseStream.CreateStreamDescriptor( + streamId, + "mimir-live", + "mimir:starfire", + "mimir:starfire:clock", + calibration.TrackingSpaceId, + calibration.CalibrationId)); + using var ring = catalog.CreateSharedMemoryRing(streamId, slotCount: 4, slotByteLength: 8192); + var poseFrame = MimirMovePoseStream.CreateFrame( + frameId: "mimir-move-pose-frame:79", + producerPeerId: "mimir:starfire", + publishedAtNs: pose?.EstimatedAtNs ?? 0, + trackingSpaceId: calibration.TrackingSpaceId, + calibrationId: calibration.CalibrationId, + poses: fused.Poses); + var posePayload = MimirMovePoseStream.SerializeFrame(poseFrame); + var streamOk = ring.TryPublishCopy(posePayload, poseFrame.PublishedAtNs, durationNs: 0, out var published); + MimirMoveControllerPoseStreamFrame? decodedPoseFrame = null; + if (streamOk) + { + catalog.PublishFrame(published); + streamOk = ring.TryAcquireLatestRead(out var lease); + if (streamOk) + { + using (lease) + { + decodedPoseFrame = MimirMovePoseStream.DeserializeFrame(lease.Memory[..lease.Handle.ByteLength]); + } + } + } + + var positionOk = pose is not null && + Math.Abs(pose.PositionMeters.X) <= 0.025 && + Math.Abs(pose.PositionMeters.Y) <= 0.025 && + Math.Abs(pose.PositionMeters.Z - 1.0) <= 0.05; + var evidenceOk = pose is not null && + pose.EvidenceKinds.Contains("optical-marker:triangulated", StringComparer.Ordinal) && + pose.EvidenceKinds.Contains("orientation:imu-unresolved", StringComparer.Ordinal) && + pose.Buttons.Any(button => button.Id == "move" && button.Pressed) && + pose.Buttons.Any(button => button.Id == "trigger" && button.Value >= 0.49); + streamOk = streamOk && + posePayload.Length > 0 && + catalog.LatestFrame(streamId)?.Sequence == published.Sequence && + decodedPoseFrame?.Poses.Length == 1 && + decodedPoseFrame.Poses[0].PoseId == pose?.PoseId && + decodedPoseFrame.TrackingSpaceId == calibration.TrackingSpaceId && + decodedPoseFrame.CalibrationId == calibration.CalibrationId; + + Console.WriteLine( + $"move-fusion-smoke poses={fused.Poses.Count} controllers={fused.ControllerEvidenceCount} optical={fused.OpticalEvidenceCount} calibrated={fused.CalibratedOpticalEvidenceCount} uncalibratedPoses={uncalibrated.Poses.Count} streamPoses={decodedPoseFrame?.Poses.Length ?? 0} pos=({pose?.PositionMeters.X:F3},{pose?.PositionMeters.Y:F3},{pose?.PositionMeters.Z:F3}) confidence={pose?.Confidence:F3} evidence={string.Join(",", pose?.EvidenceKinds ?? [])}"); + + return fused.Poses.Count == 1 && + fused.ControllerEvidenceCount == 1 && + fused.OpticalEvidenceCount == 2 && + fused.CalibratedOpticalEvidenceCount == 2 && + uncalibrated.Poses.Count == 0 && + positionOk && + evidenceOk && + streamOk + ? 0 + : 1; +} + static MoveTrackingSmokeContext BuildMoveTrackingSmokeHub() { var starfireDescriptor = new MimirStreamDescriptor( diff --git a/src/Mimir.Runtime/Synchronization/MimirMoveFusion.cs b/src/Mimir.Runtime/Synchronization/MimirMoveFusion.cs new file mode 100644 index 0000000..3e04ba1 --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirMoveFusion.cs @@ -0,0 +1,307 @@ +using System.Numerics; + +namespace Mimir.Runtime.Synchronization; + +public sealed record MimirMoveFusionCameraCalibration( + string CameraId, + ulong WitnessIdHash, + MimirVector3Snapshot PositionMeters, + MimirQuaternionSnapshot Orientation, + double FocalLengthXPx, + double FocalLengthYPx, + double PrincipalPointXPx, + double PrincipalPointYPx); + +public sealed record MimirMoveFusionRigCalibration( + string CalibrationId, + string TrackingSpaceId, + IReadOnlyList Cameras, + double GyroUnitsPerRadianPerSecond = 1.0, + double MaximumAssociationSkewMilliseconds = 20.0, + double SingleRayFallbackDepthMeters = 1.5); + +public sealed record MimirMoveFusionResult( + IReadOnlyList Poses, + int ControllerEvidenceCount, + int OpticalEvidenceCount, + int CalibratedOpticalEvidenceCount); + +public static class MimirMoveFusion +{ + public static MimirMoveFusionResult Fuse( + IReadOnlyList samples, + MimirMoveFusionRigCalibration calibration, + string fusionAuthorityId = "mimir.runtime.move-fusion", + string consumerContract = "fensalir.move-controller-input") + { + ArgumentNullException.ThrowIfNull(samples); + ArgumentNullException.ThrowIfNull(calibration); + ArgumentException.ThrowIfNullOrWhiteSpace(calibration.CalibrationId); + ArgumentException.ThrowIfNullOrWhiteSpace(calibration.TrackingSpaceId); + + var controllerStates = samples + .Where(sample => sample.EvidenceKind == (uint)MimirNativeMoveEvidenceKind.ControllerState && + sample.ControllerIdHash != 0) + .OrderBy(sample => sample.SourceTimestampNs) + .ThenBy(sample => sample.Sequence) + .ToArray(); + var opticalMarkers = samples + .Where(sample => sample.EvidenceKind == (uint)MimirNativeMoveEvidenceKind.OpticalMarker) + .OrderBy(sample => sample.SourceTimestampNs) + .ThenBy(sample => sample.Sequence) + .ToArray(); + var cameras = calibration.Cameras + .Where(IsCameraUsable) + .ToDictionary(camera => camera.WitnessIdHash, camera => camera); + var maxSkewNs = (ulong)Math.Max(0.0, calibration.MaximumAssociationSkewMilliseconds * 1_000_000.0); + + var poses = new List(); + foreach (var controller in controllerStates) + { + var associatedMarkers = opticalMarkers + .Where(marker => IsAssociated(marker, controller, controllerStates.Length, maxSkewNs)) + .Select(marker => (Marker: marker, Camera: cameras.GetValueOrDefault(marker.WitnessIdHash))) + .Where(pair => pair.Camera is not null) + .ToArray(); + if (associatedMarkers.Length == 0) + { + continue; + } + + var rays = associatedMarkers + .Select(pair => BuildRay(pair.Camera!, pair.Marker)) + .Where(ray => ray.HasValue) + .Select(ray => ray!.Value) + .ToArray(); + if (rays.Length == 0) + { + continue; + } + + var position = rays.Length >= 2 + ? ClosestPoint(rays) + : rays[0].Origin + rays[0].Direction * (float)Math.Max(0.05, calibration.SingleRayFallbackDepthMeters); + var opticalConfidence = Math.Clamp( + associatedMarkers.Average(pair => pair.Marker.Confidence) * (rays.Length >= 2 ? 1.0 : 0.35), + 0.0, + 1.0); + var confidence = Math.Clamp(opticalConfidence * ControllerConfidence(controller), 0.0, 1.0); + var sourceNs = Math.Max(controller.SourceTimestampNs, associatedMarkers.Max(pair => pair.Marker.SourceTimestampNs)); + var arrivalNs = Math.Max(controller.ArrivalNs, associatedMarkers.Max(pair => pair.Marker.ArrivalNs)); + var evidenceStreamIds = associatedMarkers + .Select(pair => $"witness:0x{pair.Marker.WitnessIdHash:X16}") + .Append($"controller:0x{controller.ControllerIdHash:X16}") + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + var evidenceKinds = new[] + { + rays.Length >= 2 ? "optical-marker:triangulated" : "optical-marker:single-ray-depth-prior", + "controller-state:buttons-imu", + "orientation:imu-unresolved" + }; + + poses.Add(new MimirMoveControllerPoseDocument( + PoseId: $"move:0x{controller.ControllerIdHash:X16}:{controller.Sequence}", + WandId: $"move:0x{controller.ControllerIdHash:X16}", + TrackingSpaceId: calibration.TrackingSpaceId, + CalibrationId: calibration.CalibrationId, + FusionAuthorityId: fusionAuthorityId, + SourceTimestampNs: checked((long)Math.Min(sourceNs, (ulong)long.MaxValue)), + EstimatedAtNs: checked((long)Math.Min(arrivalNs, (ulong)long.MaxValue)), + Sequence: controller.Sequence, + PositionMeters: ToSnapshot(position), + Orientation: new MimirQuaternionSnapshot(0.0, 0.0, 0.0, 1.0), + LinearVelocityMetersPerSecond: new MimirVector3Snapshot(0.0, 0.0, 0.0), + AngularVelocityRadiansPerSecond: new MimirVector3Snapshot( + ScaleGyro(controller.GyroX, calibration), + ScaleGyro(controller.GyroY, calibration), + ScaleGyro(controller.GyroZ, calibration)), + Confidence: confidence, + LatencyMilliseconds: arrivalNs >= sourceNs ? (arrivalNs - sourceNs) / 1_000_000.0 : 0.0, + Battery01: float.IsFinite(controller.Battery01) ? Math.Clamp(controller.Battery01, 0.0f, 1.0f) : double.NaN, + Buttons: ButtonsFromMask(controller.ButtonsMask, controller.Trigger), + EvidenceStreamIds: evidenceStreamIds, + EvidenceKinds: evidenceKinds, + ConsumerContract: consumerContract)); + } + + return new MimirMoveFusionResult( + poses, + controllerStates.Length, + opticalMarkers.Length, + opticalMarkers.Count(marker => cameras.ContainsKey(marker.WitnessIdHash))); + } + + private static bool IsAssociated( + MimirNativeMoveEvidenceSample marker, + MimirNativeMoveEvidenceSample controller, + int controllerCount, + ulong maxSkewNs) + { + if (marker.ControllerIdHash != 0 && marker.ControllerIdHash != controller.ControllerIdHash) + { + return false; + } + + if (marker.ControllerIdHash == 0 && controllerCount != 1) + { + return false; + } + + return TimestampDelta(marker.SourceTimestampNs, controller.SourceTimestampNs) <= maxSkewNs; + } + + private static bool IsCameraUsable(MimirMoveFusionCameraCalibration camera) => + camera.WitnessIdHash != 0 && + camera.FocalLengthXPx > 0.0 && + camera.FocalLengthYPx > 0.0; + + private static MimirRay? BuildRay(MimirMoveFusionCameraCalibration camera, MimirNativeMoveEvidenceSample marker) + { + if (!float.IsFinite(marker.ImageX) || !float.IsFinite(marker.ImageY)) + { + return null; + } + + var directionCamera = Vector3.Normalize(new Vector3( + (float)((marker.ImageX - camera.PrincipalPointXPx) / camera.FocalLengthXPx), + (float)((camera.PrincipalPointYPx - marker.ImageY) / camera.FocalLengthYPx), + 1.0f)); + var orientation = ToQuaternion(camera.Orientation); + return new MimirRay( + ToVector(camera.PositionMeters), + Vector3.Normalize(Vector3.Transform(directionCamera, orientation))); + } + + private static Vector3 ClosestPoint(IReadOnlyList rays) + { + var matrix = new Matrix3(); + var rhs = Vector3.Zero; + foreach (var ray in rays) + { + var d = Vector3.Normalize(ray.Direction); + var xx = 1.0f - d.X * d.X; + var yy = 1.0f - d.Y * d.Y; + var zz = 1.0f - d.Z * d.Z; + var xy = -d.X * d.Y; + var xz = -d.X * d.Z; + var yz = -d.Y * d.Z; + matrix.M11 += xx; + matrix.M12 += xy; + matrix.M13 += xz; + matrix.M21 += xy; + matrix.M22 += yy; + matrix.M23 += yz; + matrix.M31 += xz; + matrix.M32 += yz; + matrix.M33 += zz; + rhs += new Vector3( + xx * ray.Origin.X + xy * ray.Origin.Y + xz * ray.Origin.Z, + xy * ray.Origin.X + yy * ray.Origin.Y + yz * ray.Origin.Z, + xz * ray.Origin.X + yz * ray.Origin.Y + zz * ray.Origin.Z); + } + + return matrix.TrySolve(rhs, out var solved) + ? solved + : rays[0].Origin + rays[0].Direction; + } + + private static double ControllerConfidence(MimirNativeMoveEvidenceSample controller) => + Math.Clamp( + 0.75 + + (float.IsFinite(controller.Battery01) ? 0.10 : 0.0) + + (controller.ButtonsMask != 0 ? 0.05 : 0.0) + + (Math.Abs(controller.AccelX) + Math.Abs(controller.AccelY) + Math.Abs(controller.AccelZ) > 0.001 ? 0.10 : 0.0), + 0.0, + 1.0); + + private static MimirTrackingButtonSnapshot[] ButtonsFromMask(uint mask, float trigger) + { + var names = new[] + { + "select", "l3", "r3", "start", "up", "right", "down", "left", + "l2", "r2", "l1", "r1", "triangle", "circle", "cross", "square", + "ps", "move", "trigger" + }; + var buttons = new List(); + for (var bit = 0; bit < names.Length; bit++) + { + var pressed = (mask & (1u << bit)) != 0; + if (pressed || names[bit] == "trigger") + { + buttons.Add(new MimirTrackingButtonSnapshot( + names[bit], + pressed, + names[bit] == "trigger" ? Math.Clamp(trigger, 0.0f, 1.0f) : pressed ? 1.0 : 0.0)); + } + } + + return buttons.ToArray(); + } + + private static ulong TimestampDelta(ulong left, ulong right) => left >= right ? left - right : right - left; + + private static double ScaleGyro(float value, MimirMoveFusionRigCalibration calibration) => + calibration.GyroUnitsPerRadianPerSecond <= 0.0 + ? 0.0 + : value / calibration.GyroUnitsPerRadianPerSecond; + + private static Vector3 ToVector(MimirVector3Snapshot value) => new((float)value.X, (float)value.Y, (float)value.Z); + + private static MimirVector3Snapshot ToSnapshot(Vector3 value) => new(value.X, value.Y, value.Z); + + private static Quaternion ToQuaternion(MimirQuaternionSnapshot value) + { + var q = new Quaternion((float)value.X, (float)value.Y, (float)value.Z, (float)value.W); + return q.LengthSquared() <= 1.0e-12f ? Quaternion.Identity : Quaternion.Normalize(q); + } + + private readonly record struct MimirRay(Vector3 Origin, Vector3 Direction); + + private struct Matrix3 + { + public float M11; + public float M12; + public float M13; + public float M21; + public float M22; + public float M23; + public float M31; + public float M32; + public float M33; + + public readonly bool TrySolve(Vector3 rhs, out Vector3 value) + { + var det = Determinant( + M11, M12, M13, + M21, M22, M23, + M31, M32, M33); + if (Math.Abs(det) <= 1.0e-8f) + { + value = default; + return false; + } + + value = new Vector3( + Determinant(rhs.X, M12, M13, rhs.Y, M22, M23, rhs.Z, M32, M33) / det, + Determinant(M11, rhs.X, M13, M21, rhs.Y, M23, M31, rhs.Z, M33) / det, + Determinant(M11, M12, rhs.X, M21, M22, rhs.Y, M31, M32, rhs.Z) / det); + return true; + } + + private static float Determinant( + float m11, + float m12, + float m13, + float m21, + float m22, + float m23, + float m31, + float m32, + float m33) => + m11 * (m22 * m33 - m23 * m32) - + m12 * (m21 * m33 - m23 * m31) + + m13 * (m21 * m32 - m22 * m31); + } +} diff --git a/src/Mimir.Runtime/Synchronization/MimirMovePoseStream.cs b/src/Mimir.Runtime/Synchronization/MimirMovePoseStream.cs new file mode 100644 index 0000000..919cdd7 --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirMovePoseStream.cs @@ -0,0 +1,71 @@ +using GameCult.Mesh; +using MessagePack; + +namespace Mimir.Runtime.Synchronization; + +[MessagePackObject] +public sealed record MimirMoveControllerPoseStreamFrame( + [property: Key(0)] string FrameId, + [property: Key(1)] string ProducerPeerId, + [property: Key(2)] long PublishedAtNs, + [property: Key(3)] string TrackingSpaceId, + [property: Key(4)] string CalibrationId, + [property: Key(5)] MimirMoveControllerPoseDocument[] Poses); + +public static class MimirMovePoseStream +{ + public const string StreamMetadataSchemaId = "mimir.move_controller_pose_stream_frame.v1"; + + public static CultMeshStreamDescriptor CreateStreamDescriptor( + string streamId, + string verseId, + string ownerPeerId, + string clockDomainId, + string trackingSpaceId, + string calibrationId) => + new( + streamId, + verseId, + ownerPeerId, + CultMeshStreamKind.Bytes, + new CultMeshStreamClock(clockDomainId, sourceId: streamId, confidence: 1.0, evidenceKind: "mimir-move-controller-pose"), + [CultMeshStreamBodyTransport.SharedMemory, CultMeshStreamBodyTransport.CultCachePage], + label: $"Mimir Move controller poses ({trackingSpaceId}, {calibrationId})", + requiredAccess: CultMeshStreamAccess.Read, + maxInFlightFrames: 4, + metadataSchemaId: StreamMetadataSchemaId); + + public static MimirMoveControllerPoseStreamFrame CreateFrame( + string frameId, + string producerPeerId, + long publishedAtNs, + string trackingSpaceId, + string calibrationId, + IEnumerable poses) + { + ArgumentException.ThrowIfNullOrWhiteSpace(frameId); + ArgumentException.ThrowIfNullOrWhiteSpace(producerPeerId); + ArgumentException.ThrowIfNullOrWhiteSpace(trackingSpaceId); + ArgumentException.ThrowIfNullOrWhiteSpace(calibrationId); + ArgumentNullException.ThrowIfNull(poses); + + return new MimirMoveControllerPoseStreamFrame( + frameId, + producerPeerId, + publishedAtNs, + trackingSpaceId, + calibrationId, + poses + .Where(pose => string.Equals(pose.TrackingSpaceId, trackingSpaceId, StringComparison.Ordinal) && + string.Equals(pose.CalibrationId, calibrationId, StringComparison.Ordinal)) + .OrderBy(pose => pose.SourceTimestampNs) + .ThenBy(pose => pose.Sequence) + .ToArray()); + } + + public static byte[] SerializeFrame(MimirMoveControllerPoseStreamFrame frame) => + MessagePackSerializer.Serialize(frame); + + public static MimirMoveControllerPoseStreamFrame DeserializeFrame(ReadOnlyMemory bytes) => + MessagePackSerializer.Deserialize(bytes); +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 02e184d..c4451ac 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -134,3 +134,4 @@ {"ts": "2026-06-11T19:27:48+01:00", "type": "implementation", "status": "ok", "note": "Connected Mimir.Runtime to the native Move evidence reservoir: MimirNativeReservoirRuntime loads localcast_reservoir, pins Move evidence sample/descriptor batches, admits them through localcast_producer_push_move_evidence_buffer, and BufferSmoke --move-native-reservoir-smoke proves a marker plus controller-state batch enters the native move_evidence view."} {"ts": "2026-06-11T19:58:56+01:00", "type": "implementation", "status": "ok", "note": "Added Mimir-side Muninn Move evidence normalization: muninn.move_marker_candidate.v1 and muninn.move_controller_state.v1 documents now map into native Move evidence samples, and BufferSmoke --muninn-move-evidence-smoke proves two optical candidates plus one controller-state record enter the native move_evidence reservoir view."} {"ts": "2026-06-11T20:26:19+01:00", "type": "correction", "status": "ok", "note": "Corrected the Move witness live path from CultCache polling to CultMesh streaming: MimirMuninnMoveEvidenceAdapter now creates/consumes Muninn Move shared-memory stream frames, BufferSmoke --muninn-move-cultmesh-stream-smoke proves a CultMesh latest-frame read lease normalizes into native move_evidence, and CultCache remains receipt/debug state rather than the hot tracking feed."} +{"ts": "2026-06-12T14:08:32+01:00", "type": "implementation", "status": "ok", "note": "Added MimirMoveFusion as the first calibrated Move pose owner and MimirMovePoseStream as the realtime output frame: native Muninn Move evidence samples are associated against USB controller state, calibrated multi-camera orb rays triangulate position into mimir.move_controller_pose.v1, controller buttons/trigger/gyro are carried forward, orientation is explicitly marked imu-unresolved, and BufferSmoke --move-fusion-smoke proves the positive calibrated pose path, the negative no-calibration/no-pose guard, and a CultMesh pose-stream roundtrip."} diff --git a/state/map.yaml b/state/map.yaml index af1abd7..af75a17 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -103,6 +103,16 @@ accepted_design: - `mimir.move_controller_pose.v1` is Mimir's resolved wand pose contract for Fensalir-facing interaction. Mimir owns calibration, association, triangulation, IMU fusion, prediction, confidence, and latency accounting. + - `MimirMoveFusion` is the current Move pose owner. It consumes native Muninn + Move evidence samples, refuses to publish poses without calibrated optical + witnesses, triangulates multi-camera orb position, carries controller + buttons/trigger/gyro into `mimir.move_controller_pose.v1`, and marks + orientation as `orientation:imu-unresolved` until IMU fusion/prediction + earns a full 6DoF controller contract. + - `MimirMovePoseStream` publishes resolved Mimir-owned Move poses as + `mimir.move_controller_pose_stream_frame.v1` CultMesh shared-memory byte + frames for Fensalir and other realtime consumers; it carries poses and does + not own calibration or fusion decisions. - `scripts/start-nightwing-move-tracking.ps1` restores the live Nightwing Eye/Move witness path: Starfire owns the `/eve/periwinkle` receiver and recorder, Nightwing owns PS Move HID report `0x06` LED writes and PS3 Eye