| 1 | // SPDX-License-Identifier: LGPL-2.1-only |
| 2 | // Copyright (C) 2021 James Hogan <[email protected]> |
| 3 | |
| 4 | #define XR_USE_GRAPHICS_API_OPENGL |
| 5 | #include <openxr/openxr_platform.h> |
| 6 | |
| 7 | #include "ActionSet.h" |
| 8 | #include "Compositor.h" |
| 9 | #include "Session.h" |
| 10 | #include "GraphicsBinding.h" |
| 11 | |
| 12 | #include <osg/Notify> |
| 13 | |
| 14 | #include <cassert> |
| 15 | #include <vector> |
| 16 | |
| 17 | #ifdef OSGXR_USE_X11 |
| 18 | #include <osgViewer/api/X11/GraphicsWindowX11> |
| 19 | #include <GL/glx.h> |
| 20 | #endif // OSGXR_USE_X11 |
| 21 | |
| 22 | using namespace osgXR::OpenXR; |
| 23 | |
| 24 | Session::Session(System *system, |
| 25 | osgViewer::GraphicsWindow *window) : |
| 26 | _window(window), |
| 27 | _instance(system->getInstance()), |
| 28 | _system(system), |
| 29 | _session(XR_NULL_HANDLE), |
| 30 | _viewConfiguration(nullptr), |
| 31 | _actionSyncCount(0), |
| 32 | _state(XR_SESSION_STATE_UNKNOWN), |
| 33 | _running(false), |
| 34 | _exiting(false), |
| 35 | _lost(false), |
| 36 | _readSwapchainFormats(false), |
| 37 | _lastDisplayTime(0) |
| 38 | { |
| 39 | XrSessionCreateInfo createInfo = { XR_TYPE_SESSION_CREATE_INFO }; |
| 40 | createInfo.systemId = getXrSystemId(); |
| 41 | |
| 42 | // Get OpenGL graphics requirements |
| 43 | XrGraphicsRequirementsOpenGLKHR req; |
| 44 | req.type = XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR; |
| 45 | req.next = nullptr; |
| 46 | check(_instance->getOpenGLGraphicsRequirements(getXrSystemId(), &req), |
| 47 | "get OpenXR's OpenGL graphics requirements"); |
| 48 | // ... and pretty much ignore what it says |
| 49 | |
| 50 | osg::ref_ptr<GraphicsBinding> graphicsBinding = createGraphicsBinding(window); |
| 51 | if (graphicsBinding == nullptr) |
| 52 | { |
| 53 | OSG_WARN << "osgXR: Failed to get OpenXR graphics binding" << std::endl; |
| 54 | return; |
| 55 | } |
| 56 | |
| 57 | createInfo.next = graphicsBinding->getXrGraphicsBinding(); |
| 58 | |
| 59 | // GL context must not be bound in another thread |
| 60 | bool switchContext = shouldSwitchContext(); |
| 61 | if (switchContext) |
| 62 | makeCurrent(); |
| 63 | if (check(xrCreateSession(getXrInstance(), &createInfo, &_session), |
| 64 | "create OpenXR session")) |
| 65 | { |
| 66 | _instance->registerSession(this); |
| 67 | } |
| 68 | if (switchContext) |
| 69 | releaseContext(); |
| 70 | } |
| 71 | |
| 72 | Session::~Session() |
| 73 | { |
| 74 | releaseGLObjects(); |
| 75 | } |
| 76 | |
| 77 | void Session::releaseGLObjects(osg::State *state) |
| 78 | { |
| 79 | if (_session != XR_NULL_HANDLE) |
| 80 | { |
| 81 | _instance->unregisterSession(this); |
| 82 | _localSpace = nullptr; |
| 83 | // GL context must not be bound in another thread |
| 84 | check(xrDestroySession(_session), |
| 85 | "destroy OpenXR session"); |
| 86 | _session = XR_NULL_HANDLE; |
| 87 | _running = false; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | bool Session::check(XrResult result, const char *actionMsg) const |
| 92 | { |
| 93 | if (XR_FAILED(result)) |
| 94 | { |
| 95 | if (result == XR_ERROR_SESSION_LOST) |
| 96 | _lost = true; |
| 97 | } |
| 98 | return _system->check(result, actionMsg); |
| 99 | } |
| 100 | |
| 101 | void Session::addActionSet(ActionSet *actionSet) |
| 102 | { |
| 103 | assert(actionSet->getInstance() == getInstance()); |
| 104 | _actionSets.insert(actionSet); |
| 105 | } |
| 106 | |
| 107 | bool Session::attachActionSets() |
| 108 | { |
| 109 | assert(valid()); |
| 110 | if (_actionSets.empty()) |
| 111 | return false; |
| 112 | |
| 113 | // Construct vector of XrActionSets |
| 114 | std::vector<XrActionSet> actionSets; |
| 115 | actionSets.reserve(_actionSets.size()); |
| 116 | for (auto actionSet: _actionSets) |
| 117 | actionSets.push_back(actionSet->getXrActionSet()); |
| 118 | |
| 119 | XrSessionActionSetsAttachInfo attachInfo{ XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO }; |
| 120 | attachInfo.countActionSets = actionSets.size(); |
| 121 | attachInfo.actionSets = actionSets.data(); |
| 122 | |
| 123 | return check(xrAttachSessionActionSets(_session, &attachInfo), |
| 124 | "attach action sets to OpenXR session"); |
| 125 | } |
| 126 | |
| 127 | Path Session::getCurrentInteractionProfile(const Path &subactionPath) const |
| 128 | { |
| 129 | XrInteractionProfileState interactionProfile{ XR_TYPE_INTERACTION_PROFILE_STATE }; |
| 130 | |
| 131 | if (check(xrGetCurrentInteractionProfile(_session, subactionPath.getXrPath(), |
| 132 | &interactionProfile), |
| 133 | "get OpenXR current interaction profile")) |
| 134 | { |
| 135 | return Path(getInstance(), interactionProfile.interactionProfile); |
| 136 | } |
| 137 | return Path(); |
| 138 | } |
| 139 | |
| 140 | bool Session::getActionBoundSources(Action *action, |
| 141 | std::vector<XrPath> &sourcePaths) const |
| 142 | { |
| 143 | if (!valid()) |
| 144 | return false; |
| 145 | |
| 146 | // Count bound sources |
| 147 | XrBoundSourcesForActionEnumerateInfo enumerateInfo{ XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO }; |
| 148 | enumerateInfo.action = action->getXrAction(); |
| 149 | uint32_t count; |
| 150 | if (check(xrEnumerateBoundSourcesForAction(_session, &enumerateInfo, |
| 151 | 0, &count, nullptr), |
| 152 | "count OpenXR action bound sources")) |
| 153 | { |
| 154 | // Resize output buffer |
| 155 | sourcePaths.resize(count); |
| 156 | if (!count) |
| 157 | return true; |
| 158 | |
| 159 | // Fill buffer |
| 160 | if (check(xrEnumerateBoundSourcesForAction(_session, &enumerateInfo, |
| 161 | sourcePaths.size(), |
| 162 | &count, |
| 163 | sourcePaths.data()), |
| 164 | "enumerate OpenXR action bound sources")) |
| 165 | { |
| 166 | // Success! |
| 167 | if (count < sourcePaths.size()) |
| 168 | sourcePaths.resize(count); |
| 169 | return true; |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | // Failure! |
| 174 | return false; |
| 175 | } |
| 176 | |
| 177 | std::string Session::getInputSourceLocalizedName(XrPath sourcePath, |
| 178 | XrInputSourceLocalizedNameFlags whichComponents) const |
| 179 | { |
| 180 | if (!valid()) |
| 181 | return ""; |
| 182 | |
| 183 | XrInputSourceLocalizedNameGetInfo getInfo{ XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO }; |
| 184 | getInfo.sourcePath = sourcePath; |
| 185 | getInfo.whichComponents = whichComponents; |
| 186 | |
| 187 | uint32_t count; |
| 188 | if (!check(xrGetInputSourceLocalizedName(_session, &getInfo, |
| 189 | 0, &count, nullptr), |
| 190 | "size OpenXR input source localized name string")) |
| 191 | return ""; |
| 192 | std::vector<char> buffer(count); |
| 193 | if (!check(xrGetInputSourceLocalizedName(_session, &getInfo, |
| 194 | buffer.size(), &count, buffer.data()), |
| 195 | "get OpenXR input source localized name string")) |
| 196 | return ""; |
| 197 | |
| 198 | return buffer.data(); |
| 199 | } |
| 200 | |
| 201 | void Session::activateActionSet(ActionSet *actionSet, Path subactionPath) |
| 202 | { |
| 203 | assert(_actionSets.count(actionSet)); |
| 204 | _activeActionSets.insert(ActionSetSubactionPair(actionSet, subactionPath.getXrPath())); |
| 205 | } |
| 206 | |
| 207 | void Session::deactivateActionSet(ActionSet *actionSet, Path subactionPath) |
| 208 | { |
| 209 | _activeActionSets.erase(ActionSetSubactionPair(actionSet, subactionPath.getXrPath())); |
| 210 | } |
| 211 | |
| 212 | bool Session::syncActions() |
| 213 | { |
| 214 | if (!valid()) |
| 215 | return false; |
| 216 | |
| 217 | XrActionsSyncInfo syncInfo{ XR_TYPE_ACTIONS_SYNC_INFO }; |
| 218 | std::vector<XrActiveActionSet> actionSets; |
| 219 | if (!_activeActionSets.empty()) |
| 220 | { |
| 221 | // Construct vector of XrActionSets |
| 222 | actionSets.reserve(_activeActionSets.size()); |
| 223 | for (auto actionSet: _activeActionSets) |
| 224 | { |
| 225 | XrActiveActionSet activeActionSet; |
| 226 | activeActionSet.actionSet = actionSet.first->getXrActionSet(); |
| 227 | activeActionSet.subactionPath = actionSet.second; |
| 228 | actionSets.push_back(activeActionSet); |
| 229 | } |
| 230 | |
| 231 | syncInfo.countActiveActionSets = actionSets.size(); |
| 232 | syncInfo.activeActionSets = actionSets.data(); |
| 233 | |
| 234 | bool ret = check(xrSyncActions(_session, &syncInfo), |
| 235 | "sync action sets to OpenXR session"); |
| 236 | if (ret) |
| 237 | ++_actionSyncCount; |
| 238 | return ret; |
| 239 | } |
| 240 | else |
| 241 | { |
| 242 | return false; |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | const Session::SwapchainFormats &Session::getSwapchainFormats() const |
| 247 | { |
| 248 | if (!_readSwapchainFormats && valid()) |
| 249 | { |
| 250 | uint32_t formatCount; |
| 251 | if (check(xrEnumerateSwapchainFormats(_session, 0, &formatCount, nullptr), |
| 252 | "count OpenXR swapchain formats")) |
| 253 | { |
| 254 | if (formatCount) |
| 255 | { |
| 256 | _swapchainFormats.resize(formatCount); |
| 257 | if (!check(xrEnumerateSwapchainFormats(_session, formatCount, |
| 258 | &formatCount, _swapchainFormats.data()), |
| 259 | "enumerate OpenXR swapchain formats")) |
| 260 | { |
| 261 | _swapchainFormats.resize(0); |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | _readSwapchainFormats = true; |
| 267 | } |
| 268 | |
| 269 | return _swapchainFormats; |
| 270 | } |
| 271 | |
| 272 | Space *Session::getLocalSpace() |
| 273 | { |
| 274 | if (!_localSpace.valid()) |
| 275 | _localSpace = new Space(this, XR_REFERENCE_SPACE_TYPE_LOCAL); |
| 276 | |
| 277 | return _localSpace; |
| 278 | } |
| 279 | |
| 280 | void Session::updateVisibilityMasks(XrViewConfigurationType viewConfigurationType, |
| 281 | uint32_t viewIndex) |
| 282 | { |
| 283 | // Session must be started ... |
| 284 | if (!_viewConfiguration) |
| 285 | return; |
| 286 | // ... and with a matching view configuration |
| 287 | if (viewConfigurationType != _viewConfiguration->getType()) |
| 288 | return; |
| 289 | |
| 290 | if (viewIndex >= _viewConfiguration->getViews().size()) |
| 291 | return; |
| 292 | VisMaskGeometryView &visMaskView = _visMaskCache[viewIndex]; |
| 293 | |
| 294 | // Regenerate cached visibility mask geometries for this viewIndex |
| 295 | for (uint32_t visMaskType = 0; visMaskType < visMaskView.size(); ++visMaskType) |
| 296 | if (visMaskView[visMaskType].valid()) |
| 297 | getVisibilityMask(viewIndex, static_cast<XrVisibilityMaskTypeKHR>(1 + visMaskType), true); |
| 298 | } |
| 299 | |
| 300 | osg::ref_ptr<osg::Geometry> Session::getVisibilityMask(uint32_t viewIndex, |
| 301 | XrVisibilityMaskTypeKHR visibilityMaskType, |
| 302 | bool force) |
| 303 | { |
| 304 | if (!_viewConfiguration) |
| 305 | return nullptr; |
| 306 | if (viewIndex >= _viewConfiguration->getViews().size()) |
| 307 | return nullptr; |
| 308 | if (visibilityMaskType == 0 || visibilityMaskType > XR_VISIBILITY_MASK_TYPE_LINE_LOOP_KHR) |
| 309 | return nullptr; |
| 310 | |
| 311 | // Size cache to match number of views... |
| 312 | if (_visMaskCache.size() == 0) |
| 313 | _visMaskCache.resize(_viewConfiguration->getViews().size()); |
| 314 | // ... and number of vis mask types |
| 315 | VisMaskGeometryView &visMaskView = _visMaskCache[viewIndex]; |
| 316 | if (visMaskView.size() == 0) |
| 317 | visMaskView.resize(XR_VISIBILITY_MASK_TYPE_LINE_LOOP_KHR); |
| 318 | // Cache hit? |
| 319 | VisMaskGeometry &visMaskGeometry = visMaskView[visibilityMaskType - 1]; |
| 320 | if (!force && visMaskGeometry.valid()) |
| 321 | return visMaskGeometry; |
| 322 | |
| 323 | // Get counts of visibility mask |
| 324 | XrVisibilityMaskKHR visibilityMask{ XR_TYPE_VISIBILITY_MASK_KHR }; |
| 325 | XrResult res = xrGetVisibilityMask(*_viewConfiguration, viewIndex, |
| 326 | visibilityMaskType, &visibilityMask); |
| 327 | if (res != XR_ERROR_FUNCTION_UNSUPPORTED && |
| 328 | check(res, "size OpenXR visibility mask")) |
| 329 | { |
| 330 | osg::PrimitiveSet::Mode mode; |
| 331 | switch (visibilityMaskType) |
| 332 | { |
| 333 | case XR_VISIBILITY_MASK_TYPE_HIDDEN_TRIANGLE_MESH_KHR: |
| 334 | // fall through |
| 335 | case XR_VISIBILITY_MASK_TYPE_VISIBLE_TRIANGLE_MESH_KHR: |
| 336 | mode = osg::PrimitiveSet::TRIANGLES; |
| 337 | break; |
| 338 | case XR_VISIBILITY_MASK_TYPE_LINE_LOOP_KHR: |
| 339 | mode = osg::PrimitiveSet::LINE_LOOP; |
| 340 | break; |
| 341 | default: |
| 342 | return nullptr; |
| 343 | } |
| 344 | |
| 345 | // Allocate space for data |
| 346 | osg::ref_ptr<osg::Vec2Array> vertices = new osg::Vec2Array(visibilityMask.vertexCountOutput); |
| 347 | osg::ref_ptr<osg::DrawElementsUInt> indices = new osg::DrawElementsUInt(mode, visibilityMask.indexCountOutput); |
| 348 | |
| 349 | // Get the actual data |
| 350 | static_assert(sizeof((*vertices)[0]) == sizeof(XrVector2f)); |
| 351 | static_assert(sizeof((*indices)[0]) == sizeof(uint32_t)); |
| 352 | visibilityMask.vertexCapacityInput = vertices->size(); |
| 353 | visibilityMask.vertices = reinterpret_cast<XrVector2f *>(&vertices->front()); |
| 354 | visibilityMask.indexCapacityInput = indices->size(); |
| 355 | visibilityMask.indices = reinterpret_cast<uint32_t *>(&indices->front()); |
| 356 | XrResult res = xrGetVisibilityMask(*_viewConfiguration, viewIndex, |
| 357 | visibilityMaskType, &visibilityMask); |
| 358 | if (check(res, "get OpenXR visibility mask")) |
| 359 | { |
| 360 | if (!visMaskGeometry.valid()) |
| 361 | { |
| 362 | // Create a new geometry object |
| 363 | osg::Geometry *geometry = new osg::Geometry(); |
| 364 | geometry->setVertexArray(vertices); |
| 365 | geometry->addPrimitiveSet(indices); |
| 366 | visMaskGeometry = geometry; |
| 367 | return geometry; |
| 368 | } |
| 369 | else |
| 370 | { |
| 371 | // Update the existing geometry object |
| 372 | osg::Geometry *geometry = visMaskGeometry.get(); |
| 373 | geometry->setVertexArray(vertices); |
| 374 | geometry->setPrimitiveSet(0, indices); |
| 375 | return geometry; |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | return nullptr; |
| 381 | } |
| 382 | |
| 383 | bool Session::checkCurrent() const |
| 384 | { |
| 385 | #ifdef OSGXR_USE_X11 |
| 386 | // Ugly X11 specific hack |
| 387 | const auto *window = dynamic_cast<const osgViewer::GraphicsWindowX11*>(_window.get()); |
| 388 | return glXGetCurrentContext() == window->getContext(); |
| 389 | #else |
| 390 | return true; |
| 391 | #endif |
| 392 | } |
| 393 | |
| 394 | void Session::makeCurrent() const |
| 395 | { |
| 396 | #ifdef OSGXR_USE_X11 |
| 397 | _window->makeCurrentImplementation(); |
| 398 | #endif |
| 399 | } |
| 400 | |
| 401 | void Session::releaseContext() const |
| 402 | { |
| 403 | #ifdef OSGXR_USE_X11 |
| 404 | _window->releaseContextImplementation(); |
| 405 | #endif |
| 406 | } |
| 407 | |
| 408 | bool Session::begin(const System::ViewConfiguration &viewConfiguration) |
| 409 | { |
| 410 | _viewConfiguration = &viewConfiguration; |
| 411 | |
| 412 | XrSessionBeginInfo beginInfo{ XR_TYPE_SESSION_BEGIN_INFO }; |
| 413 | beginInfo.primaryViewConfigurationType = viewConfiguration.getType(); |
| 414 | if (check(xrBeginSession(_session, &beginInfo), |
| 415 | "begin OpenXR session")) |
| 416 | { |
| 417 | _running = true; |
| 418 | return true; |
| 419 | } |
| 420 | return false; |
| 421 | } |
| 422 | |
| 423 | void Session::end() |
| 424 | { |
| 425 | check(xrEndSession(_session), |
| 426 | "end OpenXR session"); |
| 427 | _running = false; |
| 428 | _viewConfiguration = nullptr; |
| 429 | _visMaskCache.resize(0); |
| 430 | } |
| 431 | |
| 432 | void Session::requestExit() |
| 433 | { |
| 434 | _exiting = true; |
| 435 | if (isRunning()) |
| 436 | check(xrRequestExitSession(_session), |
| 437 | "request OpenXR exit"); |
| 438 | } |
| 439 | |
| 440 | osg::ref_ptr<Session::Frame> Session::waitFrame() |
| 441 | { |
| 442 | if (_instance->lost()) |
| 443 | return nullptr; |
| 444 | |
| 445 | osg::ref_ptr<Frame> frame; |
| 446 | |
| 447 | XrFrameWaitInfo frameWaitInfo{ XR_TYPE_FRAME_WAIT_INFO }; |
| 448 | XrFrameState frameState; |
| 449 | frameState.type = XR_TYPE_FRAME_STATE; |
| 450 | frameState.next = nullptr; |
| 451 | if (check(xrWaitFrame(_session, &frameWaitInfo, &frameState), |
| 452 | "wait for OpenXR frame")) |
| 453 | { |
| 454 | frame = new Frame(this, &frameState); |
| 455 | _lastDisplayTime = frameState.predictedDisplayTime; |
| 456 | } |
| 457 | |
| 458 | return frame; |
| 459 | } |
| 460 | |
| 461 | Session::Frame::Frame(osg::ref_ptr<Session> session, XrFrameState *frameState) : |
| 462 | _session(session), |
| 463 | _time(frameState->predictedDisplayTime), |
| 464 | _period(frameState->predictedDisplayPeriod), |
| 465 | _shouldRender(frameState->shouldRender), |
| 466 | _osgFrameNumber(0), |
| 467 | _locatedViews(false), |
| 468 | _begun(false), |
| 469 | _envBlendMode(XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM) |
| 470 | { |
| 471 | } |
| 472 | |
| 473 | Session::Frame::~Frame() |
| 474 | { |
| 475 | } |
| 476 | |
| 477 | void Session::Frame::locateViews() |
| 478 | { |
| 479 | // Get view locations |
| 480 | XrViewLocateInfo locateInfo = { XR_TYPE_VIEW_LOCATE_INFO }; |
| 481 | locateInfo.viewConfigurationType = _session->getViewConfiguration()->getType(); |
| 482 | locateInfo.displayTime = _time; |
| 483 | locateInfo.space = _session->getLocalSpace()->getXrSpace(); |
| 484 | |
| 485 | _viewState = { XR_TYPE_VIEW_STATE }; |
| 486 | |
| 487 | uint32_t viewCount; |
| 488 | if (!check(xrLocateViews(_session->getXrSession(), &locateInfo, &_viewState, 0, &viewCount, nullptr), |
| 489 | "count OpenXR views")) |
| 490 | { |
| 491 | return; |
| 492 | } |
| 493 | _views.resize(viewCount); |
| 494 | for (auto &view: _views) |
| 495 | view = { XR_TYPE_VIEW }; |
| 496 | if (!check(xrLocateViews(_session->getXrSession(), &locateInfo, &_viewState, _views.size(), &viewCount, _views.data()), |
| 497 | "locate OpenXR views")) |
| 498 | { |
| 499 | return; |
| 500 | } |
| 501 | |
| 502 | _locatedViews = true; |
| 503 | } |
| 504 | |
| 505 | void Session::Frame::addLayer(osg::ref_ptr<CompositionLayer> layer) |
| 506 | { |
| 507 | _layers.push_back(layer); |
| 508 | } |
| 509 | |
| 510 | bool Session::Frame::begin() |
| 511 | { |
| 512 | XrFrameBeginInfo frameBeginInfo{ XR_TYPE_FRAME_BEGIN_INFO }; |
| 513 | return _begun = check(xrBeginFrame(_session->getXrSession(), &frameBeginInfo), |
| 514 | "begin OpenXR frame"); |
| 515 | } |
| 516 | |
| 517 | bool Session::Frame::end() |
| 518 | { |
| 519 | std::vector<const XrCompositionLayerBaseHeader *> layers; |
| 520 | layers.reserve(_layers.size()); |
| 521 | for (auto &layer: _layers) |
| 522 | layers.push_back(layer->getXr()); |
| 523 | |
| 524 | XrFrameEndInfo frameEndInfo{ XR_TYPE_FRAME_END_INFO }; |
| 525 | frameEndInfo.displayTime = _time; |
| 526 | frameEndInfo.environmentBlendMode = _envBlendMode; |
| 527 | frameEndInfo.layerCount = layers.size(); |
| 528 | frameEndInfo.layers = layers.data(); |
| 529 | |
| 530 | bool restoreContext = _session->shouldRestoreContext(); |
| 531 | bool ret = check(xrEndFrame(_session->getXrSession(), &frameEndInfo), |
| 532 | "end OpenXR frame"); |
| 533 | |
| 534 | if (restoreContext) |
| 535 | _session->makeCurrent(); |
| 536 | |
| 537 | return ret; |
| 538 | } |