hotham 0.2.0

A framework for creating incredible standalone VR experiences
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::{
    components::{hand::Handedness, Panel, UIPanel},
    resources::{GuiContext, HapticContext, RenderContext, VulkanContext},
};
use hecs::{PreparedQuery, World};
static GUI_HAPTIC_AMPLITUDE: f32 = 0.5;

/// GUI system
/// Walks through each panel in the World and
/// - draws the panel to a texture
/// - updates any input state
pub fn draw_gui_system(
    query: &mut PreparedQuery<(&mut Panel, &mut UIPanel)>,
    world: &mut World,
    vulkan_context: &VulkanContext,
    swapchain_image_index: &usize,
    render_context: &RenderContext,
    gui_context: &mut GuiContext,
    haptic_context: &mut HapticContext,
) {
    // Reset hovered_this_frame
    gui_context.hovered_this_frame = false;

    // Draw each panel
    for (_, (panel, ui_panel)) in query.query_mut(world) {
        // Reset the button state
        for button in &mut ui_panel.buttons {
            button.clicked_this_frame = false;
        }

        gui_context.paint_gui(
            vulkan_context,
            render_context,
            *swapchain_image_index,
            ui_panel,
            panel,
        );
    }

    // Did we hover over a button in this frame? If so request haptic feedback.
    if !gui_context.hovered_last_frame && gui_context.hovered_this_frame {
        // TODO - We should really have two pointer hands..
        haptic_context.request_haptic_feedback(GUI_HAPTIC_AMPLITUDE, Handedness::Right);
    }

    // Stash the value for the next frame.
    gui_context.hovered_last_frame = gui_context.hovered_this_frame;
}

#[cfg(target_os = "windows")]
#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use ash::vk::{self, Handle};
    use egui::Pos2;
    use image::{jpeg::JpegEncoder, DynamicImage, RgbaImage};
    use nalgebra::UnitQuaternion;
    use openxr::{Fovf, Quaternionf, Vector3f};
    use std::process::Command;

    use crate::{
        buffer::Buffer,
        components::{
            panel::PanelInput,
            ui_panel::{add_ui_panel_to_world, UIPanelButton},
            UIPanel,
        },
        gltf_loader,
        image::Image,
        resources::{GuiContext, HapticContext, PhysicsContext, RenderContext, VulkanContext},
        scene_data::SceneParams,
        swapchain::Swapchain,
        systems::{
            rendering_system, update_parent_transform_matrix_system, update_transform_matrix_system,
        },
        util::get_from_device_memory,
        COLOR_FORMAT,
    };

    use super::draw_gui_system;

    #[test]
    pub fn test_draw_gui() {
        let resolution = vk::Extent2D {
            height: 800,
            width: 800,
        };
        let (
            mut world,
            image,
            vulkan_context,
            mut render_context,
            mut haptic_context,
            mut gui_context,
        ) = setup(resolution.clone());

        // Begin. Use renderdoc in headless mode for debugging.
        let mut renderdoc = begin_renderdoc();

        let mut query = Default::default();
        schedule(
            &mut query,
            &mut world,
            &mut gui_context,
            &mut haptic_context,
            &mut render_context,
            &vulkan_context,
        );

        // Assert that haptic feedback has been requested.
        assert_eq!(
            haptic_context.right_hand_amplitude_this_frame,
            GUI_HAPTIC_AMPLITUDE
        );

        // Assert the button WAS NOT clicked this frame
        assert!(!button_was_clicked(&mut world));

        // Release the trigger slightly
        release_trigger(&mut world, &mut query);
        schedule(
            &mut query,
            &mut world,
            &mut gui_context,
            &mut haptic_context,
            &mut render_context,
            &vulkan_context,
        );

        // Assert that NO haptic feedback has been requested.
        assert_eq!(haptic_context.right_hand_amplitude_this_frame, 0.);

        // Assert the button WAS clicked this frame
        assert!(button_was_clicked(&mut world));

        // Move the cursor off the panel and release the trigger entirely
        move_cursor_off_panel(&mut world, &mut query);
        schedule(
            &mut query,
            &mut world,
            &mut gui_context,
            &mut haptic_context,
            &mut render_context,
            &vulkan_context,
        );

        // Assert the button WAS NOT clicked this frame
        assert!(!button_was_clicked(&mut world));

        // Assert that NO haptic feedback has been requested.
        assert_eq!(haptic_context.right_hand_amplitude_this_frame, 0.);

        end_renderdoc(&mut renderdoc);

        // Get the image off the GPU
        write_image_to_disk(&vulkan_context, image, resolution);

        open_file(&mut renderdoc);
    }

    fn schedule(
        query: &mut PreparedQuery<(&mut Panel, &mut UIPanel)>,
        world: &mut World,
        gui_context: &mut GuiContext,
        haptic_context: &mut HapticContext,
        render_context: &mut RenderContext,
        vulkan_context: &VulkanContext,
    ) {
        println!("[DRAW_GUI_TEST] Running schedule..");
        begin_frame(render_context, vulkan_context);

        // Reset the haptic context each frame - do this instead of having to create an OpenXR context etc.
        haptic_context.right_hand_amplitude_this_frame = 0.;

        // Draw the GUI
        draw_gui_system(
            query,
            world,
            vulkan_context,
            &0,
            render_context,
            gui_context,
            haptic_context,
        );

        // Begin the PBR Render Pass
        render_context.begin_pbr_render_pass(vulkan_context, 0);

        // Update transforms, etc.
        update_transform_matrix_system(&mut Default::default(), world);

        // Update parent transform matrix
        update_parent_transform_matrix_system(
            &mut Default::default(),
            &mut Default::default(),
            world,
        );

        // Render
        rendering_system(
            &mut Default::default(),
            world,
            vulkan_context,
            0,
            render_context,
        );

        // End PBR render
        render_context.end_pbr_render_pass(vulkan_context, 0);
        render_context.end_frame(vulkan_context, 0);
    }

    fn begin_frame(render_context: &mut RenderContext, vulkan_context: &VulkanContext) {
        let rotation: mint::Quaternion<f32> = UnitQuaternion::from_euler_angles(0., 0., 0.).into();
        let position = Vector3f {
            x: -1.0,
            y: 0.0,
            z: 1.0,
        };

        let view = openxr::View {
            pose: openxr::Posef {
                orientation: Quaternionf::from(rotation),
                position,
            },
            fov: Fovf {
                angle_up: 45.0_f32.to_radians(),
                angle_down: -45.0_f32.to_radians(),
                angle_left: -45.0_f32.to_radians(),
                angle_right: 45.0_f32.to_radians(),
            },
        };
        let views = vec![view.clone(), view];

        render_context.begin_frame(&vulkan_context, 0);

        render_context
            .update_scene_data(&views, &vulkan_context)
            .unwrap();
        render_context
            .scene_params_buffer
            .update(
                &vulkan_context,
                &[SceneParams {
                    // debug_view_inputs: 1.,
                    ..Default::default()
                }],
            )
            .unwrap();
    }

    fn button_was_clicked(world: &mut World) -> bool {
        let panel = world
            .query_mut::<&mut UIPanel>()
            .into_iter()
            .next()
            .unwrap()
            .1;
        return panel.buttons[0].clicked_this_frame;
    }

    fn release_trigger(world: &mut World, query: &mut PreparedQuery<(&mut Panel, &mut UIPanel)>) {
        let (panel, _ui_panel) = query.query_mut(world).into_iter().next().unwrap().1;
        panel.input = Some(PanelInput {
            cursor_location: Pos2::new(0.5 * 800., 0.15 * 800.),
            trigger_value: 0.2,
        });
    }

    fn move_cursor_off_panel(
        world: &mut World,
        query: &mut PreparedQuery<(&mut Panel, &mut UIPanel)>,
    ) {
        let (panel, _ui_panel) = query.query_mut(world).into_iter().next().unwrap().1;
        panel.input = Some(PanelInput {
            cursor_location: Pos2::new(0., 0.),
            trigger_value: 0.0,
        });
    }

    fn write_image_to_disk(vulkan_context: &VulkanContext, image: Image, resolution: vk::Extent2D) {
        let size = (resolution.height * resolution.width * 4) as usize;
        let image_data = vec![0; size];
        let buffer = Buffer::new(
            &vulkan_context,
            &image_data,
            vk::BufferUsageFlags::TRANSFER_DST,
        )
        .unwrap();
        vulkan_context.transition_image_layout(
            image.handle,
            vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
            vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
            1,
            1,
        );
        vulkan_context.copy_image_to_buffer(
            &image,
            vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
            buffer.handle,
        );
        let image_bytes = unsafe { get_from_device_memory(&vulkan_context, &buffer) }.to_vec();
        let image_from_vulkan = DynamicImage::ImageRgba8(
            RgbaImage::from_raw(resolution.width, resolution.height, image_bytes).unwrap(),
        );
        let output_path = "../test_assets/render_gui.jpg";
        {
            let output_path = std::path::Path::new(&output_path);
            let mut file = std::fs::File::create(output_path).unwrap();
            let mut jpeg_encoder = JpegEncoder::new(&mut file);
            jpeg_encoder.encode_image(&image_from_vulkan).unwrap();
        }
    }

    pub fn setup(
        resolution: vk::Extent2D,
    ) -> (
        World,
        Image,
        VulkanContext,
        RenderContext,
        HapticContext,
        GuiContext,
    ) {
        let vulkan_context = VulkanContext::testing().unwrap();
        let mut physics_context = PhysicsContext::default();
        // Create an image with vulkan_context
        let image = vulkan_context
            .create_image(
                COLOR_FORMAT,
                &resolution,
                vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::TRANSFER_SRC,
                2,
                1,
            )
            .unwrap();
        vulkan_context
            .set_debug_name(vk::ObjectType::IMAGE, image.handle.as_raw(), "Screenshot")
            .unwrap();

        let swapchain = Swapchain {
            images: vec![image.handle],
            resolution,
        };

        let render_context =
            RenderContext::new_from_swapchain(&vulkan_context, &swapchain).unwrap();
        let gui_context = GuiContext::new(&vulkan_context);

        let gltf_data: Vec<&[u8]> = vec![include_bytes!(
            "../../../test_assets/ferris-the-crab/source/ferris.glb"
        )];
        let mut models = gltf_loader::load_models_from_glb(
            &gltf_data,
            &vulkan_context,
            &render_context.descriptor_set_layouts,
        )
        .unwrap();
        let (_, mut world) = models.drain().next().unwrap();

        let panel = add_ui_panel_to_world(
            "Hello..",
            vk::Extent2D {
                width: 800,
                height: 800,
            },
            [1., 1.].into(),
            [-1.0, 0., 0.].into(),
            vec![
                UIPanelButton::new("Click me!"),
                UIPanelButton::new("Don't click me!"),
            ],
            &vulkan_context,
            &render_context,
            &gui_context,
            &mut physics_context,
            &mut world,
        );
        world.get_mut::<Panel>(panel).unwrap().input = Some(PanelInput {
            cursor_location: Pos2::new(0.5 * 800., 0.15 * 800.),
            trigger_value: 1.,
        });

        let haptic_context = HapticContext::default();

        (
            world,
            image,
            vulkan_context,
            render_context,
            haptic_context,
            gui_context,
        )
    }

    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    use renderdoc::RenderDoc;

    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    fn begin_renderdoc() -> Result<RenderDoc<renderdoc::V141>> {
        let mut renderdoc = RenderDoc::<renderdoc::V141>::new()?;
        renderdoc.start_frame_capture(std::ptr::null(), std::ptr::null());
        Ok(renderdoc)
    }

    #[cfg(target_os = "windows")]
    fn open_file(renderdoc: &mut Result<RenderDoc<renderdoc::V141>>) {
        if !renderdoc
            .as_mut()
            .map(|r| r.is_target_control_connected())
            .unwrap_or(false)
        {
            let _ = Command::new("explorer.exe")
                .args(["..\\test_assets\\render_gui.jpg"])
                .output()
                .unwrap();
        }
    }

    #[cfg(target_os = "macos")]
    fn open_file(_: &mut ()) {
        let _ = Command::new("open")
            .args(["../test_assets/render_gui.jpg"])
            .output()
            .unwrap();
    }

    // TODO: Support opening files on Linux
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    fn open_file(_: &mut Result<RenderDoc<renderdoc::V141>>) {}

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    fn begin_renderdoc() {}

    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    fn end_renderdoc(renderdoc: &mut Result<RenderDoc<renderdoc::V141>>) {
        let _ = renderdoc
            .as_mut()
            .map(|r| r.end_frame_capture(std::ptr::null(), std::ptr::null()));
    }

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    fn end_renderdoc(_: &mut ()) {}
}