Blender V5.0
GHOST_XrSession.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2020-2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10#include <cassert>
11#include <chrono>
12#include <cstdio>
13#include <list>
14#include <sstream>
15
16#include "GHOST_C-api.h"
17
19#include "GHOST_XrAction.hh"
20#include "GHOST_XrContext.hh"
22#include "GHOST_XrException.hh"
23#include "GHOST_XrSwapchain.hh"
24#include "GHOST_Xr_intern.hh"
25
26#include "GHOST_XrSession.hh"
27
29 XrSystemId system_id = XR_NULL_SYSTEM_ID;
30 XrSession session = XR_NULL_HANDLE;
31 XrSessionState session_state = XR_SESSION_STATE_UNKNOWN;
32
33 /* Use stereo rendering by default. */
34 XrViewConfigurationType view_type = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
35 bool foveation_supported = false;
36
38 XrSpace view_space;
40 std::vector<XrView> views;
41 std::vector<GHOST_XrSwapchain> swapchains;
42
43 std::map<std::string, GHOST_XrActionSet> action_sets;
44 /* Controller models identified by subaction path. */
45 std::map<std::string, GHOST_XrControllerModel> controller_models;
46
47 /* Meta Quest passthrough support. */
49 XrCompositionLayerPassthroughFB passthrough_layer;
50};
51
53 XrFrameState frame_state;
54
56 std::chrono::high_resolution_clock::time_point frame_begin_time;
57 /* Time previous frames took for rendering (in ms). */
58 std::list<double> last_frame_times;
59
60 /* Whether foveation is active for the frame. */
62};
63
64/* -------------------------------------------------------------------- */
67
69 : context_(&xr_context), oxr_(std::make_unique<OpenXRSessionData>())
70{
71}
72
74{
76
77 oxr_->swapchains.clear();
78 oxr_->action_sets.clear();
79
80 if (oxr_->reference_space != XR_NULL_HANDLE) {
81 CHECK_XR_ASSERT(xrDestroySpace(oxr_->reference_space));
82 }
83 if (oxr_->view_space != XR_NULL_HANDLE) {
84 CHECK_XR_ASSERT(xrDestroySpace(oxr_->view_space));
85 }
86 if (oxr_->combined_eye_space != XR_NULL_HANDLE) {
87 CHECK_XR_ASSERT(xrDestroySpace(oxr_->combined_eye_space));
88 }
89 if (oxr_->session != XR_NULL_HANDLE) {
90 CHECK_XR_ASSERT(xrDestroySession(oxr_->session));
91 }
92
93 oxr_->session = XR_NULL_HANDLE;
94 oxr_->session_state = XR_SESSION_STATE_UNKNOWN;
95
96 oxr_->passthrough_supported = false;
97 oxr_->passthrough_layer.layerHandle = XR_NULL_HANDLE;
98
99 context_->getCustomFuncs().session_exit_fn(context_->getCustomFuncs().session_exit_customdata);
100}
101
106void GHOST_XrSession::initSystem()
107{
108 assert(context_->getInstance() != XR_NULL_HANDLE);
109 assert(oxr_->system_id == XR_NULL_SYSTEM_ID);
110
111 XrSystemGetInfo system_info = {};
112 system_info.type = XR_TYPE_SYSTEM_GET_INFO;
113 system_info.formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
114
115 CHECK_XR(xrGetSystem(context_->getInstance(), &system_info, &oxr_->system_id),
116 "Failed to get device information. Is a device plugged in?");
117}
118 /* Create, Initialize and Destruct */
120
121/* -------------------------------------------------------------------- */
124
126 const GHOST_XrPose &base_pose,
127 bool isDebugMode)
128{
129 XrReferenceSpaceCreateInfo create_info = {XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
130 create_info.poseInReferenceSpace.orientation.w = 1.0f;
131
132 create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
133#if 0
134/* TODO
135 *
136 * Proper reference space set up is not supported yet. We simply hand OpenXR
137 * the global space as reference space and apply its pose onto the active
138 * camera matrix to get a basic viewing experience going. If there's no active
139 * camera with stick to the world origin.
140 *
141 * Once we have proper reference space set up (i.e. a way to define origin, up-
142 * direction and an initial view rotation perpendicular to the up-direction),
143 * we can hand OpenXR a proper reference pose/space.
144 */
145 create_info.poseInReferenceSpace.position.x = base_pose->position[0];
146 create_info.poseInReferenceSpace.position.y = base_pose->position[1];
147 create_info.poseInReferenceSpace.position.z = base_pose->position[2];
148 create_info.poseInReferenceSpace.orientation.x = base_pose->orientation_quat[1];
149 create_info.poseInReferenceSpace.orientation.y = base_pose->orientation_quat[2];
150 create_info.poseInReferenceSpace.orientation.z = base_pose->orientation_quat[3];
151 create_info.poseInReferenceSpace.orientation.w = base_pose->orientation_quat[0];
152#else
153 (void)base_pose;
154#endif
155
156 XrResult result = xrCreateReferenceSpace(oxr.session, &create_info, &oxr.reference_space);
157
158 if (XR_FAILED(result)) {
159 /* One of the rare cases where we don't want to immediately throw an exception on failure,
160 * since runtimes are not required to support the stage reference space. If the runtime
161 * doesn't support it then just fall back to the local space. */
162 if (result == XR_ERROR_REFERENCE_SPACE_UNSUPPORTED) {
163 if (isDebugMode) {
164 printf(
165 "Warning: XR runtime does not support stage reference space, falling back to local "
166 "reference space.\n");
167 }
168 create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
169 CHECK_XR(xrCreateReferenceSpace(oxr.session, &create_info, &oxr.reference_space),
170 "Failed to create local reference space.");
171 }
172 else {
173 throw GHOST_XrException("Failed to create stage reference space.", result);
174 }
175 }
176 else {
177 /* Check if tracking bounds are valid. Tracking bounds may be invalid if the user did not
178 * define a tracking space via the XR runtime. */
179 XrExtent2Df extents;
180 CHECK_XR(xrGetReferenceSpaceBoundsRect(oxr.session, XR_REFERENCE_SPACE_TYPE_STAGE, &extents),
181 "Failed to get stage reference space bounds.");
182 if (extents.width == 0.0f || extents.height == 0.0f) {
183 if (isDebugMode) {
184 printf(
185 "Warning: Invalid stage reference space bounds, falling back to local reference "
186 "space. To use the stage reference space, please define a tracking space via the XR "
187 "runtime.\n");
188 }
189 /* Fall back to local space. */
190 if (oxr.reference_space != XR_NULL_HANDLE) {
191 CHECK_XR(xrDestroySpace(oxr.reference_space), "Failed to destroy stage reference space.");
192 }
193
194 create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
195 CHECK_XR(xrCreateReferenceSpace(oxr.session, &create_info, &oxr.reference_space),
196 "Failed to create local reference space.");
197 }
198 }
199
200 create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_VIEW;
201 CHECK_XR(xrCreateReferenceSpace(oxr.session, &create_info, &oxr.view_space),
202 "Failed to create view reference space.");
203
204 /* Foveation reference spaces. */
205 if (oxr.foveation_supported) {
206 create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_COMBINED_EYE_VARJO;
207 CHECK_XR(xrCreateReferenceSpace(oxr.session, &create_info, &oxr.combined_eye_space),
208 "Failed to create combined eye reference space.");
209 }
210}
211
212void GHOST_XrSession::start(const GHOST_XrSessionBeginInfo *begin_info)
213{
214 assert(context_->getInstance() != XR_NULL_HANDLE);
215 assert(oxr_->session == XR_NULL_HANDLE);
216 if (context_->getCustomFuncs().gpu_ctx_bind_fn == nullptr) {
217 throw GHOST_XrException(
218 "Invalid API usage: No way to bind graphics context to the XR session. Call "
219 "GHOST_XrGraphicsContextBindFuncs() with valid parameters before starting the "
220 "session (through GHOST_XrSessionStart()).");
221 }
222
223 initSystem();
224
225 bindGraphicsContext();
226 if (gpu_ctx_ == nullptr) {
227 throw GHOST_XrException(
228 "Invalid API usage: No graphics context returned through the callback set with "
229 "GHOST_XrGraphicsContextBindFuncs(). This is required for session starting (through "
230 "GHOST_XrSessionStart()).");
231 }
232
233 std::string requirement_str;
234 gpu_binding_ = GHOST_XrGraphicsBindingCreateFromType(context_->getGraphicsBindingType(),
235 *gpu_ctx_);
236 if (!gpu_binding_->checkVersionRequirements(
237 *gpu_ctx_, context_->getInstance(), oxr_->system_id, &requirement_str))
238 {
239 std::ostringstream strstream;
240 strstream << "Available graphics context version does not meet the following requirements: "
241 << requirement_str;
242 throw GHOST_XrException(strstream.str().data());
243 }
244 gpu_binding_->initFromGhostContext(*gpu_ctx_, context_->getInstance(), oxr_->system_id);
245
246 XrSessionCreateInfo create_info = {};
247 create_info.type = XR_TYPE_SESSION_CREATE_INFO;
248 create_info.systemId = oxr_->system_id;
249 create_info.next = &gpu_binding_->oxr_binding;
250
251 CHECK_XR(xrCreateSession(context_->getInstance(), &create_info, &oxr_->session),
252 "Failed to create VR session. The OpenXR runtime may have additional requirements for "
253 "the graphics driver that are not met. Other causes are possible too however.\nTip: "
254 "The --debug-xr command line option for Blender might allow the runtime to output "
255 "detailed error information to the command line.");
256
257 prepareDrawing();
258 create_reference_spaces(*oxr_, begin_info->base_pose, context_->isDebugMode());
259
260 /* Create and bind actions here. */
261 context_->getCustomFuncs().session_create_fn();
262}
263
265{
266 xrRequestExitSession(oxr_->session);
267}
268
269void GHOST_XrSession::beginSession()
270{
271 XrSessionBeginInfo begin_info = {XR_TYPE_SESSION_BEGIN_INFO};
272 begin_info.primaryViewConfigurationType = oxr_->view_type;
273 CHECK_XR(xrBeginSession(oxr_->session, &begin_info), "Failed to cleanly begin the VR session.");
274}
275
276void GHOST_XrSession::endSession()
277{
278 assert(oxr_->session != XR_NULL_HANDLE);
279 CHECK_XR(xrEndSession(oxr_->session), "Failed to cleanly end the VR session.");
280}
281
283 const XrEventDataSessionStateChanged &lifecycle)
284{
285 oxr_->session_state = lifecycle.state;
286
287 /* Runtime may send events for apparently destroyed session. Our handle should be nullptr then.
288 */
289 assert(oxr_->session == XR_NULL_HANDLE || oxr_->session == lifecycle.session);
290
291 switch (lifecycle.state) {
292 case XR_SESSION_STATE_READY:
293 beginSession();
294 break;
295 case XR_SESSION_STATE_STOPPING:
296 endSession();
297 break;
298 case XR_SESSION_STATE_EXITING:
299 case XR_SESSION_STATE_LOSS_PENDING:
300 return SESSION_DESTROY;
301 default:
302 break;
303 }
304
305 return SESSION_KEEP_ALIVE;
306}
307 /* State Management */
309
310/* -------------------------------------------------------------------- */
313
314void GHOST_XrSession::prepareDrawing()
315{
316 assert(context_->getInstance() != XR_NULL_HANDLE);
317
318 std::vector<XrViewConfigurationView> view_configs;
319 uint32_t view_count;
320
321 /* Attempt to use quad view if supported. */
322 if (context_->isExtensionEnabled(XR_VARJO_QUAD_VIEWS_EXTENSION_NAME)) {
323 oxr_->view_type = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
324 }
325
326 oxr_->foveation_supported = context_->isExtensionEnabled(
327 XR_VARJO_FOVEATED_RENDERING_EXTENSION_NAME);
328
329 CHECK_XR(xrEnumerateViewConfigurationViews(
330 context_->getInstance(), oxr_->system_id, oxr_->view_type, 0, &view_count, nullptr),
331 "Failed to get count of view configurations.");
332 view_configs.resize(view_count, {XR_TYPE_VIEW_CONFIGURATION_VIEW});
333 CHECK_XR(xrEnumerateViewConfigurationViews(context_->getInstance(),
334 oxr_->system_id,
335 oxr_->view_type,
336 view_configs.size(),
337 &view_count,
338 view_configs.data()),
339 "Failed to get view configurations.");
340
341 /* If foveated rendering is used, query the foveated views. */
342 if (oxr_->foveation_supported) {
343 std::vector<XrFoveatedViewConfigurationViewVARJO> request_foveated_config{
344 view_count, {XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO, nullptr, XR_TRUE}};
345
346 auto foveated_views = std::vector<XrViewConfigurationView>(view_count,
347 {XR_TYPE_VIEW_CONFIGURATION_VIEW});
348
349 for (uint32_t i = 0; i < view_count; i++) {
350 foveated_views[i].next = &request_foveated_config[i];
351 }
352 CHECK_XR(xrEnumerateViewConfigurationViews(context_->getInstance(),
353 oxr_->system_id,
354 oxr_->view_type,
355 view_configs.size(),
356 &view_count,
357 foveated_views.data()),
358 "Failed to get foveated view configurations.");
359
360 /* Ensure swapchains have correct size even when foveation is being used. */
361 for (uint32_t i = 0; i < view_count; i++) {
362 view_configs[i].recommendedImageRectWidth = std::max(
363 view_configs[i].recommendedImageRectWidth, foveated_views[i].recommendedImageRectWidth);
364 view_configs[i].recommendedImageRectHeight = std::max(
365 view_configs[i].recommendedImageRectHeight,
366 foveated_views[i].recommendedImageRectHeight);
367 }
368 }
369
370 for (const XrViewConfigurationView &view_config : view_configs) {
371 oxr_->swapchains.emplace_back(*gpu_binding_, oxr_->session, view_config);
372 }
373
374 oxr_->views.resize(view_count, {XR_TYPE_VIEW});
375
376 draw_info_ = std::make_unique<GHOST_XrDrawInfo>();
377}
378
379void GHOST_XrSession::beginFrameDrawing()
380{
381 XrFrameWaitInfo wait_info = {XR_TYPE_FRAME_WAIT_INFO};
382 XrFrameBeginInfo begin_info = {XR_TYPE_FRAME_BEGIN_INFO};
383 XrFrameState frame_state = {XR_TYPE_FRAME_STATE};
384
385 /* TODO Blocking call. Drawing should run on a separate thread to avoid interferences. */
386 CHECK_XR(xrWaitFrame(oxr_->session, &wait_info, &frame_state),
387 "Failed to synchronize frame rates between Blender and the device.");
388
389 /* Check if we have foveation available for the current frame. */
390 draw_info_->foveation_active = false;
391 if (oxr_->foveation_supported) {
392 XrSpaceLocation render_gaze_location{XR_TYPE_SPACE_LOCATION};
393 CHECK_XR(xrLocateSpace(oxr_->combined_eye_space,
394 oxr_->view_space,
395 frame_state.predictedDisplayTime,
396 &render_gaze_location),
397 "Failed to locate combined eye space.");
398
399 draw_info_->foveation_active = (render_gaze_location.locationFlags &
400 XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) != 0;
401 }
402
403 CHECK_XR(xrBeginFrame(oxr_->session, &begin_info),
404 "Failed to submit frame rendering start state.");
405
406 draw_info_->frame_state = frame_state;
407
408 if (context_->isDebugTimeMode()) {
409 draw_info_->frame_begin_time = std::chrono::high_resolution_clock::now();
410 }
411}
412
414{
416 std::chrono::duration<double, std::milli> duration = std::chrono::high_resolution_clock::now() -
417 draw_info.frame_begin_time;
418 const double duration_ms = duration.count();
419 const int avg_frame_count = 8;
420 double avg_ms_tot = 0.0;
421
422 if (draw_info.last_frame_times.size() >= avg_frame_count) {
423 draw_info.last_frame_times.pop_front();
424 assert(draw_info.last_frame_times.size() == avg_frame_count - 1);
425 }
426 draw_info.last_frame_times.push_back(duration_ms);
427 for (double ms_iter : draw_info.last_frame_times) {
428 avg_ms_tot += ms_iter;
429 }
430
431 printf("VR frame render time: %.0fms - %.2f FPS (%.2f FPS 8 frames average)\n",
432 duration_ms,
433 1000.0 / duration_ms,
434 1000.0 / (avg_ms_tot / draw_info.last_frame_times.size()));
435}
436
437void GHOST_XrSession::endFrameDrawing(std::vector<XrCompositionLayerBaseHeader *> &layers)
438{
439 XrFrameEndInfo end_info = {XR_TYPE_FRAME_END_INFO};
440
441 end_info.displayTime = draw_info_->frame_state.predictedDisplayTime;
442 end_info.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
443 end_info.layerCount = layers.size();
444 end_info.layers = layers.data();
445
446 CHECK_XR(xrEndFrame(oxr_->session, &end_info), "Failed to submit rendered frame.");
447
448 if (context_->isDebugTimeMode()) {
449 print_debug_timings(*draw_info_);
450 }
451}
452
453void GHOST_XrSession::draw(void *draw_customdata)
454{
455 std::vector<XrCompositionLayerProjectionView>
456 projection_layer_views; /* Keep alive until #xrEndFrame() call! */
457 XrCompositionLayerProjection proj_layer;
458 std::vector<XrCompositionLayerBaseHeader *> layers;
459
460 beginFrameDrawing();
461
462 if (context_->getCustomFuncs().passthrough_enabled_fn(draw_customdata)) {
463 enablePassthrough();
464 if (oxr_->passthrough_supported) {
465 layers.push_back((XrCompositionLayerBaseHeader *)&oxr_->passthrough_layer);
466 }
467 else {
468 context_->getCustomFuncs().disable_passthrough_fn(draw_customdata);
469 }
470 }
471
472 if (draw_info_->frame_state.shouldRender) {
473 proj_layer = drawLayer(projection_layer_views, draw_customdata);
474 if (layers.size() > 0) {
475 proj_layer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
476 }
477 layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&proj_layer));
478 }
479
480 endFrameDrawing(layers);
481}
482
483static void ghost_xr_draw_view_info_from_view(const XrView &view, GHOST_XrDrawViewInfo &r_info)
484{
485 /* Set and convert to Blender coordinate space. */
486 copy_openxr_pose_to_ghost_pose(view.pose, r_info.eye_pose);
487
488 r_info.fov.angle_left = view.fov.angleLeft;
489 r_info.fov.angle_right = view.fov.angleRight;
490 r_info.fov.angle_up = view.fov.angleUp;
491 r_info.fov.angle_down = view.fov.angleDown;
492}
493
494void GHOST_XrSession::drawView(GHOST_XrSwapchain &swapchain,
495 XrSwapchainImageBaseHeader &swapchain_image,
496 XrCompositionLayerProjectionView &r_proj_layer_view,
497 const XrSpaceLocation &view_location,
498 const XrView &view,
499 uint32_t view_idx,
500 void *draw_customdata)
501{
502 r_proj_layer_view.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
503 r_proj_layer_view.pose = view.pose;
504 r_proj_layer_view.fov = view.fov;
505 swapchain.updateCompositionLayerProjectViewSubImage(r_proj_layer_view.subImage);
506
507 assert(view_idx < 256);
508 GHOST_XrDrawViewInfo draw_view_info = {};
509 draw_view_info.view_idx = char(view_idx);
510 draw_view_info.swapchain_format = swapchain.getFormat();
511 draw_view_info.expects_srgb_buffer = swapchain.isBufferSRGB();
512 draw_view_info.ofsx = r_proj_layer_view.subImage.imageRect.offset.x;
513 draw_view_info.ofsy = r_proj_layer_view.subImage.imageRect.offset.y;
514 draw_view_info.width = r_proj_layer_view.subImage.imageRect.extent.width;
515 draw_view_info.height = r_proj_layer_view.subImage.imageRect.extent.height;
516 copy_openxr_pose_to_ghost_pose(view_location.pose, draw_view_info.local_pose);
518
519 /* Draw! */
520 context_->getCustomFuncs().draw_view_fn(&draw_view_info, draw_customdata);
521 gpu_binding_->submitToSwapchainImage(swapchain_image, draw_view_info);
522}
523
524XrCompositionLayerProjection GHOST_XrSession::drawLayer(
525 std::vector<XrCompositionLayerProjectionView> &r_proj_layer_views, void *draw_customdata)
526{
527 XrViewLocateInfo viewloc_info = {XR_TYPE_VIEW_LOCATE_INFO};
528 XrViewLocateFoveatedRenderingVARJO foveated_info{
529 XR_TYPE_VIEW_LOCATE_FOVEATED_RENDERING_VARJO, nullptr, true};
530 XrViewState view_state = {XR_TYPE_VIEW_STATE};
531 XrCompositionLayerProjection layer = {XR_TYPE_COMPOSITION_LAYER_PROJECTION};
532 XrSpaceLocation view_location{XR_TYPE_SPACE_LOCATION};
533 uint32_t view_count;
534
535 viewloc_info.viewConfigurationType = oxr_->view_type;
536 viewloc_info.displayTime = draw_info_->frame_state.predictedDisplayTime;
537 viewloc_info.space = oxr_->reference_space;
538
539 if (draw_info_->foveation_active) {
540 viewloc_info.next = &foveated_info;
541 }
542
543 CHECK_XR(xrLocateViews(oxr_->session,
544 &viewloc_info,
545 &view_state,
546 oxr_->views.size(),
547 &view_count,
548 oxr_->views.data()),
549 "Failed to query frame view and projection state.");
550
551 assert(oxr_->swapchains.size() == view_count);
552
553 CHECK_XR(xrLocateSpace(
554 oxr_->view_space, oxr_->reference_space, viewloc_info.displayTime, &view_location),
555 "Failed to query frame view space");
556
557 r_proj_layer_views.resize(view_count);
558 std::vector<XrSwapchainImageBaseHeader *> swapchain_images;
559 swapchain_images.resize(view_count);
560
561 for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) {
562 GHOST_XrSwapchain &swapchain = oxr_->swapchains[view_idx];
563 swapchain_images[view_idx] = swapchain.acquireDrawableSwapchainImage();
564 }
565
566 gpu_binding_->submitToSwapchainBegin();
567 for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) {
568 GHOST_XrSwapchain &swapchain = oxr_->swapchains[view_idx];
569 XrSwapchainImageBaseHeader &swapchain_image = *swapchain_images[view_idx];
570 drawView(swapchain,
571 swapchain_image,
572 r_proj_layer_views[view_idx],
573 view_location,
574 oxr_->views[view_idx],
575 view_idx,
576 draw_customdata);
577 }
578 gpu_binding_->submitToSwapchainEnd();
579
580 for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) {
581 GHOST_XrSwapchain &swapchain = oxr_->swapchains[view_idx];
582 swapchain.releaseImage();
583 swapchain_images[view_idx] = nullptr;
584 }
585
586 layer.space = oxr_->reference_space;
587 layer.viewCount = r_proj_layer_views.size();
588 layer.views = r_proj_layer_views.data();
589
590 return layer;
591}
592
594{
595 return gpu_binding_ && gpu_binding_->needsUpsideDownDrawing(*gpu_ctx_);
596}
597 /* Drawing */
599
600/* -------------------------------------------------------------------- */
603
605{
606 if (oxr_->session == XR_NULL_HANDLE) {
607 return false;
608 }
609 switch (oxr_->session_state) {
610 case XR_SESSION_STATE_READY:
611 case XR_SESSION_STATE_SYNCHRONIZED:
612 case XR_SESSION_STATE_VISIBLE:
613 case XR_SESSION_STATE_FOCUSED:
614 return true;
615 default:
616 return false;
617 }
618}
619 /* State Queries */
621
622/* -------------------------------------------------------------------- */
631
632void GHOST_XrSession::bindGraphicsContext()
633{
634 const GHOST_XrCustomFuncs &custom_funcs = context_->getCustomFuncs();
635 assert(custom_funcs.gpu_ctx_bind_fn);
636 gpu_ctx_ = static_cast<GHOST_Context *>(custom_funcs.gpu_ctx_bind_fn());
637}
638
640{
641 const GHOST_XrCustomFuncs &custom_funcs = context_->getCustomFuncs();
642 if (custom_funcs.gpu_ctx_unbind_fn) {
643 custom_funcs.gpu_ctx_unbind_fn((GHOST_ContextHandle)gpu_ctx_);
644 }
645 gpu_ctx_ = nullptr;
646}
647 /* Graphics Context Injection */
649
650/* -------------------------------------------------------------------- */
654
655static GHOST_XrActionSet *find_action_set(OpenXRSessionData *oxr, const char *action_set_name)
656{
657 std::map<std::string, GHOST_XrActionSet>::iterator it = oxr->action_sets.find(action_set_name);
658 if (it == oxr->action_sets.end()) {
659 return nullptr;
660 }
661 return &it->second;
662}
663
664bool GHOST_XrSession::createActionSet(const GHOST_XrActionSetInfo &info)
665{
666 std::map<std::string, GHOST_XrActionSet> &action_sets = oxr_->action_sets;
667 if (action_sets.find(info.name) != action_sets.end()) {
668 return false;
669 }
670
671 XrInstance instance = context_->getInstance();
672
673 action_sets.emplace(
674 std::piecewise_construct, std::make_tuple(info.name), std::make_tuple(instance, info));
675
676 return true;
677}
678
679void GHOST_XrSession::destroyActionSet(const char *action_set_name)
680{
681 std::map<std::string, GHOST_XrActionSet> &action_sets = oxr_->action_sets;
682 /* It's possible nothing is removed. */
683 action_sets.erase(action_set_name);
684}
685
686bool GHOST_XrSession::createActions(const char *action_set_name,
687 uint32_t count,
688 const GHOST_XrActionInfo *infos)
689{
690 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
691 if (action_set == nullptr) {
692 return false;
693 }
694
695 XrInstance instance = context_->getInstance();
696
697 for (uint32_t i = 0; i < count; ++i) {
698 if (!action_set->createAction(instance, infos[i])) {
699 return false;
700 }
701 }
702
703 return true;
704}
705
706void GHOST_XrSession::destroyActions(const char *action_set_name,
707 uint32_t count,
708 const char *const *action_names)
709{
710 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
711 if (action_set == nullptr) {
712 return;
713 }
714
715 for (uint32_t i = 0; i < count; ++i) {
716 action_set->destroyAction(action_names[i]);
717 }
718}
719
720bool GHOST_XrSession::createActionBindings(const char *action_set_name,
721 uint32_t count,
722 const GHOST_XrActionProfileInfo *infos)
723{
724 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
725 if (action_set == nullptr) {
726 return false;
727 }
728
729 XrInstance instance = context_->getInstance();
730 XrSession session = oxr_->session;
731
732 for (uint32_t profile_idx = 0; profile_idx < count; ++profile_idx) {
733 const GHOST_XrActionProfileInfo &info = infos[profile_idx];
734
735 GHOST_XrAction *action = action_set->findAction(info.action_name);
736 if (action == nullptr) {
737 continue;
738 }
739
740 action->createBinding(instance, session, info);
741 }
742
743 return true;
744}
745
746void GHOST_XrSession::destroyActionBindings(const char *action_set_name,
747 uint32_t count,
748 const char *const *action_names,
749 const char *const *profile_paths)
750{
751 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
752 if (action_set == nullptr) {
753 return;
754 }
755
756 for (uint32_t i = 0; i < count; ++i) {
757 GHOST_XrAction *action = action_set->findAction(action_names[i]);
758 if (action == nullptr) {
759 continue;
760 }
761
762 action->destroyBinding(profile_paths[i]);
763 }
764}
765
767{
768 /* Suggest action bindings for all action sets. */
769 std::map<XrPath, std::vector<XrActionSuggestedBinding>> profile_bindings;
770 for (auto &[name, action_set] : oxr_->action_sets) {
771 action_set.getBindings(profile_bindings);
772 }
773
774 if (profile_bindings.size() < 1) {
775 return false;
776 }
777
778 XrInteractionProfileSuggestedBinding bindings_info{
779 XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
780 XrInstance instance = context_->getInstance();
781
782 for (auto &[profile, bindings] : profile_bindings) {
783 bindings_info.interactionProfile = profile;
784 bindings_info.countSuggestedBindings = uint32_t(bindings.size());
785 bindings_info.suggestedBindings = bindings.data();
786
787 CHECK_XR(xrSuggestInteractionProfileBindings(instance, &bindings_info),
788 "Failed to suggest interaction profile bindings.");
789 }
790
791 /* Attach action sets. */
792 XrSessionActionSetsAttachInfo attach_info{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO};
793 attach_info.countActionSets = uint32_t(oxr_->action_sets.size());
794
795 /* Create an aligned copy of the action sets to pass to xrAttachSessionActionSets(). */
796 std::vector<XrActionSet> action_sets(attach_info.countActionSets);
797 uint32_t i = 0;
798 for (auto &[name, action_set] : oxr_->action_sets) {
799 action_sets[i++] = action_set.getActionSet();
800 }
801 attach_info.actionSets = action_sets.data();
802
803 CHECK_XR(xrAttachSessionActionSets(oxr_->session, &attach_info),
804 "Failed to attach XR action sets.");
805
806 return true;
807}
808
809bool GHOST_XrSession::syncActions(const char *action_set_name)
810{
811 std::map<std::string, GHOST_XrActionSet> &action_sets = oxr_->action_sets;
812
813 XrActionsSyncInfo sync_info{XR_TYPE_ACTIONS_SYNC_INFO};
814 sync_info.countActiveActionSets = (action_set_name != nullptr) ? 1 :
815 uint32_t(action_sets.size());
816 if (sync_info.countActiveActionSets < 1) {
817 return false;
818 }
819
820 std::vector<XrActiveActionSet> active_action_sets(sync_info.countActiveActionSets);
821 GHOST_XrActionSet *action_set = nullptr;
822
823 if (action_set_name != nullptr) {
824 action_set = find_action_set(oxr_.get(), action_set_name);
825 if (action_set == nullptr) {
826 return false;
827 }
828
829 XrActiveActionSet &active_action_set = active_action_sets[0];
830 active_action_set.actionSet = action_set->getActionSet();
831 active_action_set.subactionPath = XR_NULL_PATH;
832 }
833 else {
834 uint32_t i = 0;
835 for (auto &[name, action_set] : action_sets) {
836 XrActiveActionSet &active_action_set = active_action_sets[i++];
837 active_action_set.actionSet = action_set.getActionSet();
838 active_action_set.subactionPath = XR_NULL_PATH;
839 }
840 }
841 sync_info.activeActionSets = active_action_sets.data();
842
843 CHECK_XR(xrSyncActions(oxr_->session, &sync_info), "Failed to synchronize XR actions.");
844
845 /* Update action states (i.e. Blender custom data). */
846 XrSession session = oxr_->session;
847 XrSpace reference_space = oxr_->reference_space;
848 const XrTime &predicted_display_time = draw_info_->frame_state.predictedDisplayTime;
849
850 if (action_set != nullptr) {
851 action_set->updateStates(session, reference_space, predicted_display_time);
852 }
853 else {
854 for (auto &[name, action_set] : action_sets) {
855 action_set.updateStates(session, reference_space, predicted_display_time);
856 }
857 }
858
859 return true;
860}
861
862bool GHOST_XrSession::applyHapticAction(const char *action_set_name,
863 const char *action_name,
864 const char *subaction_path,
865 const int64_t &duration,
866 const float &frequency,
867 const float &amplitude)
868{
869 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
870 if (action_set == nullptr) {
871 return false;
872 }
873
874 GHOST_XrAction *action = action_set->findAction(action_name);
875 if (action == nullptr) {
876 return false;
877 }
878
879 action->applyHapticFeedback(
880 oxr_->session, action_name, subaction_path, duration, frequency, amplitude);
881
882 return true;
883}
884
885void GHOST_XrSession::stopHapticAction(const char *action_set_name,
886 const char *action_name,
887 const char *subaction_path)
888{
889 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
890 if (action_set == nullptr) {
891 return;
892 }
893
894 GHOST_XrAction *action = action_set->findAction(action_name);
895 if (action == nullptr) {
896 return;
897 }
898
899 action->stopHapticFeedback(oxr_->session, action_name, subaction_path);
900}
901
902void *GHOST_XrSession::getActionSetCustomdata(const char *action_set_name)
903{
904 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
905 if (action_set == nullptr) {
906 return nullptr;
907 }
908
909 return action_set->getCustomdata();
910}
911
912void *GHOST_XrSession::getActionCustomdata(const char *action_set_name, const char *action_name)
913{
914 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
915 if (action_set == nullptr) {
916 return nullptr;
917 }
918
919 GHOST_XrAction *action = action_set->findAction(action_name);
920 if (action == nullptr) {
921 return nullptr;
922 }
923
924 return action->getCustomdata();
925}
926
927uint32_t GHOST_XrSession::getActionCount(const char *action_set_name)
928{
929 const GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
930 if (action_set == nullptr) {
931 return 0;
932 }
933
934 return action_set->getActionCount();
935}
936
937void GHOST_XrSession::getActionCustomdataArray(const char *action_set_name,
938 void **r_customdata_array)
939{
940 GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
941 if (action_set == nullptr) {
942 return;
943 }
944
945 action_set->getActionCustomdataArray(r_customdata_array);
946}
947 /* Actions */
949
950/* -------------------------------------------------------------------- */
954
955bool GHOST_XrSession::loadControllerModel(const char *subaction_path)
956{
957 if (!context_->isExtensionEnabled(XR_MSFT_CONTROLLER_MODEL_EXTENSION_NAME)) {
958 return false;
959 }
960
961 XrSession session = oxr_->session;
962 std::map<std::string, GHOST_XrControllerModel> &controller_models = oxr_->controller_models;
963 std::map<std::string, GHOST_XrControllerModel>::iterator it = controller_models.find(
964 subaction_path);
965
966 if (it == controller_models.end()) {
967 XrInstance instance = context_->getInstance();
968 it = controller_models
969 .emplace(std::piecewise_construct,
970 std::make_tuple(subaction_path),
971 std::make_tuple(instance, subaction_path))
972 .first;
973 }
974
975 it->second.load(session);
976
977 return true;
978}
979
980void GHOST_XrSession::unloadControllerModel(const char *subaction_path)
981{
982 std::map<std::string, GHOST_XrControllerModel> &controller_models = oxr_->controller_models;
983 /* It's possible nothing is removed. */
984 controller_models.erase(subaction_path);
985}
986
988{
989 XrSession session = oxr_->session;
990 std::map<std::string, GHOST_XrControllerModel>::iterator it = oxr_->controller_models.find(
991 subaction_path);
992 if (it == oxr_->controller_models.end()) {
993 return false;
994 }
995
996 it->second.updateComponents(session);
997
998 return true;
999}
1000
1001bool GHOST_XrSession::getControllerModelData(const char *subaction_path,
1002 GHOST_XrControllerModelData &r_data)
1003{
1004 std::map<std::string, GHOST_XrControllerModel>::iterator it = oxr_->controller_models.find(
1005 subaction_path);
1006 if (it == oxr_->controller_models.end()) {
1007 return false;
1008 }
1009
1010 it->second.getData(r_data);
1011
1012 return true;
1013}
1014 /* Controller Model */
1016
1017/* -------------------------------------------------------------------- */
1021
1022static PFN_xrCreatePassthroughFB g_xrCreatePassthroughFB = nullptr;
1023static PFN_xrCreatePassthroughLayerFB g_xrCreatePassthroughLayerFB = nullptr;
1024static PFN_xrPassthroughStartFB g_xrPassthroughStartFB = nullptr;
1025static PFN_xrPassthroughLayerResumeFB g_xrPassthroughLayerResumeFB = nullptr;
1026
1027static void init_passthrough_extension_functions(XrInstance instance)
1028{
1029 if (g_xrCreatePassthroughFB == nullptr) {
1030 INIT_EXTENSION_FUNCTION(xrCreatePassthroughFB);
1031 }
1032 if (g_xrCreatePassthroughLayerFB == nullptr) {
1033 INIT_EXTENSION_FUNCTION(xrCreatePassthroughLayerFB);
1034 }
1035 if (g_xrPassthroughStartFB == nullptr) {
1036 INIT_EXTENSION_FUNCTION(xrPassthroughStartFB);
1037 }
1038 if (g_xrPassthroughLayerResumeFB == nullptr) {
1039 INIT_EXTENSION_FUNCTION(xrPassthroughLayerResumeFB);
1040 }
1041}
1042
1043void GHOST_XrSession::enablePassthrough()
1044{
1045 if (!context_->isExtensionEnabled(XR_FB_PASSTHROUGH_EXTENSION_NAME)) {
1046 oxr_->passthrough_supported = false;
1047 return;
1048 }
1049
1050 if (oxr_->passthrough_layer.layerHandle != XR_NULL_HANDLE) {
1051 return; /* Already initialized */
1052 }
1053
1054 init_passthrough_extension_functions(context_->getInstance());
1055
1056 XrResult result;
1057
1058 XrPassthroughCreateInfoFB passthrough_create_info = {};
1059 passthrough_create_info.type = XR_TYPE_PASSTHROUGH_CREATE_INFO_FB;
1060 passthrough_create_info.next = nullptr;
1061 passthrough_create_info.flags |= XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB;
1062
1063 XrPassthroughFB passthrough_handle;
1064 result = g_xrCreatePassthroughFB(oxr_->session, &passthrough_create_info, &passthrough_handle);
1065
1066 XrPassthroughLayerCreateInfoFB passthrough_layer_create_info;
1067 passthrough_layer_create_info.type = XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB;
1068 passthrough_layer_create_info.next = nullptr;
1069 passthrough_layer_create_info.passthrough = passthrough_handle;
1070 passthrough_layer_create_info.flags |= XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB;
1071 passthrough_layer_create_info.purpose = XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB;
1072
1073 XrPassthroughLayerFB passthrough_layer_handle;
1075 oxr_->session, &passthrough_layer_create_info, &passthrough_layer_handle);
1076
1077 g_xrPassthroughStartFB(passthrough_handle);
1078 g_xrPassthroughLayerResumeFB(passthrough_layer_handle);
1079
1080 oxr_->passthrough_layer.type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB;
1081 oxr_->passthrough_layer.next = nullptr;
1082 oxr_->passthrough_layer.flags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
1083 oxr_->passthrough_layer.space = nullptr;
1084 oxr_->passthrough_layer.layerHandle = passthrough_layer_handle;
1085
1086 oxr_->passthrough_supported = (result == XR_SUCCESS);
1087}
1088 /* Meta Quest Passthrough */
static AppView * view
GHOST C-API function and type declarations.
std::unique_ptr< GHOST_IXrGraphicsBinding > GHOST_XrGraphicsBindingCreateFromType(GHOST_TXrGraphicsBinding type, GHOST_Context &context)
static void init_passthrough_extension_functions(XrInstance instance)
static void create_reference_spaces(OpenXRSessionData &oxr, const GHOST_XrPose &base_pose, bool isDebugMode)
static void print_debug_timings(GHOST_XrDrawInfo &draw_info)
static void ghost_xr_draw_view_info_from_view(const XrView &view, GHOST_XrDrawViewInfo &r_info)
static PFN_xrCreatePassthroughLayerFB g_xrCreatePassthroughLayerFB
static PFN_xrPassthroughLayerResumeFB g_xrPassthroughLayerResumeFB
static PFN_xrCreatePassthroughFB g_xrCreatePassthroughFB
static PFN_xrPassthroughStartFB g_xrPassthroughStartFB
static GHOST_XrActionSet * find_action_set(OpenXRSessionData *oxr, const char *action_set_name)
void copy_openxr_pose_to_ghost_pose(const XrPosef &oxr_pose, GHOST_XrPose &r_ghost_pose)
#define INIT_EXTENSION_FUNCTION(name)
#define CHECK_XR_ASSERT(call)
#define CHECK_XR(call, error_msg)
long long int int64_t
void updateStates(XrSession session, XrSpace reference_space, const XrTime &predicted_display_time)
GHOST_XrAction * findAction(const char *action_name)
bool createAction(XrInstance instance, const GHOST_XrActionInfo &info)
XrActionSet getActionSet() const
void getActionCustomdataArray(void **r_customdata_array)
uint32_t getActionCount() const
void destroyAction(const char *action_name)
bool createBinding(XrInstance instance, XrSession session, const GHOST_XrActionProfileInfo &info)
void destroyBinding(const char *profile_path)
void applyHapticFeedback(XrSession session, const char *action_name, const char *subaction_path_str, const int64_t &duration, const float &frequency, const float &amplitude)
void stopHapticFeedback(XrSession session, const char *action_name, const char *subaction_path_str)
Main GHOST container to manage OpenXR through.
XrInstance getInstance() const
const GHOST_XrCustomFuncs & getCustomFuncs() const
bool isExtensionEnabled(const char *ext) const
void destroyActionBindings(const char *action_set_name, uint32_t count, const char *const *action_names, const char *const *profile_paths)
void destroyActionSet(const char *action_set_name)
void draw(void *draw_customdata)
bool createActionSet(const GHOST_XrActionSetInfo &info)
void * getActionCustomdata(const char *action_set_name, const char *action_name)
void unloadControllerModel(const char *subaction_path)
void * getActionSetCustomdata(const char *action_set_name)
bool updateControllerModelComponents(const char *subaction_path)
bool createActionBindings(const char *action_set_name, uint32_t count, const GHOST_XrActionProfileInfo *infos)
GHOST_XrSession(GHOST_XrContext &xr_context)
void stopHapticAction(const char *action_set_name, const char *action_name, const char *subaction_path)
bool isRunning() const
LifeExpectancy handleStateChangeEvent(const XrEventDataSessionStateChanged &lifecycle)
void getActionCustomdataArray(const char *action_set_name, void **r_customdata_array)
bool loadControllerModel(const char *subaction_path)
bool syncActions(const char *action_set_name=nullptr)
bool needsUpsideDownDrawing() const
void start(const GHOST_XrSessionBeginInfo *begin_info)
void destroyActions(const char *action_set_name, uint32_t count, const char *const *action_names)
bool applyHapticAction(const char *action_set_name, const char *action_name, const char *subaction_path, const int64_t &duration, const float &frequency, const float &amplitude)
uint32_t getActionCount(const char *action_set_name)
bool getControllerModelData(const char *subaction_path, GHOST_XrControllerModelData &r_data)
bool createActions(const char *action_set_name, uint32_t count, const GHOST_XrActionInfo *infos)
GHOST_TXrSwapchainFormat getFormat() const
void updateCompositionLayerProjectViewSubImage(XrSwapchainSubImage &r_sub_image)
XrSwapchainImageBaseHeader * acquireDrawableSwapchainImage()
#define assert(assertion)
#define printf(...)
int count
const char * name
GHOST_XrGraphicsContextUnbindFn gpu_ctx_unbind_fn
GHOST_XrGraphicsContextBindFn gpu_ctx_bind_fn
std::chrono::high_resolution_clock::time_point frame_begin_time
XrFrameState frame_state
std::list< double > last_frame_times
XrCompositionLayerPassthroughFB passthrough_layer
std::map< std::string, GHOST_XrControllerModel > controller_models
XrViewConfigurationType view_type
std::map< std::string, GHOST_XrActionSet > action_sets
XrSessionState session_state
std::vector< GHOST_XrSwapchain > swapchains
std::vector< XrView > views
i
Definition text_draw.cc:230