Muninn has one body: drop the workspace copy
The three muninn crates, their seventeen actuator scripts, the two Raven capture-mux wrappers that called one of them, and the two Muninn docs all leave this workspace. GameCult/Muninn has carried them since 2026-09-09 and has moved on (media stream advertisement, receivers dialling the producer); this copy was a fork drifting behind under the same name, and gamecult-ops now binds every Muninn target to the Muninn repository. Odin keeps the Muninn records in odin-core until they are moved; that is the remaining piece of the extraction. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
1ff6a323de
commit
d41c744b2e
34 changed files with 4 additions and 22638 deletions
|
|
@ -1,40 +0,0 @@
|
|||
[package]
|
||||
name = "muninn-daemon"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
psmoveapi-tracker = ["dep:muninn-psmoveapi-tracker"]
|
||||
|
||||
[[bin]]
|
||||
name = "muninn"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a8aeddacab7dd4b9e634b4420867ea3b402cb858", package = "cultmesh-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a8aeddacab7dd4b9e634b4420867ea3b402cb858", package = "cultnet-rs" }
|
||||
libc = "0.2"
|
||||
muninn-move-tracker = { path = "../muninn-move-tracker" }
|
||||
muninn-psmoveapi-tracker = { path = "../muninn-psmoveapi-tracker", optional = true }
|
||||
odin-core = { path = "../odin-core" }
|
||||
rmp-serde = "1.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_bytes = "0.11"
|
||||
serde_json = "1"
|
||||
socket2 = "0.5"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.59", features = [
|
||||
"Win32_Devices_DeviceAndDriverInstallation",
|
||||
"Win32_Devices_HumanInterfaceDevice",
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_IO",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_Input_XboxController",
|
||||
] }
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,11 +0,0 @@
|
|||
[package]
|
||||
name = "muninn-move-tracker"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Muninn-owned Rust orchestration and CPU mirror for PS Move marker candidate extraction"
|
||||
|
||||
[lib]
|
||||
name = "muninn_move_tracker"
|
||||
crate-type = ["rlib", "cdylib", "staticlib"]
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
# Muninn Move Tracker
|
||||
|
||||
Muninn owns PS Move sensor stream exposure. This crate is Muninn's first native
|
||||
optical marker candidate extractor: Rust owns orchestration, FFI, validation,
|
||||
and the CPU mirror; the compute shader owns the parallel image reduction stage.
|
||||
The shader includes CultMath's canonical HLSL mirror, so shader compilation must
|
||||
add `E:\Projects\CultLib\packages\cultmath\shaders` or the packaged CultMath shader content to
|
||||
the include path.
|
||||
|
||||
This crate deliberately stops at per-frame marker candidates. Final pose,
|
||||
stereo triangulation, controller association, IMU fusion, prediction, and
|
||||
calibration remain separate later owners. Mimir consumes Muninn-emitted typed
|
||||
candidate/observation streams; it does not own raw optical extraction.
|
||||
|
||||
## Current Contract
|
||||
|
||||
- Input: one luma frame (`Y8`) with width, height, stride, source hash, and frame
|
||||
sequence.
|
||||
- GPU stage: one 16px tile per thread group, emitting at most one candidate per
|
||||
tile.
|
||||
- Output: `MoveMarkerCandidate` records containing weighted centroid, radius,
|
||||
area, peak/mean luma, and score.
|
||||
- Rust mirror: deterministic CPU implementation and FFI wrappers for tests and
|
||||
non-GPU smoke paths.
|
||||
- FFI prefix: `muninn_move_tracker_*`.
|
||||
- Shader IDs are carried as `uint2` low/high pairs to avoid making 64-bit HLSL
|
||||
integer support a dependency of the first extraction pass.
|
||||
|
||||
This is the first stage required for PlayStation-class wand tracking. The
|
||||
remaining stack needs calibrated camera rays, controlled sphere colors/exposure,
|
||||
multi-camera association, triangulation, IMU fusion, and latency prediction.
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
// Muninn PS Move sphere candidate extraction.
|
||||
// One thread group owns one image tile. The shader emits at most one bright
|
||||
// marker candidate per 16px tile; Rust owns dispatch sizing and downstream ranking.
|
||||
|
||||
#include "CultMath.hlsl"
|
||||
|
||||
struct MoveSphereCandidate
|
||||
{
|
||||
uint2 sourceIdHash;
|
||||
uint2 frameSequence;
|
||||
uint tileX;
|
||||
uint tileY;
|
||||
float centerXPx;
|
||||
float centerYPx;
|
||||
float radiusPx;
|
||||
uint areaPx;
|
||||
float meanLuma;
|
||||
uint peakLuma;
|
||||
float score;
|
||||
};
|
||||
|
||||
cbuffer MoveTrackerConfig : register(b0)
|
||||
{
|
||||
uint width;
|
||||
uint height;
|
||||
uint strideBytes;
|
||||
uint tileSize;
|
||||
uint thresholdMin;
|
||||
uint minAreaPx;
|
||||
uint maxCandidates;
|
||||
uint _pad0;
|
||||
uint2 sourceIdHash;
|
||||
uint2 frameSequence;
|
||||
};
|
||||
|
||||
ByteAddressBuffer frameY8 : register(t0);
|
||||
RWStructuredBuffer<MoveSphereCandidate> candidates : register(u0);
|
||||
RWByteAddressBuffer candidateCounter : register(u1);
|
||||
|
||||
groupshared uint gArea;
|
||||
groupshared uint gSumX;
|
||||
groupshared uint gSumY;
|
||||
groupshared uint gSumW;
|
||||
groupshared uint gPeak;
|
||||
|
||||
[numthreads(16, 16, 1)]
|
||||
void main(uint3 groupId : SV_GroupID, uint3 groupThreadId : SV_GroupThreadID)
|
||||
{
|
||||
if (groupThreadId.x == 0 && groupThreadId.y == 0)
|
||||
{
|
||||
gArea = 0;
|
||||
gSumX = 0;
|
||||
gSumY = 0;
|
||||
gSumW = 0;
|
||||
gPeak = 0;
|
||||
}
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
uint x = groupId.x * tileSize + groupThreadId.x;
|
||||
uint y = groupId.y * tileSize + groupThreadId.y;
|
||||
if (groupThreadId.x < tileSize && groupThreadId.y < tileSize && x < width && y < height)
|
||||
{
|
||||
uint byteOffset = y * strideBytes + x;
|
||||
uint packed = frameY8.Load(byteOffset & ~3u);
|
||||
uint shift = (byteOffset & 3u) * 8u;
|
||||
uint luma = (packed >> shift) & 0xffu;
|
||||
if (luma >= thresholdMin)
|
||||
{
|
||||
uint weight = luma - thresholdMin + 1u;
|
||||
InterlockedAdd(gArea, 1u);
|
||||
InterlockedAdd(gSumX, x * weight);
|
||||
InterlockedAdd(gSumY, y * weight);
|
||||
InterlockedAdd(gSumW, weight);
|
||||
InterlockedMax(gPeak, luma);
|
||||
}
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
if (groupThreadId.x == 0 && groupThreadId.y == 0 && gArea >= minAreaPx && gSumW > 0)
|
||||
{
|
||||
uint index;
|
||||
candidateCounter.InterlockedAdd(0, 1, index);
|
||||
if (index < maxCandidates)
|
||||
{
|
||||
float area = (float)gArea;
|
||||
float tilePixels = (float)(tileSize * tileSize);
|
||||
float areaScore = cultmath_saturate(area / tilePixels);
|
||||
float brightnessScore = (float)gPeak / 255.0;
|
||||
|
||||
MoveSphereCandidate candidate;
|
||||
candidate.sourceIdHash = sourceIdHash;
|
||||
candidate.frameSequence = frameSequence;
|
||||
candidate.tileX = groupId.x;
|
||||
candidate.tileY = groupId.y;
|
||||
candidate.centerXPx = (float)gSumX / (float)gSumW;
|
||||
candidate.centerYPx = (float)gSumY / (float)gSumW;
|
||||
candidate.radiusPx = sqrt(area / 3.14159265358979323846);
|
||||
candidate.areaPx = gArea;
|
||||
candidate.meanLuma = (float)thresholdMin + (((float)gSumW / area) - 1.0);
|
||||
candidate.peakLuma = gPeak;
|
||||
candidate.score = brightnessScore * (0.65 + areaScore * 0.35);
|
||||
candidates[index] = candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,308 +0,0 @@
|
|||
#![deny(unsafe_op_in_unsafe_fn)]
|
||||
|
||||
use core::ffi::c_int;
|
||||
|
||||
pub const MUNINN_MOVE_TRACKER_OK: c_int = 0;
|
||||
pub const MUNINN_MOVE_TRACKER_NULL: c_int = -1;
|
||||
pub const MUNINN_MOVE_TRACKER_INVALID: c_int = -2;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct MoveTrackerConfig {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub stride_bytes: u32,
|
||||
pub tile_size: u32,
|
||||
pub threshold_min: u8,
|
||||
pub min_area_px: u32,
|
||||
pub max_candidates: u32,
|
||||
pub source_id_hash: u64,
|
||||
pub frame_sequence: u64,
|
||||
}
|
||||
|
||||
impl Default for MoveTrackerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: 320,
|
||||
height: 240,
|
||||
stride_bytes: 320,
|
||||
tile_size: 16,
|
||||
threshold_min: 180,
|
||||
min_area_px: 4,
|
||||
max_candidates: 64,
|
||||
source_id_hash: 0,
|
||||
frame_sequence: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct MoveTrackerDispatchPlan {
|
||||
pub group_size_x: u32,
|
||||
pub group_size_y: u32,
|
||||
pub groups_x: u32,
|
||||
pub groups_y: u32,
|
||||
pub max_candidates: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct MoveMarkerCandidate {
|
||||
pub source_id_hash: u64,
|
||||
pub frame_sequence: u64,
|
||||
pub tile_x: u32,
|
||||
pub tile_y: u32,
|
||||
pub center_x_px: f32,
|
||||
pub center_y_px: f32,
|
||||
pub radius_px: f32,
|
||||
pub area_px: u32,
|
||||
pub mean_luma: f32,
|
||||
pub peak_luma: u32,
|
||||
pub score: f32,
|
||||
}
|
||||
|
||||
pub fn dispatch_plan(config: MoveTrackerConfig) -> Option<MoveTrackerDispatchPlan> {
|
||||
if !config_is_valid(config) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let tile = config.tile_size;
|
||||
Some(MoveTrackerDispatchPlan {
|
||||
group_size_x: tile,
|
||||
group_size_y: tile,
|
||||
groups_x: config.width.div_ceil(tile),
|
||||
groups_y: config.height.div_ceil(tile),
|
||||
max_candidates: config.max_candidates,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn extract_luma_candidates(
|
||||
frame: &[u8],
|
||||
config: MoveTrackerConfig,
|
||||
) -> Option<Vec<MoveMarkerCandidate>> {
|
||||
if !config_is_valid(config) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let required = required_frame_bytes(config)?;
|
||||
if frame.len() < required {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
let tile = config.tile_size;
|
||||
let groups_x = config.width.div_ceil(tile);
|
||||
let groups_y = config.height.div_ceil(tile);
|
||||
|
||||
for tile_y in 0..groups_y {
|
||||
for tile_x in 0..groups_x {
|
||||
if candidates.len() >= config.max_candidates as usize {
|
||||
return Some(candidates);
|
||||
}
|
||||
|
||||
if let Some(candidate) = extract_tile(frame, config, tile_x, tile_y) {
|
||||
candidates.push(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
candidates.sort_by(|left, right| {
|
||||
right
|
||||
.score
|
||||
.partial_cmp(&left.score)
|
||||
.unwrap_or(core::cmp::Ordering::Equal)
|
||||
});
|
||||
Some(candidates)
|
||||
}
|
||||
|
||||
fn extract_tile(
|
||||
frame: &[u8],
|
||||
config: MoveTrackerConfig,
|
||||
tile_x: u32,
|
||||
tile_y: u32,
|
||||
) -> Option<MoveMarkerCandidate> {
|
||||
let x0 = tile_x * config.tile_size;
|
||||
let y0 = tile_y * config.tile_size;
|
||||
let x1 = (x0 + config.tile_size).min(config.width);
|
||||
let y1 = (y0 + config.tile_size).min(config.height);
|
||||
let threshold = u32::from(config.threshold_min);
|
||||
let mut area = 0u32;
|
||||
let mut sum_x = 0u64;
|
||||
let mut sum_y = 0u64;
|
||||
let mut sum_w = 0u64;
|
||||
let mut peak = 0u32;
|
||||
|
||||
for y in y0..y1 {
|
||||
let row = y as usize * config.stride_bytes as usize;
|
||||
for x in x0..x1 {
|
||||
let luma = u32::from(frame[row + x as usize]);
|
||||
if luma < threshold {
|
||||
continue;
|
||||
}
|
||||
|
||||
area += 1;
|
||||
peak = peak.max(luma);
|
||||
let weight = u64::from(luma - threshold + 1);
|
||||
sum_x += u64::from(x) * weight;
|
||||
sum_y += u64::from(y) * weight;
|
||||
sum_w += weight;
|
||||
}
|
||||
}
|
||||
|
||||
if area < config.min_area_px || sum_w == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let center_x = sum_x as f32 / sum_w as f32;
|
||||
let center_y = sum_y as f32 / sum_w as f32;
|
||||
let radius = (area as f32 / core::f32::consts::PI).sqrt();
|
||||
let mean_luma = threshold as f32 + ((sum_w as f32 / area as f32) - 1.0);
|
||||
let area_score = (area as f32 / (config.tile_size * config.tile_size) as f32).min(1.0);
|
||||
let brightness_score = peak as f32 / 255.0;
|
||||
|
||||
Some(MoveMarkerCandidate {
|
||||
source_id_hash: config.source_id_hash,
|
||||
frame_sequence: config.frame_sequence,
|
||||
tile_x,
|
||||
tile_y,
|
||||
center_x_px: center_x,
|
||||
center_y_px: center_y,
|
||||
radius_px: radius,
|
||||
area_px: area,
|
||||
mean_luma,
|
||||
peak_luma: peak,
|
||||
score: brightness_score * (0.65 + area_score * 0.35),
|
||||
})
|
||||
}
|
||||
|
||||
fn config_is_valid(config: MoveTrackerConfig) -> bool {
|
||||
config.width > 0
|
||||
&& config.height > 0
|
||||
&& config.stride_bytes >= config.width
|
||||
&& config.tile_size == 16
|
||||
&& config.min_area_px > 0
|
||||
&& config.max_candidates > 0
|
||||
}
|
||||
|
||||
fn required_frame_bytes(config: MoveTrackerConfig) -> Option<usize> {
|
||||
let rows = usize::try_from(config.height).ok()?;
|
||||
let stride = usize::try_from(config.stride_bytes).ok()?;
|
||||
rows.checked_mul(stride)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn muninn_move_tracker_dispatch_plan(
|
||||
config: MoveTrackerConfig,
|
||||
out_plan: *mut MoveTrackerDispatchPlan,
|
||||
) -> c_int {
|
||||
if out_plan.is_null() {
|
||||
return MUNINN_MOVE_TRACKER_NULL;
|
||||
}
|
||||
|
||||
let Some(plan) = dispatch_plan(config) else {
|
||||
return MUNINN_MOVE_TRACKER_INVALID;
|
||||
};
|
||||
|
||||
unsafe {
|
||||
*out_plan = plan;
|
||||
}
|
||||
MUNINN_MOVE_TRACKER_OK
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn muninn_move_tracker_extract_luma_cpu(
|
||||
config: MoveTrackerConfig,
|
||||
frame: *const u8,
|
||||
frame_len: usize,
|
||||
out_candidates: *mut MoveMarkerCandidate,
|
||||
out_capacity: usize,
|
||||
out_count: *mut usize,
|
||||
) -> c_int {
|
||||
if frame.is_null() || out_candidates.is_null() || out_count.is_null() {
|
||||
return MUNINN_MOVE_TRACKER_NULL;
|
||||
}
|
||||
|
||||
let frame = unsafe { core::slice::from_raw_parts(frame, frame_len) };
|
||||
let Some(candidates) = extract_luma_candidates(frame, config) else {
|
||||
return MUNINN_MOVE_TRACKER_INVALID;
|
||||
};
|
||||
|
||||
let written = candidates.len().min(out_capacity);
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(candidates.as_ptr(), out_candidates, written);
|
||||
*out_count = written;
|
||||
}
|
||||
MUNINN_MOVE_TRACKER_OK
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dispatch_plan_covers_partial_tiles() {
|
||||
let config = MoveTrackerConfig {
|
||||
width: 33,
|
||||
height: 17,
|
||||
stride_bytes: 40,
|
||||
tile_size: 16,
|
||||
..MoveTrackerConfig::default()
|
||||
};
|
||||
|
||||
let plan = dispatch_plan(config).expect("valid plan");
|
||||
assert_eq!(3, plan.groups_x);
|
||||
assert_eq!(2, plan.groups_y);
|
||||
assert_eq!(16, plan.group_size_x);
|
||||
assert_eq!(16, plan.group_size_y);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_weighted_marker_candidate() {
|
||||
let config = MoveTrackerConfig {
|
||||
width: 32,
|
||||
height: 24,
|
||||
stride_bytes: 32,
|
||||
tile_size: 16,
|
||||
threshold_min: 180,
|
||||
min_area_px: 3,
|
||||
max_candidates: 8,
|
||||
source_id_hash: 42,
|
||||
frame_sequence: 7,
|
||||
};
|
||||
let mut frame = vec![0u8; (config.stride_bytes * config.height) as usize];
|
||||
for (x, y, luma) in [
|
||||
(10u32, 8u32, 230u8),
|
||||
(11, 8, 250),
|
||||
(10, 9, 240),
|
||||
(11, 9, 255),
|
||||
] {
|
||||
frame[(y * config.stride_bytes + x) as usize] = luma;
|
||||
}
|
||||
|
||||
let candidates = extract_luma_candidates(&frame, config).expect("candidates");
|
||||
assert_eq!(1, candidates.len());
|
||||
let candidate = candidates[0];
|
||||
assert_eq!(42, candidate.source_id_hash);
|
||||
assert_eq!(7, candidate.frame_sequence);
|
||||
assert_eq!(0, candidate.tile_x);
|
||||
assert_eq!(0, candidate.tile_y);
|
||||
assert_eq!(4, candidate.area_px);
|
||||
assert_eq!(255, candidate.peak_luma);
|
||||
assert!(candidate.center_x_px > 10.4 && candidate.center_x_px < 10.7);
|
||||
assert!(candidate.center_y_px > 8.4 && candidate.center_y_px < 8.7);
|
||||
assert!(candidate.score > 0.65);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_short_frames_and_empty_config() {
|
||||
assert!(extract_luma_candidates(&[], MoveTrackerConfig::default()).is_none());
|
||||
assert!(
|
||||
dispatch_plan(MoveTrackerConfig {
|
||||
width: 0,
|
||||
..MoveTrackerConfig::default()
|
||||
})
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
[package]
|
||||
name = "muninn-psmoveapi-tracker"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Safe Muninn ownership wrapper for the upstream PSMoveAPI tracker ABI"
|
||||
|
||||
[lib]
|
||||
name = "muninn_psmoveapi_tracker"
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -1,359 +0,0 @@
|
|||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PsmoveApiObservation {
|
||||
pub move_id: String,
|
||||
pub center_x_px: f32,
|
||||
pub center_y_px: f32,
|
||||
pub radius_px: f32,
|
||||
pub age_ms: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PsmoveApiCameraInfo {
|
||||
pub name: String,
|
||||
pub api: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub exposure: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PsmoveApiTrackerError(pub String);
|
||||
|
||||
impl core::fmt::Display for PsmoveApiTrackerError {
|
||||
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
formatter.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PsmoveApiTrackerError {}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux {
|
||||
use super::{PsmoveApiCameraInfo, PsmoveApiObservation, PsmoveApiTrackerError};
|
||||
use core::ffi::{c_char, c_float, c_int, c_uchar, c_void};
|
||||
use std::ffi::CStr;
|
||||
|
||||
const TRACKER_CALIBRATED: c_int = 2;
|
||||
|
||||
#[repr(C)]
|
||||
struct CameraInfo {
|
||||
camera_name: *const c_char,
|
||||
camera_api: *const c_char,
|
||||
width: c_int,
|
||||
height: c_int,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct TrackerRgbImage {
|
||||
data: *const u8,
|
||||
width: c_int,
|
||||
height: c_int,
|
||||
}
|
||||
|
||||
#[link(name = "psmoveapi")]
|
||||
#[link(name = "psmoveapi_tracker")]
|
||||
unsafe extern "C" {
|
||||
fn psmove_count_connected() -> c_int;
|
||||
fn psmove_connect_by_id(id: c_int) -> *mut c_void;
|
||||
fn psmove_get_serial(controller: *mut c_void) -> *const c_char;
|
||||
fn psmove_disconnect(controller: *mut c_void);
|
||||
fn psmove_tracker_new_with_camera(camera: c_int) -> *mut c_void;
|
||||
fn psmove_tracker_free(tracker: *mut c_void);
|
||||
fn psmove_tracker_enable_color_observer(
|
||||
tracker: *mut c_void,
|
||||
controller: *mut c_void,
|
||||
red: c_uchar,
|
||||
green: c_uchar,
|
||||
blue: c_uchar,
|
||||
) -> c_int;
|
||||
fn psmove_tracker_set_expected_color(
|
||||
tracker: *mut c_void,
|
||||
controller: *mut c_void,
|
||||
red: c_uchar,
|
||||
green: c_uchar,
|
||||
blue: c_uchar,
|
||||
) -> bool;
|
||||
fn psmove_tracker_disable(tracker: *mut c_void, controller: *mut c_void);
|
||||
fn psmove_tracker_set_exposure(tracker: *mut c_void, exposure: c_float);
|
||||
fn psmove_tracker_get_exposure(tracker: *mut c_void) -> c_float;
|
||||
fn psmove_tracker_update_image(tracker: *mut c_void);
|
||||
fn psmove_tracker_update(tracker: *mut c_void, controller: *mut c_void) -> c_int;
|
||||
fn psmove_tracker_get_position(
|
||||
tracker: *mut c_void,
|
||||
controller: *mut c_void,
|
||||
x: *mut c_float,
|
||||
y: *mut c_float,
|
||||
radius: *mut c_float,
|
||||
) -> c_int;
|
||||
fn psmove_tracker_get_camera_info(tracker: *mut c_void) -> *const CameraInfo;
|
||||
fn psmove_tracker_get_image(tracker: *mut c_void) -> TrackerRgbImage;
|
||||
}
|
||||
|
||||
struct Controller {
|
||||
handle: *mut c_void,
|
||||
move_id: String,
|
||||
}
|
||||
|
||||
pub struct PsmoveApiTracker {
|
||||
tracker: *mut c_void,
|
||||
controllers: Vec<Controller>,
|
||||
colors: Vec<(String, [u8; 3])>,
|
||||
camera_info: PsmoveApiCameraInfo,
|
||||
}
|
||||
|
||||
impl PsmoveApiTracker {
|
||||
pub fn open(
|
||||
camera_index: i32,
|
||||
exposure: f32,
|
||||
colors: &[(String, [u8; 3])],
|
||||
) -> Result<Self, PsmoveApiTrackerError> {
|
||||
if !(0.0..=1.0).contains(&exposure) {
|
||||
return Err(PsmoveApiTrackerError(format!(
|
||||
"PSMoveAPI exposure must be within 0..=1, got {exposure}"
|
||||
)));
|
||||
}
|
||||
let tracker = unsafe { psmove_tracker_new_with_camera(camera_index) };
|
||||
if tracker.is_null() {
|
||||
return Err(PsmoveApiTrackerError(format!(
|
||||
"PSMoveAPI could not open camera index {camera_index}"
|
||||
)));
|
||||
}
|
||||
unsafe { psmove_tracker_set_exposure(tracker, exposure) };
|
||||
|
||||
let mut result = Self {
|
||||
tracker,
|
||||
controllers: Vec::new(),
|
||||
colors: colors.to_vec(),
|
||||
camera_info: PsmoveApiCameraInfo {
|
||||
name: "unknown".to_string(),
|
||||
api: "unknown".to_string(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
exposure,
|
||||
},
|
||||
};
|
||||
result.observe_connected();
|
||||
result.camera_info = unsafe {
|
||||
let info = psmove_tracker_get_camera_info(tracker);
|
||||
if info.is_null() {
|
||||
PsmoveApiCameraInfo {
|
||||
exposure: psmove_tracker_get_exposure(tracker),
|
||||
..result.camera_info.clone()
|
||||
}
|
||||
} else {
|
||||
PsmoveApiCameraInfo {
|
||||
name: text((*info).camera_name),
|
||||
api: text((*info).camera_api),
|
||||
width: (*info).width.max(0) as u32,
|
||||
height: (*info).height.max(0) as u32,
|
||||
exposure: psmove_tracker_get_exposure(tracker),
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn calibrate_connected(&mut self) -> usize {
|
||||
self.observe_connected()
|
||||
}
|
||||
|
||||
pub fn observe_connected(&mut self) -> usize {
|
||||
let count = unsafe { psmove_count_connected() }.max(0);
|
||||
for index in 0..count {
|
||||
let handle = unsafe { psmove_connect_by_id(index) };
|
||||
if handle.is_null() {
|
||||
continue;
|
||||
}
|
||||
let serial = unsafe { text(psmove_get_serial(handle)) };
|
||||
let move_id = format!("move-{}", serial.replace(':', "").to_ascii_lowercase());
|
||||
if self
|
||||
.controllers
|
||||
.iter()
|
||||
.any(|controller| controller.move_id == move_id)
|
||||
{
|
||||
unsafe { psmove_disconnect(handle) };
|
||||
continue;
|
||||
}
|
||||
let Some((_, color)) = self
|
||||
.colors
|
||||
.iter()
|
||||
.find(|(identity, _)| identity.eq_ignore_ascii_case(&move_id))
|
||||
else {
|
||||
unsafe { psmove_disconnect(handle) };
|
||||
continue;
|
||||
};
|
||||
let status = unsafe {
|
||||
psmove_tracker_enable_color_observer(
|
||||
self.tracker,
|
||||
handle,
|
||||
color[0],
|
||||
color[1],
|
||||
color[2],
|
||||
)
|
||||
};
|
||||
if status == TRACKER_CALIBRATED {
|
||||
self.controllers.push(Controller { handle, move_id });
|
||||
} else {
|
||||
unsafe { psmove_disconnect(handle) };
|
||||
}
|
||||
}
|
||||
|
||||
self.controllers.len()
|
||||
}
|
||||
|
||||
pub fn set_expected_color(&mut self, move_id: &str, color: [u8; 3]) -> bool {
|
||||
let Some(controller) = self
|
||||
.controllers
|
||||
.iter()
|
||||
.find(|controller| controller.move_id.eq_ignore_ascii_case(move_id))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
unsafe {
|
||||
psmove_tracker_set_expected_color(
|
||||
self.tracker,
|
||||
controller.handle,
|
||||
color[0],
|
||||
color[1],
|
||||
color[2],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn camera_info(&self) -> &PsmoveApiCameraInfo {
|
||||
&self.camera_info
|
||||
}
|
||||
|
||||
pub fn tracked_controller_count(&self) -> usize {
|
||||
self.controllers.len()
|
||||
}
|
||||
|
||||
pub fn update(&mut self) -> Vec<PsmoveApiObservation> {
|
||||
unsafe { psmove_tracker_update_image(self.tracker) };
|
||||
let mut observations = Vec::new();
|
||||
for controller in &self.controllers {
|
||||
unsafe { psmove_tracker_update(self.tracker, controller.handle) };
|
||||
let mut x = 0.0;
|
||||
let mut y = 0.0;
|
||||
let mut radius = 0.0;
|
||||
let age_ms = unsafe {
|
||||
psmove_tracker_get_position(
|
||||
self.tracker,
|
||||
controller.handle,
|
||||
&mut x,
|
||||
&mut y,
|
||||
&mut radius,
|
||||
)
|
||||
};
|
||||
if age_ms >= 0 && radius > 0.0 {
|
||||
observations.push(PsmoveApiObservation {
|
||||
move_id: controller.move_id.clone(),
|
||||
center_x_px: x,
|
||||
center_y_px: y,
|
||||
radius_px: radius,
|
||||
age_ms,
|
||||
});
|
||||
}
|
||||
}
|
||||
observations
|
||||
}
|
||||
|
||||
pub fn rgb_image(&self) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let image = unsafe { psmove_tracker_get_image(self.tracker) };
|
||||
if image.data.is_null() || image.width <= 0 || image.height <= 0 {
|
||||
return None;
|
||||
}
|
||||
let byte_len = (image.width as usize)
|
||||
.checked_mul(image.height as usize)?
|
||||
.checked_mul(3)?;
|
||||
let bytes = unsafe { core::slice::from_raw_parts(image.data, byte_len) };
|
||||
Some((image.width as u32, image.height as u32, bytes.to_vec()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PsmoveApiTracker {
|
||||
fn drop(&mut self) {
|
||||
for controller in self.controllers.drain(..) {
|
||||
unsafe {
|
||||
psmove_tracker_disable(self.tracker, controller.handle);
|
||||
psmove_disconnect(controller.handle);
|
||||
}
|
||||
}
|
||||
unsafe { psmove_tracker_free(self.tracker) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn text(value: *const c_char) -> String {
|
||||
if value.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
unsafe { CStr::from_ptr(value) }
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use linux::PsmoveApiTracker;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub struct PsmoveApiTracker;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
impl PsmoveApiTracker {
|
||||
pub fn open(
|
||||
_camera_index: i32,
|
||||
_exposure: f32,
|
||||
_colors: &[(String, [u8; 3])],
|
||||
) -> Result<Self, PsmoveApiTrackerError> {
|
||||
Err(PsmoveApiTrackerError(
|
||||
"PSMoveAPI tracker backend is currently available on Linux".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn camera_info(&self) -> &PsmoveApiCameraInfo {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn calibrate_connected(&mut self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
pub fn observe_connected(&mut self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
pub fn set_expected_color(&mut self, _move_id: &str, _color: [u8; 3]) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn tracked_controller_count(&self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
pub fn update(&mut self) -> Vec<PsmoveApiObservation> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub fn rgb_image(&self) -> Option<(u32, u32, Vec<u8>)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn observation_preserves_stable_move_identity() {
|
||||
let observation = PsmoveApiObservation {
|
||||
move_id: "move-000704a39772".to_string(),
|
||||
center_x_px: 369.0,
|
||||
center_y_px: 430.0,
|
||||
radius_px: 10.6,
|
||||
age_ms: 1,
|
||||
};
|
||||
assert_eq!(observation.move_id, "move-000704a39772");
|
||||
assert!(observation.radius_px > 0.0);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue