Skip to main content
QAROS Rust API Dev (main) · versions: Dev (main) · Developer Guide

qaros/
types.rs

1//! Value types: identifiers, math, and the C enums the safe API uses.
2
3use std::ffi::CStr;
4use std::fmt;
5
6use qaros_sys as sys;
7
8macro_rules! define_id {
9    ($(#[$documentation:meta])* $name:ident, $raw:ty) => {
10        $(#[$documentation])*
11        ///
12        /// Formats as colon-separated hex bytes, like the C examples'
13        /// `print_hex_id`. Persist onboarding ids with
14        /// [`crate::Library::uuid_to_string`] instead, which uses the
15        /// library's own UUID text form.
16        #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
17        pub struct $name(pub [u8; 16]);
18
19        #[allow(dead_code)]
20        impl $name {
21            /// The all-zero id, which names nothing.
22            pub const ZERO: Self = Self([0; 16]);
23
24            /// Whether this is [`Self::ZERO`].
25            pub fn is_zero(&self) -> bool {
26                self.0 == [0; 16]
27            }
28
29            pub(crate) fn to_raw(self) -> $raw {
30                <$raw>::from_bytes(self.0)
31            }
32
33            pub(crate) fn from_raw(raw: $raw) -> Self {
34                Self(raw.data)
35            }
36        }
37
38        impl fmt::Display for $name {
39            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
40                write_hex_id(formatter, &self.0)
41            }
42        }
43
44        impl fmt::Debug for $name {
45            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46                write!(formatter, "{}(", stringify!($name))?;
47                write_hex_id(formatter, &self.0)?;
48                formatter.write_str(")")
49            }
50        }
51    };
52}
53
54fn write_hex_id(formatter: &mut fmt::Formatter<'_>, bytes: &[u8; 16]) -> fmt::Result {
55    for (index, byte) in bytes.iter().enumerate() {
56        if index > 0 {
57            formatter.write_str(":")?;
58        }
59        write!(formatter, "{byte:02X}")?;
60    }
61    Ok(())
62}
63
64trait FromIdBytes {
65    fn from_bytes(bytes: [u8; 16]) -> Self;
66}
67
68macro_rules! impl_from_id_bytes {
69    ($($raw:ty),*) => {
70        $(impl FromIdBytes for $raw {
71            fn from_bytes(bytes: [u8; 16]) -> Self {
72                Self { data: bytes }
73            }
74        })*
75    };
76}
77
78impl_from_id_bytes!(
79    sys::QarPeerId,
80    sys::QarSessionId,
81    sys::QarGuiPanelId,
82    sys::QarAppVolumeId,
83    sys::QarStreamId,
84    sys::QarOnboardingId
85);
86
87define_id!(
88    /// A participant in the session: a device or an application.
89    PeerId,
90    sys::QarPeerId
91);
92define_id!(SessionId, sys::QarSessionId);
93define_id!(GuiPanelId, sys::QarGuiPanelId);
94define_id!(AppVolumeId, sys::QarAppVolumeId);
95define_id!(
96    /// Correlates render stream requests.
97    StreamId,
98    sys::QarStreamId
99);
100define_id!(
101    /// Key of a persisted identity slot, the ticket for the deprecated
102    /// [`crate::Runtime::rejoin`] and [`crate::Runtime::forget`]. Local apps,
103    /// companions and member hubs' apps have none to persist.
104    OnboardingId,
105    sys::QarOnboardingId
106);
107
108/// Position in meters. Room space is right-handed, Y up, minus Z forward
109/// (OpenXR conventions).
110#[derive(Clone, Copy, Debug, PartialEq, Default)]
111pub struct Vec3 {
112    pub x: f32,
113    pub y: f32,
114    pub z: f32,
115}
116
117impl Vec3 {
118    /// A vector from its components.
119    pub const fn new(x: f32, y: f32, z: f32) -> Self {
120        Self { x, y, z }
121    }
122}
123
124/// Rotation quaternion, scalar last.
125#[derive(Clone, Copy, Debug, PartialEq)]
126pub struct Quat {
127    pub x: f32,
128    pub y: f32,
129    pub z: f32,
130    pub w: f32,
131}
132
133impl Quat {
134    /// No rotation.
135    pub const IDENTITY: Self = Self {
136        x: 0.0,
137        y: 0.0,
138        z: 0.0,
139        w: 1.0,
140    };
141}
142
143impl Default for Quat {
144    fn default() -> Self {
145        Self::IDENTITY
146    }
147}
148
149/// Orientation and position; the default is the identity pose, as
150/// `qar_pose_default()`.
151#[derive(Clone, Copy, Debug, PartialEq, Default)]
152pub struct Pose {
153    pub orientation: Quat,
154    pub position: Vec3,
155}
156
157impl Pose {
158    /// A pose at `position` with no rotation.
159    pub const fn from_position(position: Vec3) -> Self {
160        Self {
161            orientation: Quat::IDENTITY,
162            position,
163        }
164    }
165
166    pub(crate) fn to_raw(self) -> sys::QarPose {
167        sys::QarPose {
168            orientation: sys::QarQuaternion {
169                x: self.orientation.x,
170                y: self.orientation.y,
171                z: self.orientation.z,
172                w: self.orientation.w,
173            },
174            position: sys::QarVector3 {
175                x: self.position.x,
176                y: self.position.y,
177                z: self.position.z,
178            },
179        }
180    }
181
182    pub(crate) fn from_raw(raw: sys::QarPose) -> Self {
183        Self {
184            orientation: Quat {
185                x: raw.orientation.x,
186                y: raw.orientation.y,
187                z: raw.orientation.z,
188                w: raw.orientation.w,
189            },
190            position: Vec3 {
191                x: raw.position.x,
192                y: raw.position.y,
193                z: raw.position.z,
194            },
195        }
196    }
197}
198
199/// Field of view as four angles in radians, OpenXR style: `left` and `down`
200/// are normally negative.
201#[derive(Clone, Copy, Debug, PartialEq)]
202pub struct Fov {
203    pub angle_left: f32,
204    pub angle_right: f32,
205    pub angle_up: f32,
206    pub angle_down: f32,
207}
208
209impl Fov {
210    pub(crate) fn from_raw(raw: sys::QarFov) -> Self {
211        Self {
212            angle_left: raw.angle_left,
213            angle_right: raw.angle_right,
214            angle_up: raw.angle_up,
215            angle_down: raw.angle_down,
216        }
217    }
218}
219
220/// Maps a newtype C enum to a Rust enum with an `Other` variant for values
221/// this binding does not know, so values coming from the library never cause
222/// undefined behaviour.
223macro_rules! c_enum {
224    (
225        $(#[$documentation:meta])*
226        $name:ident: $raw:ident {
227            $($(#[$variant_documentation:meta])* $variant:ident = $constant:ident),* $(,)?
228        }
229    ) => {
230        $(#[$documentation])*
231        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
232        pub enum $name {
233            $($(#[$variant_documentation])* $variant,)*
234            /// A value not in the C header.
235            Other(sys::$raw),
236        }
237
238        #[allow(dead_code)]
239        impl $name {
240            pub(crate) fn from_raw(raw: sys::$raw) -> Self {
241                $(if raw == sys::$raw::$constant {
242                    return Self::$variant;
243                })*
244                Self::Other(raw)
245            }
246
247            pub(crate) fn to_raw(self) -> sys::$raw {
248                match self {
249                    $(Self::$variant => sys::$raw::$constant,)*
250                    Self::Other(raw) => raw,
251                }
252            }
253        }
254    };
255}
256
257c_enum!(
258    /// Pixel format of a frame texture (`QarPixelFormat`).
259    PixelFormat: QarPixelFormat {
260        R32Float = QAR_PIXEL_FORMAT_R32_FLOAT,
261        R8G8B8A8 = QAR_PIXEL_FORMAT_R8G8B8A8,
262        B8G8R8A8 = QAR_PIXEL_FORMAT_B8G8R8A8,
263        R16G16B16A16 = QAR_PIXEL_FORMAT_R16G16B16A16,
264        B8G8R8X8 = QAR_PIXEL_FORMAT_B8G8R8X8,
265        D32Float = QAR_PIXEL_FORMAT_D32_FLOAT,
266        /// 16-bit normalized depth, accepted only as a render sender's depth format; the sender
267        /// widens it to 32-bit float before the frame leaves the application.
268        D16Unorm = QAR_PIXEL_FORMAT_D16_UNORM,
269        /// Depth with stencil, accepted only as an OpenGL or Vulkan sender's depth format (the
270        /// CPU and D3D11 senders refuse it); only the depth is streamed, as 32-bit float.
271        D24UnormS8Uint = QAR_PIXEL_FORMAT_D24_UNORM_S8_UINT,
272        /// 32-bit float depth with stencil, accepted as [`Self::D24UnormS8Uint`] is.
273        D32FloatS8X24Uint = QAR_PIXEL_FORMAT_D32_FLOAT_S8X24_UINT,
274    }
275);
276
277c_enum!(
278    /// How views pack into the frame's textures.
279    FrameLayout: QarFrameLayout {
280        SideBySide = QAR_FRAME_LAYOUT_SIDE_BY_SIDE,
281        SeparatedTextures = QAR_FRAME_LAYOUT_SEPARATED_TEXTURES,
282        Layered = QAR_FRAME_LAYOUT_LAYERED,
283    }
284);
285
286c_enum!(
287    /// What a frame view holds: color, grayscale or depth (`QarVideoFrameViewType`).
288    ViewKind: QarVideoFrameViewType {
289        Grayscale = QAR_VIDEO_FRAME_VIEW_TYPE_GRAYSCALE,
290        Color = QAR_VIDEO_FRAME_VIEW_TYPE_COLOR,
291        Depth = QAR_VIDEO_FRAME_VIEW_TYPE_DEPTH,
292    }
293);
294
295c_enum!(
296    /// The eye a frame view is for (`QarVideoFrameViewEye`).
297    Eye: QarVideoFrameViewEye {
298        None = QAR_VIDEO_FRAME_VIEW_EYE_NONE,
299        Left = QAR_VIDEO_FRAME_VIEW_EYE_LEFT,
300        Right = QAR_VIDEO_FRAME_VIEW_EYE_RIGHT,
301    }
302);
303
304c_enum!(
305    /// Lifecycle state of a peer's application (`QarAppState`), deprecated in the public header
306    /// for the peer presence and computed from it there; see [`crate::PeerInfo::app_state`].
307    AppState: QarAppState {
308        Unknown = QAR_APP_STATE_UNKNOWN,
309        Initializing = QAR_APP_STATE_INITIALIZING,
310        Running = QAR_APP_STATE_RUNNING,
311        ShuttingDown = QAR_APP_STATE_SHUTTING_DOWN,
312        /// Left for good: never comes back under its id.
313        Retired = QAR_APP_STATE_RETIRED,
314    }
315);
316
317c_enum!(
318    /// Visibility of a GUI panel (`QarGuiPanelState`).
319    GuiPanelState: QarGuiPanelState {
320        Visible = QAR_GUI_PANEL_STATE_VISIBLE,
321        Minimized = QAR_GUI_PANEL_STATE_MINIMIZED,
322        Hidden = QAR_GUI_PANEL_STATE_HIDDEN,
323        Closed = QAR_GUI_PANEL_STATE_CLOSED,
324    }
325);
326
327c_enum!(
328    /// What a GUI panel shows (`QarGuiPanelContentType`), fixed at creation.
329    GuiPanelContentType: QarGuiPanelContentType {
330        WebsiteUri = QAR_GUI_PANEL_CONTENT_TYPE_WEBSITE_URI,
331        StreamId = QAR_GUI_PANEL_CONTENT_TYPE_STREAM_ID,
332        /// A page of a content bundle its owner serves over the session.
333        Served = QAR_GUI_PANEL_CONTENT_TYPE_SERVED,
334    }
335);
336
337c_enum!(
338    /// Whether an app volume is active or closed (`QarAppVolumeLifetimeStatus`).
339    AppVolumeLifetime: QarAppVolumeLifetimeStatus {
340        Active = QAR_APP_VOLUME_ACTIVE,
341        Closed = QAR_APP_VOLUME_CLOSED,
342    }
343);
344
345c_enum!(
346    /// Severity of a library log message (`QarLogSeverity`).
347    LogSeverity: QarLogSeverity {
348        Trace = QAR_LOG_SEVERITY_TRACE,
349        Debug = QAR_LOG_SEVERITY_DEBUG,
350        Info = QAR_LOG_SEVERITY_INFO,
351        Warn = QAR_LOG_SEVERITY_WARN,
352        Error = QAR_LOG_SEVERITY_ERROR,
353        Fatal = QAR_LOG_SEVERITY_FATAL,
354    }
355);
356
357c_enum!(
358    /// Severity of a progress callback message (`QarActionSeverity`).
359    ActionSeverity: QarActionSeverity {
360        Info = QAR_ACTION_SEVERITY_INFO,
361        Warning = QAR_ACTION_SEVERITY_WARNING,
362        Error = QAR_ACTION_SEVERITY_ERROR,
363        Done = QAR_ACTION_SEVERITY_DONE,
364    }
365);
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn the_depth_formats_carry_the_headers_values() {
373        for (format, value) in [
374            (PixelFormat::D16Unorm, 100),
375            (PixelFormat::D32Float, 101),
376            (PixelFormat::D24UnormS8Uint, 102),
377            (PixelFormat::D32FloatS8X24Uint, 103),
378        ] {
379            assert_eq!(format.to_raw(), sys::QarPixelFormat(value));
380            assert_eq!(PixelFormat::from_raw(sys::QarPixelFormat(value)), format);
381        }
382        assert_eq!(
383            PixelFormat::from_raw(sys::QarPixelFormat(104)),
384            PixelFormat::Other(sys::QarPixelFormat(104))
385        );
386    }
387
388    #[test]
389    fn a_retired_peer_reads_as_retired_and_back() {
390        let raw = sys::QarAppState::QAR_APP_STATE_RETIRED;
391        assert_eq!(AppState::from_raw(raw), AppState::Retired);
392        assert_eq!(AppState::Retired.to_raw(), raw);
393        assert_eq!(format!("{:?}", AppState::from_raw(raw)), "Retired");
394    }
395}
396
397c_enum!(
398    /// Where a session stands in its hub's session lifecycle (`QarSessionLifecycleState`).
399    /// Treat [`Self::Other`] as [`Self::HubUnreachable`]: the session keeps trying.
400    SessionLifecycleState: QarSessionLifecycleState {
401        /// In the hub's current session; traffic flows.
402        Connected = QAR_SESSION_LIFECYCLE_STATE_CONNECTED,
403        /// Moving into another session in place; traffic resumes once connected.
404        Migrating = QAR_SESSION_LIFECYCLE_STATE_MIGRATING,
405        /// The hub has not answered for a while; the session keeps trying by itself.
406        HubUnreachable = QAR_SESSION_LIFECYCLE_STATE_HUB_UNREACHABLE,
407        /// The hub no longer admits this peer (its approval was revoked, it missed too many
408        /// rotations, or the hub was reset). Terminal: drop the session and onboard again.
409        RePairRequired = QAR_SESSION_LIFECYCLE_STATE_RE_PAIR_REQUIRED,
410    }
411);
412
413c_enum!(
414    /// Why the session moved into another session id (`QarSessionChangeCause`). Informational
415    /// only; treat [`Self::Other`] as [`Self::Rotated`].
416    SessionChangeCause: QarSessionChangeCause {
417        /// No move: a state change within the same session.
418        None = QAR_SESSION_CHANGE_CAUSE_NONE,
419        /// The hub serves a new session of its own.
420        Rotated = QAR_SESSION_CHANGE_CAUSE_ROTATED,
421        /// The hub this app paired with joined another hub as its member.
422        JoinedPrimary = QAR_SESSION_CHANGE_CAUSE_JOINED_PRIMARY,
423    }
424);
425
426/// One state of a session's lifecycle (`QarSessionLifecycleInfo`), copied out of the library.
427#[derive(Clone, Debug, PartialEq, Eq)]
428pub struct SessionLifecycle {
429    pub state: SessionLifecycleState,
430    /// Why the latest move happened; [`SessionChangeCause::None`] outside a move.
431    pub cause: SessionChangeCause,
432    /// The session the app is in now: during [`SessionLifecycleState::Migrating`] still the old
433    /// one. Compare it with the id the app last saw to tell a new move from an old one.
434    pub session_id: SessionId,
435    /// The session it moved from, on the state that ends a move.
436    pub previous_session_id: Option<SessionId>,
437    /// Text for logs and the operator, never a secret. Empty from
438    /// [`crate::Session::lifecycle`].
439    pub reason: String,
440}
441
442impl SessionLifecycle {
443    pub(crate) fn from_raw(info: &sys::QarSessionLifecycleInfo) -> Self {
444        let reason = if info.reason.is_null() {
445            String::new()
446        } else {
447            // SAFETY: non-null and NUL-terminated; valid during the callback that delivered it.
448            unsafe { CStr::from_ptr(info.reason) }
449                .to_string_lossy()
450                .into_owned()
451        };
452        Self {
453            state: SessionLifecycleState::from_raw(info.state),
454            cause: SessionChangeCause::from_raw(info.cause),
455            session_id: SessionId::from_raw(info.session_id),
456            previous_session_id: info
457                .has_previous_session
458                .then(|| SessionId::from_raw(info.previous_session_id)),
459            reason,
460        }
461    }
462}
463
464/// The device type whose setup a [`QarosView::DeviceSetup`] view shows (`QarQarosDeviceKind`).
465#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
466pub enum QarosDeviceKind {
467    /// Meta Quest.
468    MetaQuest,
469    /// Metalens.
470    Metalens,
471    /// Android XR headsets.
472    AndroidXr,
473    /// HoloLens 2.
474    HoloLens,
475}
476
477impl QarosDeviceKind {
478    pub(crate) fn to_raw(self) -> sys::QarQarosDeviceKind {
479        match self {
480            Self::MetaQuest => sys::QarQarosDeviceKind::QAR_QAROS_DEVICE_KIND_META_QUEST,
481            Self::Metalens => sys::QarQarosDeviceKind::QAR_QAROS_DEVICE_KIND_METALENS,
482            Self::AndroidXr => sys::QarQarosDeviceKind::QAR_QAROS_DEVICE_KIND_ANDROID_XR,
483            Self::HoloLens => sys::QarQarosDeviceKind::QAR_QAROS_DEVICE_KIND_HOLOLENS,
484        }
485    }
486}
487
488/// A predefined view of the QAROS Visualizer (`QarQarosView`), opened with
489/// [`crate::Session::open_qaros_view`]: each is the dialog the `qaros://visualizer` link of the
490/// same name opens. The device kind sits in the setup variant, so no other view can carry one.
491#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
492pub enum QarosView {
493    /// The Pair Headset QR code of the Devices tab.
494    PairHeadsetQr,
495    /// The Room Origin marker: the QR code headsets anchor the room to.
496    RoomOriginQr,
497    /// The setup steps of one device type.
498    DeviceSetup(QarosDeviceKind),
499}
500
501impl QarosView {
502    /// The view and device kind of `QarOpenQarosViewInfo`.
503    pub(crate) fn to_raw(self) -> (sys::QarQarosView, sys::QarQarosDeviceKind) {
504        let none = sys::QarQarosDeviceKind::QAR_QAROS_DEVICE_KIND_NONE;
505        match self {
506            Self::PairHeadsetQr => (sys::QarQarosView::QAR_QAROS_VIEW_PAIR_HEADSET_QR, none),
507            Self::RoomOriginQr => (sys::QarQarosView::QAR_QAROS_VIEW_ROOM_ORIGIN_QR, none),
508            Self::DeviceSetup(kind) => (
509                sys::QarQarosView::QAR_QAROS_VIEW_DEVICE_SETUP,
510                kind.to_raw(),
511            ),
512        }
513    }
514}