bevy_oxr 0.3.0

Community crate for OpenXR in Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::error::Error;

use bevy::{prelude::*, utils::HashMap};
use openxr as xr;
use xr::{Action, Binding, Haptic, Posef, Vector2f};

use crate::{
    resources::{XrInstance, XrSession},
    xr_init::{xr_only, XrCleanup, XrPrePostSetup, XrPreSetup},
};

use super::oculus_touch::ActionSets;

pub use xr::sys::NULL_PATH;

pub struct XrActionsPlugin;
impl Plugin for XrActionsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(PreUpdate, sync_actions.run_if(xr_only()));
        app.add_systems(
            XrPreSetup,
            (insert_setup_action_sets, apply_deferred).chain(),
        );
        app.add_systems(XrPrePostSetup, setup_oxr_actions);
        app.add_systems(XrCleanup, clean_actions);
    }
}

fn insert_setup_action_sets(mut cmds: Commands) {
    info!("WHAT?!");
    cmds.insert_resource(SetupActionSets {
        sets: HashMap::new(),
    });
}

fn clean_actions(mut cmds: Commands) {
    cmds.remove_resource::<ActionSets>();
    cmds.remove_resource::<XrActionSets>();
}

#[inline(always)]
fn create_action<T: xr::ActionTy>(
    action: &SetupAction,
    action_name: &'static str,
    oxr_action_set: &xr::ActionSet,
    hands: &[xr::Path],
) -> xr::Action<T> {
    match action.handednes {
        ActionHandednes::Single => oxr_action_set
            .create_action(action_name, &action.pretty_name, &[])
            .unwrap_or_else(|_| panic!("Unable to create action: {}", action_name)),
        ActionHandednes::Double => oxr_action_set
            .create_action(action_name, &action.pretty_name, hands)
            .unwrap_or_else(|_| panic!("Unable to create action: {}", action_name)),
    }
}
pub fn setup_oxr_actions(world: &mut World) {
    let actions = world.remove_resource::<SetupActionSets>().unwrap();
    let instance = world.get_resource::<XrInstance>().unwrap();
    let session = world.get_resource::<XrSession>().unwrap();
    let left_path = instance.string_to_path("/user/hand/left").unwrap();
    let right_path = instance.string_to_path("/user/hand/right").unwrap();
    let hands = [left_path, right_path];

    let mut action_sets = XrActionSets { sets: default() };
    // let mut action_bindings: HashMap<&'static str, Vec<xr::Path>> = HashMap::new();
    let mut action_bindings: HashMap<
        (&'static str, &'static str),
        HashMap<&'static str, Vec<xr::Path>>,
    > = HashMap::new();
    for (set_name, set) in actions.sets.into_iter() {
        let mut actions: HashMap<&'static str, TypedAction> = default();
        let oxr_action_set = instance
            .create_action_set(set_name, &set.pretty_name, set.priority)
            .expect("Unable to create action set");
        for (action_name, action) in set.actions.into_iter() {
            use self::create_action as ca;
            let typed_action = match action.action_type {
                ActionType::Vec2 => {
                    TypedAction::Vec2(ca(&action, action_name, &oxr_action_set, &hands))
                }
                ActionType::F32 => {
                    TypedAction::F32(ca(&action, action_name, &oxr_action_set, &hands))
                }
                ActionType::Bool => {
                    TypedAction::Bool(ca(&action, action_name, &oxr_action_set, &hands))
                }
                ActionType::PoseF => {
                    TypedAction::PoseF(ca(&action, action_name, &oxr_action_set, &hands))
                }
                ActionType::Haptic => {
                    TypedAction::Haptic(ca(&action, action_name, &oxr_action_set, &hands))
                }
            };
            actions.insert(action_name, typed_action);
            for (device_path, bindings) in action.bindings.into_iter() {
                for b in bindings {
                    // info!("binding {} to {}", action_name, b);
                    action_bindings
                        .entry((set_name, action_name))
                        .or_default()
                        .entry(device_path)
                        .or_default()
                        .push(instance.string_to_path(b).unwrap());
                }
            }
        }
        // oxr_action_sets.push(oxr_action_set);
        action_sets.sets.insert(
            set_name,
            ActionSet {
                oxr_action_set,
                actions,
                enabled: true,
            },
        );
    }
    let mut b_indings: HashMap<&'static str, Vec<Binding>> = HashMap::new();
    for (dev, mut bindings) in action_sets
        .sets
        .iter()
        .flat_map(|(set_name, set)| {
            set.actions
                .iter()
                .map(move |(action_name, a)| (set_name, action_name, a))
        })
        .zip([&action_bindings].into_iter().cycle())
        .flat_map(move |((set_name, action_name, action), bindings)| {
            bindings
                .get(&(set_name as &'static str, action_name as &'static str))
                .unwrap()
                .iter()
                .map(move |(dev, bindings)| (action, dev, bindings))
        })
        .map(|(action, dev, bindings)| {
            (
                dev,
                bindings
                    .iter()
                    .map(move |binding| match &action {
                        TypedAction::Vec2(a) => Binding::new(a, *binding),
                        TypedAction::F32(a) => Binding::new(a, *binding),
                        TypedAction::Bool(a) => Binding::new(a, *binding),
                        TypedAction::PoseF(a) => Binding::new(a, *binding),
                        TypedAction::Haptic(a) => Binding::new(a, *binding),
                    })
                    .collect::<Vec<_>>(),
            )
        })
    {
        b_indings.entry(dev).or_default().append(&mut bindings);
    }
    for (dev, bindings) in b_indings.into_iter() {
        instance
            .suggest_interaction_profile_bindings(instance.string_to_path(dev).unwrap(), &bindings)
            .expect("Unable to suggest interaction bindings!");
    }
    session
        .attach_action_sets(
            &action_sets
                .sets
                .values()
                .map(|set| &set.oxr_action_set)
                .collect::<Vec<_>>(),
        )
        .expect("Unable to attach action sets!");

    world.insert_resource(action_sets);
}

pub enum ActionHandednes {
    Single,
    Double,
}

#[derive(Clone, Copy)]
pub enum ActionType {
    F32,
    Bool,
    PoseF,
    Haptic,
    Vec2,
}

pub enum TypedAction {
    F32(Action<f32>),
    Bool(Action<bool>),
    PoseF(Action<Posef>),
    Haptic(Action<Haptic>),
    Vec2(Action<Vector2f>),
}

pub struct SetupAction {
    pretty_name: String,
    action_type: ActionType,
    handednes: ActionHandednes,
    bindings: HashMap<&'static str, Vec<&'static str>>,
}

pub struct SetupActionSet {
    pretty_name: String,
    priority: u32,
    actions: HashMap<&'static str, SetupAction>,
}

impl SetupActionSet {
    pub fn new_action(
        &mut self,
        name: &'static str,
        pretty_name: String,
        action_type: ActionType,
        handednes: ActionHandednes,
    ) {
        self.actions.insert(
            name,
            SetupAction {
                pretty_name,
                action_type,
                handednes,
                bindings: default(),
            },
        );
    }
    pub fn suggest_binding(&mut self, device_path: &'static str, bindings: &[XrBinding]) {
        for binding in bindings {
            self.actions
                .get_mut(binding.action)
                .ok_or(eyre::eyre!("Missing Action: {}", binding.action))
                .unwrap()
                .bindings
                .entry(device_path)
                .or_default()
                .push(binding.path);
        }
    }
}
pub struct XrBinding {
    action: &'static str,
    path: &'static str,
}

impl XrBinding {
    pub fn new(action_name: &'static str, binding_path: &'static str) -> XrBinding {
        XrBinding {
            action: action_name,
            path: binding_path,
        }
    }
}

#[derive(Resource)]
pub struct SetupActionSets {
    sets: HashMap<&'static str, SetupActionSet>,
}

impl SetupActionSets {
    pub fn add_action_set(
        &mut self,
        name: &'static str,
        pretty_name: String,
        priority: u32,
    ) -> &mut SetupActionSet {
        self.sets.insert(
            name,
            SetupActionSet {
                pretty_name,
                priority,
                actions: HashMap::new(),
            },
        );
        self.sets.get_mut(name).unwrap()
    }
}

pub struct ActionSet {
    // add functionality to enable/disable action sets
    enabled: bool,
    actions: HashMap<&'static str, TypedAction>,
    oxr_action_set: xr::ActionSet,
}

#[derive(Resource)]
pub struct XrActionSets {
    sets: HashMap<&'static str, ActionSet>,
}

use std::fmt::Display as FmtDisplay;
impl FmtDisplay for ActionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let err = match self {
            ActionError::NoActionSet => "Action Set Not Found!",
            ActionError::NoAction => "Action Not Found!",
            ActionError::WrongActionType => "Wrong Action Type!",
        };
        write!(f, "{}", err)
    }
}
impl Error for ActionError {}
#[derive(Debug)]
pub enum ActionError {
    NoActionSet,
    NoAction,
    WrongActionType,
}

impl XrActionSets {
    pub fn get_action_vec2(
        &self,
        action_set: &'static str,
        action_name: &'static str,
    ) -> Result<&Action<Vector2f>, ActionError> {
        let action = self
            .sets
            .get(action_set)
            .ok_or(ActionError::NoActionSet)?
            .actions
            .get(action_name)
            .ok_or(ActionError::NoAction)?;
        match action {
            TypedAction::Vec2(a) => Ok(a),
            _ => Err(ActionError::WrongActionType),
        }
    }
    pub fn get_action_f32(
        &self,
        action_set: &'static str,
        action_name: &'static str,
    ) -> Result<&Action<f32>, ActionError> {
        let action = self
            .sets
            .get(action_set)
            .ok_or(ActionError::NoActionSet)?
            .actions
            .get(action_name)
            .ok_or(ActionError::NoAction)?;
        match action {
            TypedAction::F32(a) => Ok(a),
            _ => Err(ActionError::WrongActionType),
        }
    }
    pub fn get_action_bool(
        &self,
        action_set: &'static str,
        action_name: &'static str,
    ) -> Result<&Action<bool>, ActionError> {
        let action = self
            .sets
            .get(action_set)
            .ok_or(ActionError::NoActionSet)?
            .actions
            .get(action_name)
            .ok_or(ActionError::NoAction)?;
        match action {
            TypedAction::Bool(a) => Ok(a),
            _ => Err(ActionError::WrongActionType),
        }
    }
    pub fn get_action_posef(
        &self,
        action_set: &'static str,
        action_name: &'static str,
    ) -> Result<&Action<Posef>, ActionError> {
        let action = self
            .sets
            .get(action_set)
            .ok_or(ActionError::NoActionSet)?
            .actions
            .get(action_name)
            .ok_or(ActionError::NoAction)?;
        match action {
            TypedAction::PoseF(a) => Ok(a),
            _ => Err(ActionError::WrongActionType),
        }
    }
    pub fn get_action_haptic(
        &self,
        action_set: &'static str,
        action_name: &'static str,
    ) -> Result<&Action<Haptic>, ActionError> {
        let action = self
            .sets
            .get(action_set)
            .ok_or(ActionError::NoActionSet)?
            .actions
            .get(action_name)
            .ok_or(ActionError::NoAction)?;
        match action {
            TypedAction::Haptic(a) => Ok(a),
            _ => Err(ActionError::WrongActionType),
        }
    }
}

pub fn sync_actions(action_sets: Res<XrActionSets>, session: Res<XrSession>) {
    let active_sets = action_sets
        .sets
        .values()
        .filter_map(|set| {
            if set.enabled {
                Some(xr::ActiveActionSet::new(&set.oxr_action_set))
            } else {
                None
            }
        })
        .collect::<Vec<_>>();
    if let Err(err) = session.sync_actions(&active_sets) {
        warn!("OpenXR action sync error: {}", err);
    }
}